简体   繁体   English

如何使用 Tensorflow 和 Keras 解决 ValueError 问题

[英]How do I solve the issue of ValueError with Tensorflow and Keras

Here's my code so far到目前为止,这是我的代码

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import cv2 

mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()   # 28x28 tal fra 0-9
x_train = tf.keras.utils.normalize(x_train, axis=1).reshape(x_train.shape[0], -1)
x_test = tf.keras.utils.normalize(x_test, axis=1).reshape(x_test.shape[0], -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)
val_loss, val_acc = model.evaluate(x_test, y_test)
print (val_loss)
print (val_acc)


model.save('projekt_tal_laeser')
new_model = tf.keras.models.load_model('projekt_tal_laeser')

predictions = new_model.predict(x_test)
print(predictions)

print(np.argmax(predictions[0]))

Then after saving that model I have then made this code然后在保存 model 之后,我制作了这段代码

import tensorflow as tf
import numpy as np
import cv2


def prepare(filepath):
    global prediction, model
    IMG_SIZE = 28
    img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
    new_array = cv2.resize(img_array,(IMG_SIZE, IMG_SIZE))
    return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)

model = tf.keras.models.load_model('projekt_tal_laeser')

prediction = model.predict([prepare('number.jpg')])

print(prediction)

And the error that I am now running into with my second code is ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape [None, 28, 28, 1]我现在使用第二个代码遇到的错误是ValueError: Input 0 of layer sequence is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape [None, 28, 28, 1]

The reason why I'm making the second code is to make it easier to implement it into a GUI, this is my first project and any input is much appreciated:)我制作第二个代码的原因是为了更容易将其实现到 GUI 中,这是我的第一个项目,非常感谢任何输入:)

Solution:解决方案:

prediction = model.predict([prepare('number.jpg').reshape(-1,784)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM