还有一个 "Error when checking target: expected dense_2 to have shape (4,) but got array with shape (1,)"

Yet another "Error when checking target: expected dense_2 to have shape (4,) but got array with shape (1,)"

我在 Python 中使用 Keras 3. 我遇到的问题似乎与许多其他问题相似,我能说的最好的是我可能需要使用 Flatten(),尽管我是没有看到如何正确设置参数。我收到错误:

ValueError: Error when checking target: expected dense_2 to have shape (4,) but got array with shape (1,)

我的数据不是图像(还),但它们是我已转换为数据帧的序列。

model = Sequential()
model.add(Dense(30, input_dim=16, activation='relu'))
model.add(Dense(len(TheBinsizeList), activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])


model.fit(Train_Columns, TrainTarget_Columns.to_frame(), epochs=100, batch_size=64)

print(Train_Columns.shape)
# Gives a value of (1627, 16)


print((TrainTarget_Columns.to_frame()).shape)
# Gives a value of (1627,1)

现在TrainTarget_Columns的值是这两个元组中的1627个:

(1494, 3) (1080, 2) (1863, 2) (919, 4) (1700, 2) (710, 4) (1365, 4) (1815, 3) (1477, 2) (1618, 1)...

主题编号是每个小管中的第一个条目,第二个条目是作为训练目标的值。

虽然我看到在 dense_2 中将 TheBinsizeList 从 4 更改为 2 会导致预期形状从 (4,) 变为 (2,),但我不知道如何使用 Flatten(如果是需要什么)以正确格式化值。

Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_1 (Dense)              (None, 30)                510       
_________________________________________________________________
dense_2 (Dense)              (None, 4)                 124       
=================================================================
Total params: 634
Trainable params: 634
Non-trainable params: 0

感谢任何帮助。

考虑到您的模型摘要,该模型需要一个形状为 (batch_size, 16) 的输入和一个形状为 (batch_size, 4) 的目标。

如果你的目标形状是(1627,1),那就是你的问题。

解决方案:将其更改为一个热变量(例如使用tf.one_hot(y, n_classes))并且错误应该消失

import numpy as np
import tensorflow as tf

input_dim = 16
hidden_dim = 30
n_classes = 4

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(hidden_dim, input_dim=input_dim, activation='relu'))
model.add(tf.keras.layers.Dense(n_classes, input_dim=hidden_dim, activation='relu'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

X = np.random.randn(100, input_dim)
y = np.random.randint(0, n_classes, size=(100,))

model.fit(X, y)
# ValueError: Shapes (None, 1) and (None, 4) are incompatible

y = tf.one_hot(y, n_classes)
model.fit(X, y)
# Works !