我有如下代碼序列。在那里,我嘗試通過使用 tensorflow模型類進行子類化來包裝該代碼。但是我收到以下錯誤。任何幫助都適用于解決這些錯誤。先感謝您
代碼序列
input_tensor = Input(shape=(720, 540, 2))
base_model = ResNet50V2(input_tensor=input_tensor, include_top=False, weights=None, classes=4)
x = base_model.output
x = GlobalAveragePooling2D()(x)
predictions = Dense(4, activation= 'sigmoid')(x)
model = Model(inputs = base_model.input, outputs = predictions)
嘗試模型類
類StreoModel(tf.keras.Model):
def __init__(self):
super(StreoModel, self).__init__()
self.dense1 = Dense(4, activation='sigmoid')
def call(self, inputs):
input_tensor = Input(shape=(720, 540, 2))
x = ResNet50V2(input_tensor=input_tensor, include_top=False, weights=None, classes=4)
x= x.output
x = GlobalAveragePooling2D()(x)
predictions = self.dense1(x)
return predictions
錯誤日志:
TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model.
uj5u.com熱心網友回復:
我認為問題在于您將資料傳遞給ResNet50V2. 嘗試定義一個簡單的子類模型,如下所示:
class StreoModel(tf.keras.Model):
def __init__(self):
super(StreoModel, self).__init__()
self.resnet_v2 = tf.keras.applications.resnet_v2.ResNet50V2(include_top=False, weights=None, classes=4, input_shape=(720, 540, 2))
self.resnet_v2.trainable = True
x= self.resnet_v2.output
x = tf.keras.layers.GlobalAveragePooling2D()(x)
output = tf.keras.layers.Dense(4, activation='softmax')(x)
self.model = tf.keras.Model(self.resnet_v2.input, output)
請注意,我洗掉了您的輸入層并將輸入形狀添加到ResNet50V2. 根據檔案,您應該指定 input_shape if include_top=False。我還將您的輸出激活函式更改為softmax,因為您要處理 4 個類。
然后使用它:
sm = StreoModel()
sm.model(np.random.random((1, 720, 540, 2)))
# <tf.Tensor: shape=(1, 4), dtype=float32, numpy=array([[0.25427648, 0.25267935, 0.23970276, 0.2533414 ]], dtype=float32)>
如果你想用一個call方法定義你的模型,那么你可以這樣做:
class StreoModel(tf.keras.Model):
def __init__(self):
super(StreoModel, self).__init__()
self.dense = tf.keras.layers.Dense(4, activation='softmax')
self.resnet = tf.keras.applications.resnet_v2.ResNet50V2(include_top=False, weights=None, classes=4, input_shape=(720, 540, 2))
self.pooling = tf.keras.layers.GlobalAveragePooling2D()
def call(self, inputs):
x = self.resnet(inputs)
x = self.pooling(x)
predictions = self.dense(x)
return predictions
并像這樣使用它:
sm = StreoModel()
sm(np.random.random((1, 720, 540, 2)))
# <tf.Tensor: shape=(1, 4), dtype=float32, numpy=array([[0.25062975, 0.2428435 , 0.25178066, 0.25474608]], dtype=float32)>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/323905.html
