我有這個自定義層,當我在模型中使用它時會出錯。
class NormalLayer(tf.keras.layers.Layer):
def __init__(self, color_space):
super(NormalLayer, self).__init__()
self.color_space = color_space
def call(self, image):
if self.color_space=="HSV":
image = tf.Variable(image)
image[:, :,0]=tf.divide(image[:, : ,0],180.)
image[:, :,1:3]=tf.divide(image[:, :, 1:3],255.)
return tf.convert_to_tensor(image)
return tf.keras.layers.Rescaling(1./255)(image)
這是錯誤:
File "<ipython-input-55-df46ae690c0b>", line 15, in call *
image = tf.Variable(image)
ValueError: Argument `initial_value` (Tensor("Placeholder:0", shape=(None, 224, 224, 3), dtype=float32))
could not be lifted out of a `tf.function`. (Tried to create variable with name='{name}').
To avoid this error, when constructing `tf.Variable`s inside of `tf.function` you can create the `initial_value` tensor in a `tf.init_scope` or pass a callable `initial_value` (e.g., `tf.Variable(lambda : tf.truncated_normal([10, 40]))`).
Please file a feature request if this restriction inconveniences you.
Call arguments received:
? image=tf.Tensor(shape=(None, 224, 224, 3), dtype=float32)
請為我修改此代碼。
uj5u.com熱心網友回復:
嘗試這樣的事情:
import numpy as np
import tensorflow as tf
class NormalLayer(tf.keras.layers.Layer):
def __init__(self, color_space):
super(NormalLayer, self).__init__()
self.color_space = color_space
def call(self, image):
if self.color_space=="HSV":
return tf.concat([tf.divide(image[:, :, : ,0, tf.newaxis], 180.), tf.divide(image[:, :, :, 1:3],255.)], axis=-1)
return tf.keras.layers.Rescaling(1./255)(image)
norm_layer = NormalLayer("HSV")
image = tf.random.normal((1, 244, 244, 3))
print(norm_layer(image).shape)
(1, 244, 244, 3)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/476644.html