在Google Colab构建深度学习模型时遇'Functional'不可下标错误
TypeError: 'Functional' object is not subscriptable 解决方法
错误出在for layer in base_model[:]:这一行——MobileNet实例化得到的base_model是Functional类型的模型对象,不支持下标切片访问。要遍历模型的所有层,需使用模型的layers属性,它会返回模型所有层的列表。
修正后的完整代码:
def model_maker(): base_model = MobileNet(include_top=False, input_shape = (IMG_WIDTH,IMG_HEIGHT,3)) # 遍历模型所有层并冻结 for layer in base_model.layers: layer.trainable = False input = Input(shape=(IMG_WIDTH,IMG_HEIGHT,3)) custom_model = base_model(input) custom_model = GlobalAveragePooling2D()(custom_model) custom_model = Dense(64,activation='relu')(custom_model) custom_model = Dropout(0.5)(custom_model) predictions = Dense(NUM_CLASSES,activation='softmax')(custom_model) return Model(inputs=input,outputs=predictions) # 调用模型 model = model_maker() model.compile(loss='categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(0.001), metrics=['acc'])
另外提供一种更简洁的冻结方式:无需循环遍历每一层,直接设置base_model.trainable = False即可冻结整个基础模型的所有层,代码更精简:
def model_maker(): base_model = MobileNet(include_top=False, input_shape = (IMG_WIDTH,IMG_HEIGHT,3)) # 直接冻结整个基础模型 base_model.trainable = False input = Input(shape=(IMG_WIDTH,IMG_HEIGHT,3)) custom_model = base_model(input) custom_model = GlobalAveragePooling2D()(custom_model) custom_model = Dense(64,activation='relu')(custom_model) custom_model = Dropout(0.5)(custom_model) predictions = Dense(NUM_CLASSES,activation='softmax')(custom_model) return Model(inputs=input,outputs=predictions)
内容的提问来源于stack exchange,提问作者Mainland
相关产品推荐
相关产品推荐

