ValueError:检查输入时出错:预期density_1_input的形状为(24,),但数组的形状为(1,)

时间:2019-04-12 23:57:32

标签: python tensorflow machine-learning keras neural-network

我正在尝试对模型进行预测,所传递的数组的shape在打印时显示为(24,)。当尝试将数组传递到predict方法时,它会产生以下错误:ValueError: Error when checking input: expected dense_1_input to have shape (24,) but got array with shape (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

1 个答案:

答案 0 :(得分:1)

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)`