我知道之前曾有人问过这个问题,但是我无法解决他们。
所以
state is [[ 0.2]
[ 10. ]
[ 1. ]
[-10.5]
[ 41.1]]
和
(5, 1) # np.shape(state)
当model.predict(state)抛出时
ValueError:检查输入时出错:预期density_1_input具有 3维,但数组的形状为(5,1)
但是...
model = Sequential()
model.add(Dense(5,activation='relu',input_shape=(5,1)))
我的第一层模型的input_shape =(5,1)等于我通过的状态的形状。
在此之后,我还有2层以上的密集层。
print(model.summary())
// output
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_1 (Dense) (None, 5, 5) 10
_________________________________________________________________
dropout_1 (Dropout) (None, 5, 5) 0
_________________________________________________________________
dense_2 (Dense) (None, 5, 5) 30
_________________________________________________________________
dropout_2 (Dropout) (None, 5, 5) 0
_________________________________________________________________
dense_3 (Dense) (None, 5, 3) 18
=================================================================
model = Sequential()
model.add(Dense(5,activation='relu',input_shape=(5,1)))
model.add(Dropout(0.2))
# model.add(Flatten())
model.add(Dense(5,activation='relu'))
model.add(Dropout(0.2))
# model.add(Flatten())
model.add(Dense(3,activation='softmax'))
model.compile(loss="mse", optimizer=Adam(lr=0.001), metrics=['accuracy'])
答案 0 :(得分:1)
几件事。首先,predict
函数假定输入张量的第一维为批处理大小(即使您仅预测一个样本),但在顺序模型的第一层上具有input_shape
属性如here所示,不包括批次大小。其次,将在最后一个维度上应用密集层,因为我假设您的输入向量具有5个特征,但并不能满足您的需求,但是您要添加最后一个1维,这会使模型输出错误的大小。尝试以下代码:
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.optimizers import Adam
model = Sequential()
model.add(Dense(5, activation='relu', input_shape=(5,)))
model.add(Dropout(0.2))
model.add(Dense(5,activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(3,activation='softmax'))
model.compile(loss="mse", optimizer=Adam(lr=0.001), metrics=['accuracy'])
print(model.summary())
state = np.array([0.2, 10., 1., -10.5, 41.1]) # shape (5,)
print("Prediction:", model.predict(np.expand_dims(state, 0))) # expand_dims adds batch dimension
您应该看到此输出以进行模型摘要,并且还可以看到预测的矢量:
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 5) 30
_________________________________________________________________
dropout (Dropout) (None, 5) 0
_________________________________________________________________
dense_1 (Dense) (None, 5) 30
_________________________________________________________________
dropout_1 (Dropout) (None, 5) 0
_________________________________________________________________
dense_2 (Dense) (None, 3) 18
=================================================================
Total params: 78
Trainable params: 78
Non-trainable params: 0