我正在尝试使用 Keras 的 train_on_batch
函数训练神经网络。我有 39 个特征,并且希望每个批次包含 32 个样本。因此,每次训练迭代我都有一个包含 32 个 numpy 数组的列表。
以下是我的代码(这里的每个 batch_x 都是一个包含 32 个 numpy 数组的列表,每个数组包含 39 个特征):
input_shape = (39,)model = Sequential()model.add(Dense(39, input_shape=input_shape)) # 这里仅展示第一层... for batch_x, batch_y in train_gen: model.train_on_batch(batch_x, batch_y)
但突然我遇到了一个错误:
Exception: Error when checking model input: the list of Numpy arraysthat you are passing to your model is not the size the model expected.Expected to see 1 arrays but instead got the following list of 32 arrays:
我不是很确定哪里出了问题。
P.S. 我还尝试了不同的 input_shape
,例如 (32, 39), (39, 32) 等。
回答:
你不需要 32 个大小为 39 的数组,你需要一个大小为 (32, 39) 的数组。
因此,你必须将 input_shape 更改为 (None, 39),None 允许你动态更改批次大小,并将 batch_x 更改为形状为 (32, 39) 的 numpy 数组。