Write a python program to recognize the number 0, 1, 2, 39.
A 5 * 3 matrix
forms the numbers. For any valid point it is taken as 1 and invalid point it is
taken as 0. The net has to be trained to recognize all the numbers and
when the test data is given, the network has to recognize the particular
numbers
In [ ]: import numpy as np
from sklearn.neural_network import MLPClassifier
In [ ]: # Define training data
X_train = np.array([
[[1, 1, 1],
[1, 0, 1],
[1, 0, 1],
[1, 0, 1],
[1, 1, 1]], # Number 0
[[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0]], # Number 1
[[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
[1, 0, 0],
[1, 1, 1]], # Number 2
[[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1]] # Number 39
])
In [ ]: # Flatten and reshape training data
X_train_flat = X_train.reshape(len(X_train), -1)
In [ ]: # Define labels
y_train = [0, 1, 2, 39]
In [ ]: # Initialize and train MLPClassifier
clf = MLPClassifier(hidden_layer_sizes=(10,), activation='relu', max_iter=100
clf.fit(X_train_flat, y_train)
Out[ ]: ▾ MLPClassifier i ?
MLPClassifier(hidden_layer_sizes=(10,), max_iter=1000)
In [ ]: # Test data
X_test = np.array([
[[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0]], # Number 1
[[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
[1, 0, 0],
[1, 1, 1]], # Number 2
[[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1]], # Number 39
[[1, 1, 1],
[1, 0, 1],
[1, 0, 1],
[1, 0, 1],
[1, 1, 1]] # Number 0
])
In [ ]: # Flatten and reshape test data
X_test_flat = X_test.reshape(len(X_test), -1)
In [ ]: # Predict using trained model
predictions = clf.predict(X_test_flat)
In [ ]: # Print predictions
for i, pred in enumerate(predictions):
print(f"Test {i+1}: Predicted number is {pred}")
Test 1: Predicted number is 1
Test 2: Predicted number is 2
Test 3: Predicted number is 39
Test 4: Predicted number is 0