在编写第一个NN程序时遇到了一些麻烦。 我基本上想在画布上绘制一个数字,并将其提供给应该显示“已识别”数字的NN。
#create the NN, train with mnist and load img saved from canvas
def Analizza():
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = tf.keras.utils.normalize(x_train, axis=1)
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu, input_shape= x_train.shape[1:]))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=3)
model.save('modello_numeri.model')
getter(c)
width = 28
height = 28
img = Image.open(immagine_salvata)
img = img.resize((width,height), Image.BICUBIC)
img.save(immagine_salvata)
img = PIL.Image.open("immagine.jpg").convert("L")
img_ar = np.array(img)
img_ar_norm = tf.keras.utils.normalize(img_ar, axis=1)
plt.imshow(img_ar, cmap=plt.cm.binary)
plt.show()
#make prediction
predizione = model.predict(img_ar_norm, batch_size=None)
risposta = np.argmax(predizione[0])
print(risposta)
#risultato = tk.Label(window, text=risposta, font=("Helvetica",57))
#risultato.grid(row=0, column=1, sticky="E")
这部分给了我这些错误:
Tkinter回调中的异常 追溯(最近一次通话): 调用中的文件>“ C:\ Users \ Massimo \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ tkinter__init __。py”,行1705 返回self.func(* args) Analizza中的文件“ c:/Users/Massimo/AppVisualCode/disegno.py”,第91行 predizione = model.predict(img_ar_norm,batch_size = None) 预测中的文件“ C:\ Users \ Massimo \ AppData \ Roaming \ Python \ Python37 \ site-packages \ tensorflow \ python \ keras \ engine \ training.py”,行1113 自我,x,batch_size = batch_size,详细=详细,steps = steps) 文件“ C:\ Users \ Massimo \ AppData \ Roaming \ Python \ Python37 \ site-packages \ tensorflow \ python \ keras \ engine \ training_arrays.py”,行329,在model_iteration中 batch_outs = f(ins_batch) 调用中的文件“ C:\ Users \ Massimo \ AppData \ Roaming \ Python \ Python37 \ site-packages \ tensorflow \ python \ keras \ backend.py”,第3076行 run_metadata = self.run_metadata) 调用中的文件“ C:\ Users \ Massimo \ AppData \ Roaming \ Python \ Python37 \ site-packages \ tensorflow \ python \ client \ session.py”,行1439 run_metadata_ptr) 退出中的文件“ C:\ Users \ Massimo \ AppData \ Roaming \ Python \ Python37 \ site-packages \ tensorflow \ python \ framework \ errors_impl.py”,第528行 c_api.TF_GetCode(self.status.status)) tensorflow.python.framework.errors_impl.InvalidArgumentError:矩阵大小不兼容:In [0]:[28,28],In [1]:[784,128] [[{{node MatMul}}]]
我知道预测所期望的矩阵大小应该有问题,但是为什么呢?我正在保存图像,将其调整为28x28(黑白),然后将其打开为np数组,就像它是x_train [0]
谢谢 最高