我在这里已经读到了一些答案,尽管我们可能只需要一个预测,但模型需要2D数组才能进行预测。但是,只要我记得我的模型就需要3D阵列进行预测。我的输入形状是2D(形状47145、120),尽管预测时需要将数组放置在其他两个列表中才能正常工作。输出形状是一维数组。
model.predict([[1, 2, 3...]])[0]
不起作用,但是
model.predict([[[1, 2, 3...]]])[0][0]
做。我不介意,它对我来说非常好,但是在每行预测之后不得不添加一个额外的
[0][0]
导致我怀疑这是否是预期的行为。这是我尝试在2D数组上进行预测时收到的错误消息:
In [154] a = [0] * 120
In [155]: model.predict([a])
ValueError: Error when checking input: expected dense_1_input to have shape (120,) but got array with shape (1,)
这是我用来创建模型的代码:
opt = keras.optimizers.Adam(lr=0.00055, decay=1e-6)
layer_num = 5
nodes = 80
model = Sequential()
model.add(Dense(x_train.shape[1], activation="relu", input_shape=(x_train.shape[1:])))
for i in range(layer_num):
model.add(Dense(nodes, activation="relu"))
model.add(Dense(1, activation='linear'))
tensorboard = TensorBoard(log_dir="logs\{}-layers-{}-nodes-{}-opt-adam-decay2".format(
layer_num, nodes, 'relu'), histogram_freq=0, write_graph=True)
callbacks = [tensorboard]
model.compile(loss='mean_squared_error', optimizer=opt, metrics=['mean_absolute_error'])
model.fit(x_train, y_train, shuffle=True, batch_size=64, validation_data=(x_test, y_test),
callbacks=callbacks, epochs=80)
我的形状:
In [146]: x_train.shape
Out[146]: (47145, 120)
In [147]: y_train.shape
Out[147]: (47145,)
In [148]: x_train[0]
Out[148]:
array([0.51050081, 0.48233333, 0.12769333, 0.12920803, 0.13162067,
0.12359916, 0.51050081, 0.488 , 0.12325733, 0.14299455,
0.13225505, 0.12455976, 0.51050081, 0.49366667, 0.12325733,
0.14299455, 0.13225505, 0.12455976, 0.51050081, 0.499 ,
0.13022811, 0.13016997, 0.13352359, 0.12584059, 0.51050081,
0.49566667, 0.12896078, 0.11991025, 0.13225505, 0.13096383,
0.51050081, 0.49233333, 0.12769333, 0.11638345, 0.12940056,
0.13032347, 0.51050081, 0.48933333, 0.12325733, 0.12407822,
0.12718045, 0.12808203, 0.51050081, 0.49266667, 0.12547533,
0.12696372, 0.12718045, 0.12231832, 0.51050081, 0.48933333,
0.12547533, 0.12696372, 0.12718045, 0.12231832, 0.51050081,
0.486 , 0.12737644, 0.12568135, 0.12654618, 0.12231832,
0.51050081, 0.48266667, 0.12769333, 0.12119272, 0.12496034,
0.12584059, 0.51050081, 0.47933333, 0.13181244, 0.12151326,
0.12718045, 0.12936276, 0.51050081, 0.476 , 0.12896078,
0.12696372, 0.1284491 , 0.12391928, 0.51050081, 0.47266667,
0.12896078, 0.12696372, 0.1284491 , 0.12391928, 0.51050081,
0.46933333, 0.126109 , 0.12728437, 0.12654618, 0.11783545,
0.51050081, 0.466 , 0.12547533, 0.12343704, 0.12305742,
0.11143137, 0.51050081, 0.46266667, 0.13022811, 0.11926895,
0.11988585, 0.11879605, 0.51050081, 0.45933333, 0.12737644,
0.12407822, 0.12147158, 0.12968299, 0.51050081, 0.456 ,
0.126109 , 0.12568135, 0.12718045, 0.14761449, 0.51050081,
0.45266667, 0.126109 , 0.12568135, 0.12718045, 0.14761449])
最佳答案
异常行为;问题来自传递列表而不是数组-在幕后,前者被视为可迭代(len([[[1,2,3]]][0].shape)==2)
),但直接处理了一个Numpy数组。尝试model.predict(np.array([[1,2,3,...]]))
为了进行编辑,a = [0] * 120
不是2D数组,而是一个列表-甚至是[a]
。
关于python - 为什么我的keras模型需要3D列表才能进行预测?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58045715/