You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 15:36:18