【发布时间】:2025-12-04 04:45:02
【问题描述】:
我第一次尝试实施 Keras(对于这个愚蠢的问题,我很抱歉),这是一个更广泛的项目的一部分,目的是让 AI 学会玩 connect 4。作为其中的一部分,我通过了一个 NN a 6 *7 网格,它输出一个包含 7 个值的数组,给出游戏中每一列的选择概率。下面是 Model.summary() 方法的输出以了解更多细节:
______________________________________________________________
Layer (type) Output Shape Param #
=================================================================
flatten (Flatten) (None, 42) 0
_________________________________________________________________
dense (Dense) (None, 20) 860
_________________________________________________________________
dense_1 (Dense) (None, 20) 420
_________________________________________________________________
dense_2 (Dense) (None, 7) 147
=================================================================
Total params: 1,427
Trainable params: 1,427
Non-trainable params: 0
_________________________________________________________________
_________________________________________________________________
当我将形状为 (1, 6, 7) 的 numpy 数组传递给模型时,该模型将给出(目前是随机的)预测,但是,当我尝试使用形状为 (221, 6, 7) 的数组训练模型时) 的数据和形状数组 (221, 7) 的标签我得到这个错误:
ValueError: 检查目标时出错:预期dense_2 的形状为(1,),但得到的数组的形状为(7,)
这是我用来训练模型的代码(输出 (221, 6, 7) 和 (221, 7)):
board_tensor = np.array(full_board_list)
print(board_tensor.shape)
label_tensor = np.array(full_label_list)
print(label_tensor.shape)
self.model.fit(board_tensor, label_tensor)
这是我用来定义模型的代码:
self.model = keras.Sequential([
keras.layers.Flatten(input_shape=(6, 7)),
keras.layers.Dense(20, activation=tf.nn.relu),
keras.layers.Dense(20, activation=tf.nn.relu),
keras.layers.Dense(7, activation=tf.nn.softmax)])
self.model.compile(optimizer=tf.train.AdamOptimizer(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
(模型是 AI 对象的一部分,因此可以与其他类型的 AI 对象进行比较) 这是成功预测一批大小为 1 的代码,由代表棋盘的二维列表生成(它输出 (1, 6, 7) 和 (1, 7)):
input_tensor = np.array(board.board)
input_tensor = np.expand_dims(input_tensor, 0)
print(input_tensor.shape)
probability_distribution = self.model.predict(input_tensor)
print(probability_distribution.shape)
我意识到这个错误可能是由于我对 Keras 中期望给出的方法缺乏了解;所以作为一个小旁注,有没有人有任何好的,彻底的学习资源,真正让你了解每种方法在做什么(即不仅仅是告诉你输入哪个代码来制作图像识别器)这是可以理解的对于像我这样不熟悉 Keras 和 Tensorflow 的人?
提前非常感谢!
【问题讨论】:
标签: python numpy tensorflow keras training-data