Reputation: 398
I'm trying to make a prediction with my model, the shape
of the array that I am passing in shows as (24,)
when printed. When trying to pass in the array into the predict
method, it generates this error: ValueError: Error when checking input: expected dense_1_input to have shape (24,) but got array with shape (1,)
, however i know that the shape of my array is (24,)
. Why is it still giving an error?
for reference, here is my model:
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'])
and that MySequential
class is here, it is a subclass of keras.models.Sequential
:
class MySequential(Sequential):
score = 0
def set_score(self, score):
self.score = score
def get_score(self):
return self.score
the loop I'am running it in:
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()
Here is the full error-stack
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
Upvotes: 2
Views: 2703
Reputation: 33460
The input_shape
argument specifies the input shape of one of the samples. So when you set it as (24,)
it means each of your input samples has a shape of (24,)
. But you must consider that the models get batches of samples as their input. Therefore, their input shape is of the form (num_samples, ...)
. Since you want to feed your model with only one sample, your input array must have a shape of (1, 24)
. So you need to reshape your current array or add a new axis to the beginning:
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)`
Upvotes: 3