简体   繁体   中英

I have trouble with the shape of the input into an Keras model

I have a model with 5 input nodes and 1 output node.

model = keras.models.Sequential()
model.add(keras.layers.Dense(5, input_shape=(5, ), activation='relu'))
model.add(keras.layers.Dense(5, activation='relu'))
model.add(keras.layers.Dense(1, activation='exponential'))
model.compile(optimizer="sgd", loss="mean_squared_error")

I am trying to train a batch with these inputs.

input1 = [1, 4, 2, 4, 5]
input2 = [1, 4, 3, 5, 1]
input3 = [1, 4, 3, 3, 2]
input_batch = np.array([input1, input2, input3])

output1 = 2.5
output2 = 3.9
output3 = 1.3
output_batch = np.array([output1, output2, output3])

model.train_on_batch(input_batch, output_batch)

print(model.predict(np.array([1, 5, 2, 3, 1])))

This does not seem to be working so I need some help on how to shape the numpy array so that it fits into the model. Here's the error message:

ValueError: Error when checking input: expected dense_input to have shape (5,) but got array with shape (1,)

The last dimension of your output is 1, so you have to change labels. Another problem - predict working on batches. So you have to add a batch dimension.

Change these lines:

model.train_on_batch(input_batch, output_batch[..., tf.newaxis])
print(model.predict(np.array([[1, 5, 2, 3, 1]]))) # <= add brackets

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM