ValueError: Error when checking target: expected dense_22 to have shape (100, 50) but got array with shape (1, 50)

ValueError: Error when checking target: expected dense_22 to have shape (100, 50) but got array with shape (1, 50)

我正在训练一个神经网络来预测一组文档的文档频率。

因此,主要思想是将包含 100 个文档和 50 个标记的矩阵映射到相应的文档频率数组。

X = (n_samples, 100, 50) -> y = (n_samples, 1, 50)

我的代码是:

model = Sequential()
model.add(Dense(50, activation='sigmoid', input_shape=(100,50)))
model.add(Dense(50))
model.compile(optimizer='rmsprop', loss='mse')
model.fit(X_train, y_train, epochs=50)

但是我得到一个错误:

ValueError: Error when checking target: expected dense_22 to have shape (100, 50) but got array with shape (1, 50)

那是因为你的输入是二维的所以你的模型总结如下。

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_1 (Dense)              (None, 100, 50)           2550      
_________________________________________________________________
dense_2 (Dense)              (None, 100, 50)           2550      
=================================================================
Total params: 5,100
Trainable params: 5,100
Non-trainable params: 0
_________________________________________________________________

尝试在 dense_1dense_2 之后重塑张量形状,方法是在第二个轴上取 sum/average 以获得与 Y 相同的形状。

这是我的例子,供大家参考

我写了一个自定义求和函数来对第二个轴求和,使 (None, 100, 50) 的张量为 (None, 1, 50)。然后,添加另一个 Dense 层。

import keras.backend as K
from keras.layers import Dense, Lambda
from keras.models import Sequential

def mysum(x): 
    return  K.sum(x, axis=1, keepdims=True) 

def mysum_output_shape(input_shape): 
    shape = list(input_shape) 
    print(shape)
    shape[1] = 1 
    return tuple(shape) 

# randomly generate data
import numpy as np
X_train = np.random.normal(0, 1, (50,100,50))
y_train = np.ones((50, 1, 50))

model = Sequential()
model.add(Dense(50, activation='sigmoid', input_shape=(100,50)))
model.add(Lambda(mysum, output_shape=mysum_output_shape)) 
model.add(Dense(50))
model.compile(optimizer='rmsprop', loss='mse')
model.fit(X_train, y_train, epochs=50)

重要的是要了解您的输入是什么以及张量如何通过每一层进行转换。希望这对您有所帮助!