预测的keras错误
Posted
技术标签:
【中文标题】预测的keras错误【英文标题】:keras error on predict 【发布时间】:2017-02-18 09:43:14 【问题描述】:我正在尝试使用 keras 神经网络来识别绘制数字的画布图像并输出数字。我已经保存了神经网络并使用 django 来运行 Web 界面。但是每当我运行它时,我都会收到内部服务器错误和服务器端代码错误。错误提示 Exception: Error when checks : expected dense_input_1 to have shape (None, 784) but got array with shape (784, 1)。我唯一的主要观点是
from django.shortcuts import render
from django.http import HttpResponse
import StringIO
from PIL import Image
import numpy as np
import re
from keras.models import model_from_json
def home(request):
if request.method=="POST":
vari=request.POST.get("imgBase64","")
imgstr=re.search(r'base64,(.*)', vari).group(1)
tempimg = StringIO.StringIO(imgstr.decode('base64'))
im=Image.open(tempimg).convert("L")
im.thumbnail((28,28), Image.ANTIALIAS)
img_np= np.asarray(im)
img_np=img_np.flatten()
img_np.astype("float32")
img_np=img_np/255
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("model.h5")
# evaluate loaded model on test data
loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
output=loaded_model.predict(img_np)
score=output.tolist()
return HttpResponse(score)
else:
return render(request, "digit/index.html")
我查看的链接是:
Here Here and Here编辑 遵从 Rohan 的建议,这是我的堆栈跟踪
Internal Server Error: /home/
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vivek/keras/neural/digit/views.py", line 27, in home
output=loaded_model.predict(img_np)
File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 671, in predict
return self.model.predict(x, batch_size=batch_size, verbose=verbose)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1161, in predict
check_batch_dim=False)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 108, in standardize_input_data
str(array.shape))
Exception: Error when checking : expected dense_input_1 to have shape (None, 784) but got array with shape (784, 1)
另外,我有我最初用来训练网络的模型。
import numpy
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.utils import np_utils
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
(X_train, y_train), (X_test, y_test) = mnist.load_data()
for item in y_train.shape:
print item
num_pixels = X_train.shape[1] * X_train.shape[2]
X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32')
X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32')
# normalize inputs from 0-255 to 0-1
X_train = X_train / 255
X_test = X_test / 255
print X_train.shape
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
# define baseline model
def baseline_model():
# create model
model = Sequential()
model.add(Dense(num_pixels, input_dim=num_pixels, init='normal', activation='relu'))
model.add(Dense(num_classes, init='normal', activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
# build the model
model = baseline_model()
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), nb_epoch=20, batch_size=200, verbose=1)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Baseline Error: %.2f%%" % (100-scores[1]*100))
# serialize model to JSON
model_json = model.to_json()
with open("model.json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("model.h5")
print("Saved model to disk")
编辑 我尝试将 img 重塑为 (1,784) 并且它也失败了,给出了与这个问题的标题相同的错误
感谢您的帮助,让 cmets 知道我应该如何添加到问题中。
【问题讨论】:
检查这是否适用于 django 之外。发布完整的堆栈跟踪。你是如何训练模型的? @Rohan 我添加了回溯堆栈和原始 keras 文件,所以我看看 你有没有尝试在 "loaded_model.predict(img_np)" 之前做类似的事情: "img_np.reshape((None, 784))" ? @Dror Hillman 我已经尝试过了,但是它给出了错误“值必须是整数”并且失败了,所以这不起作用 我认为您的网络需要一个一个地接收像素,或者至少您将X_train
作为训练集作为形状数据集传递(784,1)。即一个像素的 784 个样本。但是您已将input_dim
声明为 784,并且网络将在输入层中具有该数量的神经元。或者将 input_dim 更改为 1,或者将 train 设置为长度为 784 的元素数组。
【参考方案1】:
您要求神经网络评估 784 个案例,每个案例有一个输入,而不是一个案例,每个案例有 784 个输入。我遇到了同样的问题,我解决了这个问题,它有一个包含单个元素的数组,它是一个输入数组。请参阅下面的示例,第一个有效,而第二个给出了您遇到的相同错误。
model.predict(np.array([[0.5, 0.0, 0.1, 0.0, 0.0, 0.4, 0.0, 0.0, 0.1, 0.0, 0.0]]))
model.predict(np.array([0.5, 0.0, 0.1, 0.0, 0.0, 0.4, 0.0, 0.0, 0.1, 0.0, 0.0]))
希望这也能为您解决问题:)
【讨论】:
***.com/questions/47295025/… 任何建议以上是关于预测的keras错误的主要内容,如果未能解决你的问题,请参考以下文章