Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

tensorflow - Neural network predicts every image wrong

I am new to neural networks and I am trying to develop a nn that predicts the handwritten digit given by an image. This is my code used for training:

import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical

train_images = mnist.train_images()
train_labels = mnist.train_labels()
test_images = mnist.test_images()
test_labels = mnist.test_labels()

train_images = (train_images / 255)
test_images = (test_images / 255)

train_images = train_images.reshape((-1, 784))
test_images = test_images.reshape((-1, 784))


model = Sequential()
model.add(Dense(64, activation='relu', input_dim=784))
model.add(Dense(64, activation='relu'))
model.add(Dense(10, activation='softmax'))

model.compile(
    optimizer='adam',
    loss='categorical_crossentropy',
    metrics=['accuracy']
)

model.fit(
    train_images,
    to_categorical(train_labels),
    epochs=7,
    batch_size=32
)

model.evaluate(
    test_images,
    to_categorical(test_labels)
)

model.save('model')

And this is my code used for predicting:

import cv2
from keras.models import load_model


def prepare(filepath):
    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, 784))


def predict():
    model = load_model("model")
    prediction = model.predict([prepare('guess.png')])
    return prediction[0]


print(predict())

All of the images given by me to the nn look like this (41x41 black and white): guess.png

Any ideas where I might be mistaken?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...