Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Convolutional Neural | Master Data Science with Python lesso | BraveProgrammer
  1. Courses
  2. /
  3. Master Data Science with Python

Lesson 58 of 60

·python

Convolutional Neural Networks (CNN) for Image Classification

30 minutes

Course progress97%

CNNs – Image Classification

Convolutional Neural Networks excel at extracting spatial hierarchies from images.

Key layers

  • Conv2D: learns filters (kernels).
  • MaxPooling2D: spatial down‑sampling.
  • Flatten: convert 2‑D feature maps to 1‑D.
  • Dropout: regularization.

Building a CNN on MNIST

 tensorflow  tf
 tensorflow.keras  layers, models


mnist = tf.keras.datasets.mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()


X_train = X_train[..., tf.newaxis] /    
X_test = X_test[..., tf.newaxis] / 


y_train = tf.keras.utils.to_categorical(y_train, )
y_test = tf.keras.utils.to_categorical(y_test, )

model = models.Sequential([
    layers.Conv2D(, (,), activation=, input_shape=(,,)),
    layers.MaxPooling2D((,)),
    layers.Conv2D(, (,), activation=),
    layers.MaxPooling2D((,)),
    layers.Flatten(),
    layers.Dense(, activation=),
    layers.Dropout(),
    layers.Dense(, activation=)
])

model.(optimizer=, loss=, metrics=[])
model.summary()

history = model.fit(X_train, y_train, epochs=, batch_size=, validation_split=)

test_loss, test_acc = model.evaluate(X_test, y_test)
(, test_acc)
import
as
from
import
# Load data
# Preprocess
255.0
# shape (60000,28,28,1)
255.0
# One‑hot encode labels
10
10
32
3
3
'relu'
28
28
1
2
2
64
3
3
'relu'
2
2
128
'relu'
0.5
10
'softmax'
compile
'adam'
'categorical_crossentropy'
'accuracy'
10
64
0.1
print
'Test accuracy:'

Visualizing filters

first_layer_weights = model.layers[0].get_weights()[0]   # shape (3,3,1,32)
# Plot the first 6 filters
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1,6, figsize=(15,2))
for i in range(6):
    axs[i].imshow(first_layer_weights[:,:,0,i], cmap='viridis')
    axs[i].axis('off')
plt.show()

Transfer learning (using a pre‑trained model)

base_model = tf.keras.applications.MobileNetV2(input_shape=(128,128,3), include_top=False, weights='imagenet')
base_model.trainable = False   # freeze layers

inputs = tf.keras.Input(shape=(128,128,3))
x = base_model(inputs, training=False)
x = layers.GlobalAveragePooling2D()(x)
outputs = layers.Dense(5, activation='softmax')(x)
model_tl = tf.keras.Model(inputs, outputs)

model_tl.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

Tips

  • Normalize images to [0,1] or use ImageNet mean/std.
  • Use data augmentation (tf.keras.preprocessing.image.ImageDataGenerator).
  • Early stopping prevents over‑training.

Info

For small datasets, fine‑tune a pre‑trained network rather than training from scratch.
Make it stickPractice what you've learned1 quiz · 4 practical tests · Optional activities from Master Data Science with PythonBrowse activities
Previous lessonNeural Networks Fundamentals – Architecture & TrainingContinue to lesson 59Recurrent Neural Networks (RNN) for Sequence ModelingBack to Master Data Science with Python curriculum