We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2
1.
Imports and Initial Message
import os import cv2 import numpy as np import tensorflow as tf import matplotlib.pyplot as plt print("Welcome to the NeuralNine (c) Handwritten Digits Recognition v0.1") • Imports necessary libraries for handling data, images, and building the model • Prints an introductory message.
2. Decision to Train or Load Model
# Decide if to load an existing model or to train a new one train_new_model = True • Determines whether to train a new model or load an existing one.
3. Load and Normalize MNIST Data
if train_new_model: # Loading the MNIST data set with samples and splitting it mnist = tf.keras.datasets.mnist (X_train, y_train), (X_test, y_test) = mnist.load_data()
# Normalizing the data (making length = 1)
X_train = tf.keras.utils.normalize(X_train, axis=1) X_test = tf.keras.utils.normalize(X_test, axis=1) • Loads MNIST dataset (images and labels). • Normalizes image pixel values to range [0, 1] for better model performance. 4. Build Neural Network Model # Create a neural network model # Add one flattened input layer for the pixels # Add two dense hidden layers # Add one dense output layer for the 10 digits model = tf.keras.models.Sequential() model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(units=128, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(units=128, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(units=10, activation=tf.nn.softmax)) Defines a Sequential neural network with: 1. A Flatten layer to convert 2D images into 1D vectors. 2. Two Dense layers with 128 neurons and ReLU activation. 3. An output layer with 10 neurons (one for each digit) and softmax activation for probabilities.
5. Compile and Train the Model
# Compiling and optimizing model model.compile(optimizer=’adam’, loss=’sparse_categorical_crossentropy’, metrics=[’accuracy’]) • compiles the model with the Adam optimizer and categorical crossentropy loss. • Trains the model for 3 epochs using training data.
6. Evaluate and Save the Model
# Training the model model.fit(X_train, y_train, epochs=3)
# Evaluating the model
val_loss, val_acc = model.evaluate(X_test, y_test) print(val_loss) print(val_acc) # Saving the model model.save(’handwritten_digits.model’) • Evaluates the model on test data and prints loss and accuracy. • Saves the trained model to a file.
7. Load the existing model
else: # Load the model model = tf.keras.models.load_model(’handwritten_digits.model’) • Loads a pre-trained model if train_new_model is set to False.
8. Predict Custom Images
# Load custom images and predict them image_number = 1 while os.path.isfile(’digits/digit{}.png’.format(image_number)): try: img = cv2.imread(’digits/digit{}.png’.format(image_number))[:,:,0] img = np.invert(np.array([img])) prediction = model.predict(img) print("The number is probably a {}".format(np.argmax(prediction))) plt.imshow(img[0], cmap=plt.cm.binary) plt.show() image_number += 1 except: print("Error reading image! Proceeding with next image...") image_number += 1 • Loops through custom images stored in the digits/ directory. • Reads, inverts, and preprocesses images for prediction. • Predicts the digit using the model and displays the result and image.