我正在尝试实现一个tensorflow项目,其中用户绘制一个数字,模型可以识别它。到目前为止,我已经让用户在tkinter画布上绘制数字,保存图像,然后再次将该图像转换为numpy数组以进行模型预测。但是我一直收到以下错误:
ValueError Input 0 of layer dense is incompatible with the layer: expected axis of -1 of input shape to have value 784 but received input with shape [None, 840]
这是代码:
def draw(event):
color='black'
x1, y1 = (event.x-1), (event.y-1)
x2, y2 = (event.x+1), (event.y+1)
c.create_rectangle(x1,y1,x2,y2, fill=color, width=10)
blank.rectangle([x1-4,y1-4,x2+4,y2+4], fill=color, width=10)
def end(event):
filename = "myNum.jpg"
myImage.save(filename) #save image
print("image saved")
data = image.imread("myNum.jpg") #convert image to numpy array
predictModel(data)
def predictModel(data):
model = tf.keras.models.load_model('numbers.model')
prediction = model.predict(data)
print(np.argmax(prediction[0]))
if __name__ == "__main__":
root = Tk()
c = Canvas(root, height=280, width=280, bg='white')
c.pack()
myImage = Image.new("RGB", (280, 280), 'white')
blank = ImageDraw.Draw(myImage)
root.bind('<Return>', end)
c.bind('<B1-Motion>', draw)
root.mainloop()
我正在使用此视频中的预测模型:https://www.youtube.com/watch?v=wQ8BIBpya2k&
model = keras.models.Sequential()
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(128, activation=tf.nn.relu)) #I think the error is occurring here
model.add(keras.layers.Dense(128, activation=tf.nn.relu))
model.add(keras.layers.Dense(10, activation=tf.nn.softmax))
非常感谢您的帮助