neural network word recognition in python

Here's a basic example of how to create a neural network for word recognition in Python using the deep learning libraries Keras and TensorFlow:

  1. Importing the necessary libraries:
main.py
import keras
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten
from keras.utils import to_categorical

import numpy as np
import matplotlib.pyplot as plt
188 chars
8 lines
  1. Loading and preprocessing the data:
main.py
from keras.datasets import mnist

# Load the MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# Normalize the data
x_train = x_train / 255.0
x_test = x_test / 255.0

# One-hot encode the labels
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

# Reshape the data to fit the model
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
427 chars
17 lines
  1. Creating the neural network model:
main.py
# Create the model
model = Sequential()

# Add a convolutional layer with 32 filters, a 3x3 kernel, and a ReLU activation function
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))

# Add a second convolutional layer with 64 filters and a ReLU activation function
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))

# Flatten the output from the convolutional layers
model.add(Flatten())

# Add a dense layer with 128 neurons and a ReLU activation function
model.add(Dense(128, activation='relu'))

# Add the output layer with 10 neurons (one for each digit) and a softmax activation function
model.add(Dense(10, activation='softmax'))

# Compile the model with a categorical crossentropy loss function and an Adam optimizer
model.compile(loss=keras.losses.categorical_crossentropy, optimizer='adam', metrics=['accuracy'])
869 chars
21 lines
  1. Training the model:
main.py
# Train the model on the training data
model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))
112 chars
3 lines

After training, you can test the model's performance on new data using the predict() method. For example:

main.py
# Test the trained model on some new data
predictions = model.predict(x_test[:5])

# Show the predicted labels
print(np.argmax(predictions, axis=1))
149 chars
6 lines

gistlibby LogSnag