【问题标题】:Yet another "Error when checking target: expected dense_2 to have shape (4,) but got array with shape (1,)"另一个“检查目标时出错:预期 dense_2 的形状为 (4,),但得到的数组的形状为 (1,)”
【发布时间】:2021-01-21 04:15:03
【问题描述】:

我在 Python 3 中使用 Keras。我遇到的问题似乎与许多其他问题相似,我可以说我可能需要使用 Flatten(),尽管我不知道如何设置参数正确。我得到了错误:

ValueError:检查目标时出错:预期 dense_2 具有形状 (4,) 但得到了形状为 (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

任何帮助表示赞赏和感谢。

【问题讨论】:

    标签: python keras tf.keras


    【解决方案1】:

    考虑到您的模型摘要,模型需要形状为 (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 !
    

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 2020-06-16
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多