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

Tensorflow中DenseNet配置是否有误?仅特定multiplier值可训练

问题原因分析

你对DenseNet201的使用存在两处核心错误,直接导致了形状不匹配报错:

  • 错误1:include_top=False + pooling=None的配置下,DenseNet201输出的是4维特征张量,形状为(batch_size, 4, 4, 1920)(对应你128x128的输入),而你传入的标签是1维的(batch_size,)格式,二者形状不匹配,无法直接计算二分类交叉熵损失。
  • 错误2:include_top=False时,classes=2参数完全不生效,该参数仅在保留顶层分类层(include_top=True)时生效,你当前的模型根本没有分类输出头,无法输出二分类预测值。

你遇到的部分multiplier值能运行的情况属于张量广播的巧合,本质是计算逻辑完全错误的无效训练,没有实际意义。不同环境下能运行的multiplier值不同,是不同TensorFlow版本/硬件对广播逻辑的边缘处理有差异导致的。

修正方案

你需要在DenseNet201的卷积输出后添加全局池化层和二分类头,修正后的代码示例如下:

import numpy as np
import tensorflow as tf
from tensorflow.keras.applications.densenet import DenseNet201
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.losses import BinaryCrossentropy
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense
from tensorflow.keras.models import Sequential

random_array = np.random.rand(128,128,3)
image = tf.convert_to_tensor(random_array)
label = tf.constant(0)

# 基础模型
base_model = DenseNet201(
    include_top=False, 
    weights='imagenet', 
    input_shape=(128, 128, 3), 
    pooling=None
)
# 添加分类头
model = Sequential([
    base_model,
    GlobalAveragePooling2D(), # 把4维特征压缩为2维 (batch_size, 1920)
    Dense(1, activation='sigmoid') # 二分类输出头
])

model.compile(
    optimizer=Adam(),
    loss=BinaryCrossentropy(),
    metrics=['accuracy'],
)

for multiplier in range(1,20):
    print(f"Using multiplier {multiplier}")
    x_train = np.array([image]*multiplier)
    y_train = np.array([label]*multiplier)
    try: 
        model.fit(x=x_train,y=y_train, epochs=2, verbose=0)
        print("Training success")
    except Exception as e:
        print(f"Not training... Error: {e}")
        pass
额外注意事项
  • 你的测试样本只有1张重复的图和1个标签,仅能用来验证模型能不能跑,训练出来的模型没有实际预测能力,实际使用时需要替换为真实标注的数据集。
  • 如果需要保留include_top=True,需要把输入尺寸调整为DenseNet默认的224x224,否则预训练权重的形状和输入不匹配,无法正常加载。

内容的提问来源于stack exchange,提问作者Steffen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:45:10