-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
53 lines (44 loc) · 1.85 KB
/
test.py
File metadata and controls
53 lines (44 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import random
import numpy as np
import matplotlib.pyplot as plt
from nn import * # Import your neural network functions
from data import mnist_dataloader
# Load the trained parameters
packed_params = np.load('trained_params_with_mini_batch8.npy')
dimensions = [784,100,10]
W1, b1, W2, b2 = unpack_params(packed_params, dimensions)
def predict(X):
# Forward pass
Z1 = W1 @ X + b1
A1 = sigmoid(Z1)
Z2 = W2 @ A1 + b2
Y_hat = softmax(Z2)
predicted_class = np.argmax(Y_hat, axis=0)
return predicted_class
# Normalize and preprocess data (ensure x_test is normalized)
(x_train, y_train), (x_test, y_test) = mnist_dataloader.load_data()
x_test = np.array(x_test) / 255.0
x_test = x_test.reshape(x_test.shape[0], -1).T # Reshape for prediction
y_test = np.array(y_test)
# If y_test is one-hot encoded, convert to class labels
if y_test.ndim > 1: # Check if y_test is one-hot encoded
y_test = np.argmax(y_test, axis=0)
# Make predictions on the entire test set
predicted_classes = predict(x_test)
# Calculate accuracy
correct_predictions = np.sum(predicted_classes == y_test)
accuracy = correct_predictions / x_test.shape[1] * 100 # x_test.shape[1] is the number of test samples
print(f"Test Accuracy: {accuracy:.2f}%")
# Optionally, display a random test image and its prediction
random_index = random.randint(0, x_test.shape[1] - 1) # Random test index
sample_image = x_test[:, random_index].reshape(28, 28) # Reshape to 28x28 for visualization
for i in range(28):
for j in range(28):
if sample_image[i][j] == 0:
print(" ", end=" ") # Replace zero with a space
else:
print("0", end=" ") # Replace non-zero with 0
print() # Moves to the next line after printing a row
plt.imshow(sample_image, cmap='gray')
plt.title(f"Sample Index: {random_index}, Predicted: {predicted_classes[random_index]}")
plt.show()