-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCNN.py
More file actions
95 lines (70 loc) · 2.11 KB
/
Copy pathCNN.py
File metadata and controls
95 lines (70 loc) · 2.11 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
# -----------------------------
# Load MNIST Dataset
# -----------------------------
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
# Normalize pixel values (0 to 1)
train_images = train_images / 255.0
test_images = test_images / 255.0
# Reshape for CNN
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
# -----------------------------
# Build CNN Model
# -----------------------------
model = models.Sequential()
# Convolution Layer
model.add(layers.Conv2D(
32, # Number of filters
(3, 3), # Kernel size
activation='relu',
input_shape=(28, 28, 1)
))
# Pooling Layer
model.add(layers.MaxPooling2D((2, 2)))
# Second Convolution Layer
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# Second Pooling Layer
model.add(layers.MaxPooling2D((2, 2)))
# Flatten Layer
model.add(layers.Flatten())
# Fully Connected Layer
model.add(layers.Dense(64, activation='relu'))
# Output Layer
model.add(layers.Dense(10, activation='softmax'))
# -----------------------------
# Compile Model
# -----------------------------
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# -----------------------------
# Train Model
# -----------------------------
history = model.fit(
train_images,
train_labels,
epochs=5,
validation_data=(test_images, test_labels)
)
# -----------------------------
# Evaluate Model
# -----------------------------
test_loss, test_acc = model.evaluate(test_images, test_labels)
print("\nTest Accuracy:", test_acc)
# -----------------------------
# Predict Example
# -----------------------------
prediction = model.predict(test_images)
print("\nPredicted Digit:", prediction[0].argmax())
print("Actual Digit:", test_labels[0])
# -----------------------------
# Display Image
# -----------------------------
plt.imshow(test_images[0].reshape(28, 28), cmap='gray')
plt.title("Test Image")
plt.show()