ValueError:检查目标时出错:预期density_32的形状为(1,),但数组的形状为(10000,)

时间:2019-07-08 19:04:16

标签: python machine-learning keras

x具有shape=(33,10000,1),而y具有shape=(33,10000)。 但是当我运行代码时会弹出此错误:

ValueError: Error when checking input: expected lstm_40_input to have shape (1, 10000) but got array with shape (10000, 1)

我尝试在lstm层中更改input_shape=(10000,1),但随后出现此错误:

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

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM

x = np.reshape(x, (33, 10000, 1))

regressor = Sequential()
regressor.add(LSTM(units=4, activation='sigmoid', input_shape=(1, 10000)))
regressor.add(Dense(units=1))

regressor.compile(optimizer='adam', loss='categorical_crossentropy')

regressor.fit(x, y, batch_size=32, epochs=1)

1 个答案:

答案 0 :(得分:0)

我认为这里发生了两件事。如评论中所述,您的标签长度​​为10000,因此您似乎想对图像中的每个像素进行分类?有点奇怪另外,您正在使用分类交叉熵损失,但是密集层中只有一个输出值。如果要使用分类交叉熵,则最终密集层中的输出单位应该与类一样多,并且可能还应该使用softmax激活。

使用一些虚拟数据,我们将无法训练任何数据,但至少会告诉我们是否有错误。请注意,这里的目标是0或1,所以两个类别

x = np.random.randint(0, 2, size=(33, 10000, 1))
y = np.random.randint(0, 2, size=(33, 10000, 1))

我重写了您的网络,以将TimeDistributed()包裹在您的密集层周围,并在LSTM中设置return_sequences=True,以确保我们在时间序列的每个步骤中都能得到其输出。您的输入形状应为(10000, 1),或者通常为(sequence_length, num_features)。我还将units=2设置在密集层中,并将它的激活设置为softmax来执行分类任务。

regressor = Sequential()
regressor.add(LSTM(units=4,
                   activation='sigmoid',
                   input_shape=(10000, 1),
                   return_sequences=True))
regressor.add(TimeDistributed(Dense(units=2,
                                    activation='softmax')))

最后,我将损失设置为稀疏分类交叉熵,因为看起来您的标签不是使用常规分类交叉熵的正确维度。稀疏版本仅从标签的整数推断出一键编码。您可以尝试两者,但我认为您需要此尺寸来满足要求。

regressor.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
regressor.summary()
regressor.fit(x, y, batch_size=32, epochs=1)

网络摘要和培训结果:

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
lstm_15 (LSTM)               (None, 10000, 4)          96        
_________________________________________________________________
time_distributed_10 (TimeDis (None, 10000, 2)          10        
=================================================================
Total params: 106
Trainable params: 106
Non-trainable params: 0

_________________________________________________________________
Epoch 1/1
33/33 [==============================] - 14s 435ms/step - loss: 0.7048