Keras代码报错:'tuple'对象无法被解释为整数问题求助
问题解决:'tuple' object cannot be interpreted as an integer 错误
错误原因
错误出在up_c2_w = np.ones((1, 1, 1, pt_depth))这一行:pt_depth被赋值为base_pretrained_model.layers[-1].output_shape,而Keras中层的output_shape是一个元组(格式为(None, 高度, 宽度, 通道数)),并非整数。np.ones()需要整数来指定维度大小,传入元组会触发类型不匹配错误。
修复步骤
- 修正
pt_depth的取值,提取output_shape中的通道数(元组的最后一个元素):pt_depth = base_pretrained_model.layers[-1].output_shape[-1] - 后续
Conv2D(pt_depth, ...)的参数会因为pt_depth变为整数而正常工作。
完整修正后的关键代码片段
base_pretrained_model = VGG16(input_shape = t_x.shape[1:], include_top = False, weights = 'imagenet') base_pretrained_model.trainable = False # 修正:提取通道数(整数) pt_depth = base_pretrained_model.layers[-1].output_shape[-1] pt_features = base_pretrained_model(in_lay) from keras.layers import BatchNormalization bn_features = BatchNormalization()(pt_features) # ... 中间注意力层代码保持不变 ... # fan it out to all of the channels # 现在pt_depth是整数,np.ones可正常生成权重矩阵 up_c2_w = np.ones((1, 1, 1, pt_depth)) up_c2 = Conv2D(pt_depth, kernel_size = (1,1), padding = 'same', activation = 'linear', use_bias = False, weights = [up_c2_w]) up_c2.trainable = False attn_layer = up_c2(attn_layer)
额外说明
VGG16在include_top=False时,最后一层的输出通道数固定为512,你也可以直接写pt_depth = 512,但通过output_shape[-1]获取更灵活,适配不同的预训练模型。
内容的提问来源于stack exchange,提问作者Colab Limit
相关产品推荐
相关产品推荐

