python - Keras model.predict 不接受大小为一的输入(标量)

标签 python keras

我是 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 数组但仍然失败,它说输入需要是二维的!!!

(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 将单个数字作为输入以用于优化。我不确定我使用错误的任何设置。请帮忙,谢谢。

最佳答案

尝试:

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

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

关于python - Keras model.predict 不接受大小为一的输入(标量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39462142/

相关文章:

python - 如何以简单的方式在 Keras 中分配 class_weight?

python - 当作为指标传递给 model.compile() 时,tf.keras.metrics.TruePositives() 在 model.fit() 中返回错误值

python - Keras VGGnet 预训练模型可变大小输入

math - 这个基本卷积是在普通卷积神经网络中进行的吗?

python - 如何从bigquery中的 View 获取保存的查询

python - 如何在 np.where 中使用两个条件

python - 我的 .yaml 未正确重定向

python - try-except-else 语句的用例

python - Keras multi_gpu_model 错误 : "swig/python detected a memory leak of type ' int64_t *', no destructor found"

Python - 标准库 - ascii( ) 函数