【问题标题】:Keras model.predict won't accept input of size one (scalar number)Keras model.predict 不接受大小为一的输入(标量)
【发布时间】:2016-09-13 04:15:37
【问题描述】:

我是 Keras 和 python 的新手,现在我正在研究 Keras 以查找数据模型并使用该 model.predict 进行优化,但是 model.predict 只能将输入作为至少 2 的 numpy 数组元素。

我的代码是

import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
import numpy as np

x = np.arange(-2,3.0,0.01)
y = x**2 - 2*x + 1

model = Sequential()
model.add(Dense(50, activation='sigmoid', 
                input_dim=1, init='uniform'))
model.add(Dense(1, activation='linear'))
sgd = SGD(lr=0.05, decay=1e-6, momentum=0.9, nesterov=False)
model.compile(loss='mean_squared_error', 
              optimizer='sgd',
              metrics=['accuracy'])
model.fit(x,y,nb_epoch=300, batch_size = 5,verbose = 0)

代码可以很好,但如果我尝试使用 model.predict 作为标量数,它会给我错误

(Pdb) model.predict(0.0)
*** Exception: Error when checking : data should be a Numpy array, or list/dict of Numpy arrays. Found: 0.0...

我强制它是 numpy 数组但仍然失败,它说输入需要是 2 维!!!

(Pdb) model.predict(np.asarray(0.0))
*** Exception: Error when checking : expected dense_input_1 to have 2 dimensions, but got array with shape ()

但是如果我输入两个数字,那么它会给我答案

(Pdb) model.predict([0.0,0.0])
array([[ 1.07415712],
       [ 1.07415712]], dtype=float32)

我需要 model.predict 将单个数字作为输入以用于优化。我不确定我使用错误的任何设置。请帮忙,谢谢。

【问题讨论】:

    标签: python keras


    【解决方案1】:

    试试:

    model.predict(np.asarray(0.0).reshape((1,1)))
    

    在 Keras 中,第一维总是与示例编号相连,因此必须提供。

    【讨论】:

    • 通过示例编号,您是指索引吗?例如,如果我必须输入一组特征,那么第一维是 1。对于 2 组特征,第一维是 2??
    猜你喜欢
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多