【问题标题】:predict with Keras fails due to faulty environment setup由于环境设置错误,使用 Keras 进行预测失败
【发布时间】:2019-07-21 01:54:13
【问题描述】:

我无法让 Keras 预测任何事情。甚至在这个极简模型中也不行:

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

inDim = 3
outDim = 1

model = Sequential()
model.add(Dense(5, input_dim=inDim, activation='relu'))
model.add(Dense(outDim, activation='sigmoid'))
model.compile(loss='mse', optimizer='adam', metrics=['accuracy'])

test_input = np.zeros((1,inDim))
test_output = np.zeros((1,outDim))
model.fit(test_input, test_output)
prediction = model.predict(test_input)

一切都按预期进行,直到最后一行:

Epoch 1/1
1/1 [==============================] - 0s 448ms/step - loss: 0.2500 - acc: 1.0000
Traceback (most recent call last):

  File "<ipython-input-24-ee244a6c7287>", line 16, in <module>
    prediction = model.predict(test_input)

  File "E:\Programme\Anaconda3\lib\site-packages\keras\engine\training.py", line 1172, in predict
    steps=steps)

  File "E:\Programme\Anaconda3\lib\site-packages\keras\engine\training_arrays.py", line 304, in predict_loop
    outs.append(np.zeros(shape, dtype=batch_out.dtype))

TypeError: data type not understood

我一遍又一遍地尝试使用不同的数组和列表组合,但要么存在 TypeError,要么存在 ValueError,因为形状错误。 几个答案(如here)建议使用类似

model.predict(np.array([[0,0,0]]))

但这对我也不起作用。 谁能告诉我如何做到这一点?

编辑:显然,代码不是问题,见下文。

【问题讨论】:

  • 请用详细而准确的内容修正您的问题的标题,错误消息无济于事。请提供一些背景。如果没有更多详细信息,请对您所尝试的内容发表评论。

标签: python tensorflow keras typeerror predict


【解决方案1】:

我将您的代码粘贴到 https://colab.research.google.com 并没有给我错误。 (python2)

然而,我确实收到了关于 int 到 float 转换的警告。

我会尝试明确指定 test_input dtype,如下所示:

test_input = np.zeros((1,inDim), dtype=float)

因为这似乎是正在输出的错误消息。

【讨论】:

  • dtype 参数没有改变任何东西。但实际上,该代码适用于带有 Python 3.6 的 colab,这也是我安装的。警告独立于 predict 调用出现,并且由于 fit 调用工作正常,我不确定它们是否与我的错误有关。所以也许我的安装坏了?我会研究这个并在这里更新。
【解决方案2】:

结果证明代码不是问题,但我的软件有问题。经过以下步骤,上面的代码运行没有错误或警告:

  1. 卸载 anaconda
  2. 安装 anaconda
  3. 创建新环境
  4. 将所需的软件包安装到该环境中(keras、tensorflow、 蜘蛛...)
  5. 在该环境中运行代码

【讨论】:

    【解决方案3】:

    我再次卸载并安装了 Anaconda Navigator,它得到了修复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      相关资源
      最近更新 更多