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

构建首个神经网络遇ValueError:logits与label形状不匹配求助

问题解决:ValueError: logits and label must have the same shape

你的代码存在几个关键问题,直接导致了形状不匹配的错误,以下是具体修正方案:

核心错误点分析

  1. 任务类型与模型配置不匹配:鸢尾花是三分类任务,你却使用了二分类专属的binary_crossentropy损失函数和sigmoid激活函数,导致输出张量形状((None, 3))与标签形状((None,))无法对齐。
  2. 多余的Flatten层:模型前面全是全连接(Dense)层,输出已经是一维张量,添加Flatten()会打乱输出结构,完全没必要。

修正后的完整代码

import pandas as pd
from sklearn.model_selection import train_test_split

df = pd.read_csv('iris.csv')
X = pd.get_dummies(df.drop(['variety'], axis=1))
y = df['variety'].apply(lambda x: 0 if x=='Setosa' else (1 if x=='Versicolor' else 2))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2)
print(y_train.head())

from keras.models import Sequential
from keras.layers import Dense
from sklearn.metrics import accuracy_score

model = Sequential()
# 输入层+隐藏层:输入维度为特征数量,使用relu激活
model.add(Dense(units=8, activation='relu', input_dim=len(X_train.columns)))
# 输出层:3个神经元对应3类鸢尾花,softmax激活输出概率分布
model.add(Dense(units=3, activation='softmax'))
# 损失函数用sparse_categorical_crossentropy,适配整数类型的标签
model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])

model.fit(X_train, y_train, epochs=50, batch_size=1)

# 可选:测试集性能评估
y_pred = model.predict(X_test).argmax(axis=1)
print(f"测试集准确率: {accuracy_score(y_test, y_pred):.2f}")

额外可选方案

如果想使用categorical_crossentropy损失函数,需要先将整数标签转换为独热编码:

from keras.utils import to_categorical
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

此时模型编译时将损失函数改为categorical_crossentropy即可,其他部分无需调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:53:12