gpt4 book ai didi

python - ValueError : Error when checking target: expected dense_3 to have shape (1, ) 但得到形状为 (6,) 的数组

转载 作者:行者123 更新时间:2023-11-28 18:05:27 25 4
gpt4 key购买 nike

我正在尝试使用以下 ANN 模型运行多类分类:

classifier = Sequential()
classifier.add(Dense(units = 9, kernel_initializer = 'uniform', activation = 'relu', input_dim = 18))
classifier.add(Dense(units = 9, kernel_initializer = 'uniform', activation = 'relu'))
classifier.add(Dense(units = 9, kernel_initializer = 'uniform', activation = 'relu'))
classifier.add(Dense(units = 6 ,kernel_initializer = 'uniform', activation = 'softmax'))
classifier.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])
classifier.fit(X_train, y_train, batch_size = 10, epochs = 100)
y_pred = classifier.predict(X_test)

X_train 的格式是:

[[31 8 27 ... 2 7 5]
[31 8 11 ... 1 9 3]
[6 0 4 ... 1 9 3]
...
[55 55 134 ... 5 5 6]
[41 9 111 ... 1 3 0]
[19 9 28 ... 3 0 0]]

y_train 是:

[[0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1. 0.]
...
[0. 0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0. 1.]]

X_train 的形状是 (352, 18),y_train 的形状是 (352, 6),X_test 的形状是 (152, 18)。

运行时出现如下错误:

Traceback (most recent call last):
File "H:\p36564\Project ZS\tst1.py", line 110, in <module>
classifier.fit(X_train, y_train, batch_size = 10, epochs = 100)
File "H:\p36564\lib\site-packages\keras\engine\training.py", line 950, in fit
batch_size=batch_size)
File "H:\p36564\lib\site-packages\keras\engine\training.py", line 787, in _standardize_user_data
exception_prefix='target')
File "H:\p36564\lib\site-packages\keras\engine\training_utils.py", line 137, in standardize_input_data
str(data_shape))
ValueError: Error when checking target: expected dense_3 to have shape (1,) but got array with shape (6,)

此错误的可能原因是什么?任何帮助,将不胜感激。

最佳答案

根据您提供的 y_train 形状,使用 categorical_crossentropy 作为损失函数,而不是 sparse_categorical_crossentropy。您的 y_train 是单热编码的,而不是稀疏编码的。在您的情况下,稀疏编码是一个如下所示的数组:

[3, 4, 4, ..., 5, 5, 5]

要亲自尝试一下,请将 y_train 转换为稀疏编码,如下所示:

y_train_ = np.argmax(y_train, axis=1)

这将作为损失函数与 sparse_categorical_crossentropy 一起使用(无需更改模型架构!)

关于python - ValueError : Error when checking target: expected dense_3 to have shape (1, ) 但得到形状为 (6,) 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53697858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com