predict with Keras fails due to faulty environment

2020-04-15 15:46发布

问题:

I can't get Keras to predict anything. Not even in this minimalistic model:

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)

Everything goes as expected until the last line:

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

I tried over and over again with different combinations of arrays and lists, but either there is that TypeError or a ValueError, because the shape is wrong. Several answers (like here) suggest using something like

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

But this didn't work for me, either. Could anyone please tell me how to do this right?

EDIT: Apparently, the code was not the problem, see below.

回答1:

It turned out the code wasn't the problem, but there was something wrong with my software. After the following steps, the above code runs without errors or warnings:

  1. uninstall anaconda
  2. install anaconda
  3. create new environment
  4. install required packages into that environment (keras, tensorflow, spyder...)
  5. run code in that environment


回答2:

I pasted your code into https://colab.research.google.com and it didn't give me an error. (python2)

I did however get a warning about int to float conversion.

I would try to specify the test_input dtype explicitly as in:

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

Since that seems to be the error message that is being output.



回答3:

I uninstalled and installed the Anaconda Navigator again and it got fixed.