python - ValueError : Error when checking input: expected dense_1_input to have shape (24, )但得到形状为(1,)的数组

标签 python tensorflow machine-learning keras neural-network

我正在尝试使用我的模型进行预测,我传入的数组的 shape 在打印时显示为 (24,)。当尝试将数组传递到 predict 方法时,它会生成以下错误:ValueError: 检查输入时出错:预期的 dendense_1_input 具有形状 (24,),但得到的数组具有形状 (1 ,),但是我知道我的数组的形状是(24,)。为什么还是报错?

作为引用,这是我的模型:

model = MySequential()
model.add(Dense(units=128, activation='relu', input_shape=(24,)))
model.add(Dense(128, activation='relu'))
model.add(Dense(action_size, activation='softmax'))
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

MySequential 类在这里,它是 keras.models.Sequential 的子类:

class MySequential(Sequential):
    score = 0
    def set_score(self, score):
        self.score = score
    def get_score(self):
        return self.score

我运行它的循环:

for i in range(100):
    new_model = create_model(action_size)
    new_model.__class__ = Sequential
    reward = 0
    state = env.reset()
    while True:
        env.render()
        print(state.shape)
        input_arr = state
        input_arr = np.reshape(input_arr, (1, 24))
        action = new_model.predict(input_arr)
        state, reward, done, info = env.step(action)
        if done:
            break
    env.reset()

这是完整的错误堆栈

Traceback (most recent call last):
  File "BipedalWalker.py", line 79, in <module>
    state, reward, done, info = env.step(action)
  File "/Users/arjunbemarkar/Python/MachineLearning/gym/gym/wrappers/time_limit.py", line 31, in step
    observation, reward, done, info = self.env.step(action)
  File "/Users/arjunbemarkar/Python/MachineLearning/gym/gym/envs/box2d/bipedal_walker.py", line 385, in step
    self.joints[0].motorSpeed     = float(SPEED_HIP     * np.sign(action[0]))
TypeError: only size-1 arrays can be converted to Python scalars

最佳答案

input_shape 参数指定其中一个样本的输入形状。因此,当您将其设置为 (24,) 时,这意味着每个输入样本的形状为 (24,)。但您必须考虑到模型会获取批量样本作为输入。因此,它们的输入形状的形式为(num_samples, ...)。由于您只想为模型提供一个样本,因此您的输入数组的形状必须为 (1, 24)。因此,您需要重新调整当前数组的形状或在开头添加一个新轴:

import numpy as np

# either reshape it
input_arr = np.reshape(input_arr, (1, 24))

# or add a new axis to the beginning
input_arr = np.expand_dims(input_arr, axis=0)

# then call the predict method
preds = model.predict(input_arr)  # Note that the `preds` would have a shape of `(1, action_size)`

关于python - ValueError : Error when checking input: expected dense_1_input to have shape (24, )但得到形状为(1,)的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55660786/

相关文章:

python - tf-nightly-gpu 和 tensorflow-gpu 有什么区别

node.js - 转换 tf.fromPixels() 创建的张量时遇到问题

python - 验证损失低于训练损失训练 LSTM

python - Tensorflow 没有重新识别一个热编码标签

python - 为什么归一化范围不在0和1之间?

python - 如何使用 Python 在 Windows 命令提示符下使用颜色?

python - 如何使用 FlaskClient 测试分段上传(用于单元测试)

python - 添加文件名作为 CSV 文件的最后一列

python - Pandas:如何将字符串转换为DataFrame

machine-learning - K 倍验证与随机采样 k 次