Keras预测功能失效求助:极简模型执行predict触发TypeError
问题描述
我现在完全无法用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。参考过相关方案,尝试用model.predict(np.array([[0,0,0]])),但还是没解决问题。请问该怎么正确处理?
编辑:后来发现代码本身没有问题,详见下方解答。
解决方案
首先,你提到代码本身没问题,那大概率是Keras版本和NumPy版本不兼容导致的这个问题——老版本的Keras(尤其是Keras 2.1.x及更早)和较新的NumPy版本组合时,会在predict环节出现这种数据类型识别错误。
给你几个可行的解决方向:
降级NumPy版本
如果你想继续用当前的Keras版本,把NumPy降到1.16.x或更早的兼容版本,比如在终端执行:pip install numpy==1.16.6这个版本和大多数老Keras版本的兼容性很好,能直接解决这个数据类型的问题。
升级Keras到最新稳定版
如果你不想动NumPy版本,就把Keras升级到和当前NumPy匹配的新版本,执行:pip install --upgrade keras新版本的Keras修复了很多这类底层的兼容性bug,能更好地适配新的NumPy数据类型处理逻辑。
临时绕过:指定输入数据类型
如果你暂时不想调整版本,可以尝试在创建测试输入时显式指定数据类型为float32(Keras默认的权重数据类型),比如:test_input = np.zeros((1,inDim), dtype=np.float32) # 或者在predict时直接转换 prediction = model.predict(test_input.astype(np.float32))这个办法能临时解决数据类型不匹配的问题,但长远来看还是版本兼容方案更靠谱。
另外,还要确认你是不是用的纯Keras而不是tf.keras?如果是tf.keras的话,尽量保持TensorFlow和NumPy版本的匹配,因为tf.keras的依赖逻辑和原生Keras略有不同。
最后补充一句:你说代码本身没问题是对的,这段极简模型在环境兼容的情况下是完全可以正常运行并输出预测结果的~
内容的提问来源于stack exchange,提问作者Rumo

