1+ # -*- coding: utf-8 -*-
2+ #
3+ # Task 2: Deep Learning with TensorFlow/Keras
4+ # Objective: Build and train a CNN to classify handwritten digits (MNIST)
5+ # Framework: TensorFlow / Keras (Deep Learning)
6+
7+ import tensorflow as tf
8+ from tensorflow .keras .datasets import mnist
9+ from tensorflow .keras .models import Sequential
10+ from tensorflow .keras .layers import Conv2D , MaxPooling2D , Flatten , Dense , Dropout
11+ from tensorflow .keras .utils import to_categorical
12+ import numpy as np
13+ import matplotlib .pyplot as plt
14+
15+ # Ensure TensorFlow runs only once for logging
16+ print ("--- Task 2: CNN Image Classification (MNIST Dataset) ---" )
17+
18+ # 1. Load and Preprocess Data
19+ try :
20+ (x_train , y_train ), (x_test , y_test ) = mnist .load_data ()
21+
22+ # Reshape: Add channel dimension (28x28 -> 28x28x1)
23+ x_train = x_train .reshape (x_train .shape [0 ], 28 , 28 , 1 )
24+ x_test = x_test .reshape (x_test .shape [0 ], 28 , 28 , 1 )
25+
26+ # Normalize: Scale pixel values from 0-255 to 0-1
27+ x_train = x_train .astype ('float32' ) / 255
28+ x_test = x_test .astype ('float32' ) / 255
29+
30+ # One-Hot Encoding: Convert labels to binary vectors
31+ num_classes = 10
32+ y_train_encoded = to_categorical (y_train , num_classes )
33+ y_test_encoded = to_categorical (y_test , num_classes )
34+
35+ print (f"\n Training data shape: { x_train .shape } " )
36+
37+ except Exception as e :
38+ print (f"Error loading or preprocessing MNIST data: { e } " )
39+ exit ()
40+
41+
42+ # 2. Define the CNN Model Architecture
43+ model = Sequential ([
44+ # Input layer and first Convolution
45+ Conv2D (32 , kernel_size = (3 , 3 ), activation = 'relu' , input_shape = (28 , 28 , 1 )),
46+ MaxPooling2D (pool_size = (2 , 2 )),
47+
48+ # Second Convolution
49+ Conv2D (64 , (3 , 3 ), activation = 'relu' ),
50+ MaxPooling2D (pool_size = (2 , 2 )),
51+
52+ Dropout (0.25 ),
53+
54+ # Fully Connected Layers
55+ Flatten (),
56+ Dense (128 , activation = 'relu' ),
57+ Dropout (0.5 ),
58+
59+ # Output Layer
60+ Dense (num_classes , activation = 'softmax' )
61+ ])
62+
63+ # 3. Compile the Model
64+ print ("\n 3. Compiling Model..." )
65+ model .compile (
66+ optimizer = 'adam' ,
67+ loss = 'categorical_crossentropy' , # Loss function for multi-class classification
68+ metrics = ['accuracy' ]
69+ )
70+
71+ model .summary ()
72+
73+
74+ # 4. Train the Model
75+ print ("\n 4. Training the CNN Model..." )
76+ history = model .fit (
77+ x_train , y_train_encoded ,
78+ batch_size = 128 ,
79+ epochs = 10 , # 10 epochs is sufficient for high accuracy
80+ verbose = 1 ,
81+ validation_data = (x_test , y_test_encoded )
82+ )
83+ print (" Training finished." )
84+
85+
86+ # 5. Evaluate Performance
87+ print ("\n 5. Evaluating Model Performance on Test Set..." )
88+ score = model .evaluate (x_test , y_test_encoded , verbose = 0 )
89+ print (f"Test Loss: { score [0 ]:.4f} " )
90+ print (f"Test Accuracy: { score [1 ]:.4f} " )
91+
92+ # Check if the target accuracy is met
93+ if score [1 ] > 0.95 :
94+ print (" Success! Test Accuracy target (>95%) achieved." )
95+ else :
96+ print (" Note: Test Accuracy target not reached. Review model parameters." )
97+
98+
99+ # 6. Visualize Predictions
100+ test_samples = x_test [:5 ]
101+ test_labels = y_test [:5 ]
102+ predictions = model .predict (test_samples )
103+ predicted_classes = np .argmax (predictions , axis = 1 )
104+
105+ print ("\n 6. Visualizing 5 Sample Predictions (will require manual display of the plot)." )
106+
107+ # Plotting the results
108+ plt .figure (figsize = (12 , 4 ))
109+ for i in range (5 ):
110+ plt .subplot (1 , 5 , i + 1 )
111+ plt .imshow (test_samples [i ].reshape (28 , 28 ), cmap = 'gray' )
112+ plt .title (f"True: { test_labels [i ]} \n Pred: { predicted_classes [i ]} " , fontsize = 10 )
113+ plt .axis ('off' )
114+ plt .suptitle ("CNN Predictions on Sample MNIST Images" )
115+ # In a real environment, you'd save this image for the report
116+ # plt.savefig('assets/cnn_predictions_sample.png')
117+ # plt.show() # Uncomment to display plot
118+
119+ print ("\n Task 2 completed. CNN trained and evaluated." )
0 commit comments