我想在Google Colab中使用迁移学习创建一个自定义模型
import tensorflow as tf
from tensorflow.keras.layers import Conv2D
from tensorflow.python.keras.applications.xception import Xception
class MyModel(tf.keras.Model):
def __init__(self, input_shape, num_classes=5, dropout_rate=0.5):
super(MyModel, self).__init__()
self.weight_dict = {}
self.weight_dict['backbone'] = Xception(input_shape=input_shape, weights='imagenet', include_top=False)
self.weight_dict['outputs'] = Conv2D(num_classes, (1, 1), padding="same", activation="softmax")
self.build((None,) + input_shape)
def call(self, inputs, training=False):
self.weight_dict['backbone'].trainable = False
x = self.weight_dict['backbone'](inputs)
x = self.weight_dict['outputs'](x)
return x
model = MyModel(input_shape=(256, 256, 3))
model.save('./saved')
但是,我遇到了以下错误:
ValueError: Model `<__main__.MyModel object at 0x7fc66134bdd0>` cannot be saved because the input shapes have not been set. Usually, input shapes are automatically determined from calling `.fit()` or `.predict()`. To manually set the shapes, call `model.build(input_shape)`.
是的,没有对.fit()
或.predict()
的调用。但是在类的__init__()
方法中有一个对.build
的调用。我该怎么办
如果尚未构建该层,compute_output_shape将在该层上调用build。这假设该层稍后将与与提供的输入形状匹配的输入一起使用
工作代码如下所示
输出:
有关更多信息,请参阅here
相关问题 更多 >
编程相关推荐