Почему моя модель, обученная MNIST, неправильно классифицирует пользовательское изображение в Python?Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Почему моя модель, обученная MNIST, неправильно классифицирует пользовательское изображение в Python?

Сообщение Anonymous »

Я обучил модель нейронной сети с использованием набора данных MNIST распознаванию рукописных цифр. Модель достигает точности 97 % на тестовом наборе MNIST, но не может правильно предсказать цифры из пользовательского файла изображения. Например, изображение ниже содержит цифру 8, но прогноз модели всегда неверен.
Что я делаю неправильно на этапе предварительной обработки и как мне правильно подготовить пользовательские изображения к соответствовать формату данных MNIST?
import cv2
import numpy as np
import os
from keras.api.datasets import mnist
from keras.api.models import Sequential
from keras.api.layers import Dense, Flatten
from keras.api.utils import to_categorical
from PIL import Image

# Load the MNIST dataset
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# Converts mnist data set from uint8 to float32, because most deep learning frameworks expect input data to be in floating-point format.
train_images = train_images.astype('float32') / 255
test_images = test_images.astype('float32') / 255

# Adds a new channel dimension resulting in a shape of (num_samples, 28, 28, 1)
train_images = np.expand_dims(train_images, axis=-1)
test_images = np.expand_dims(test_images, axis=-1)

# One-hot encode the labels
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

# Build the model
model = Sequential([
Flatten(input_shape=(28, 28, 1)),
Dense(128, activation='relu'),
Dense(10, activation='softmax')
])

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

# Train the model
print("Training the model...")
model.fit(train_images, train_labels, epochs=5, batch_size=128)

# Evaluate the model
loss, accuracy = model.evaluate(test_images, test_labels, verbose=0)
print(f"Test Accuracy: {accuracy * 100:.2f}%")

# Load an image for prediction
image_path = 'digit.png' # Replace with your image path
print(f"Loading and predicting for {image_path}...")

try:
# Read the image in grayscale
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

if image is None:
raise IOError(f"Error loading image at {image_path}")

# Resize the image to 28x28
image = cv2.resize(image, (28, 28))

# Invert the colors (if needed)
image = cv2.bitwise_not(image)

# Normalize the image
image_normalized = image.astype('float32') / 255

# Convert to a format that can be saved as PNG (values 0 to 255)
image_for_saving = (image_normalized * 255).astype(np.uint8)

# Define the path for saving the image
preprocessed_image_path = "preprocessed_digit.png"

# Ensure the directory exists (current directory)
output_directory = os.path.dirname(preprocessed_image_path)
if not os.path.exists(output_directory) and output_directory != '':
os.makedirs(output_directory)

# Save the image using PIL
pil_image = Image.fromarray(image_for_saving)
pil_image.save(preprocessed_image_path)
print(f"Saved preprocessed image to {preprocessed_image_path}")

# Predict the digit using your model (assuming model is already loaded)
# Reshape image to model input format if necessary
image_input = np.expand_dims(image_normalized, axis=0)
image_input = np.expand_dims(image_input, axis=-1)
prediction = np.argmax(model.predict(image_input))
print("Predicted Digit:", prediction)

except Exception as e:
print(f"Error processing the image: {e}")


Подробнее здесь: https://stackoverflow.com/questions/792 ... -in-python
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»