iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CNN (Image)

A Convolutional Neural Network slides learned filters over an image, building hierarchies of features. Conv2D + MaxPool2D blocks turn raw pixels into class scores.

Keras CNN for CIFAR-10

EXAMPLE
import tensorflow as tf
from tensorflow.keras import layers, models, datasets, callbacks
from tensorflow.keras.optimizers import AdamW

# 1) Load + scale to [0,1]
(X_tr, y_tr), (X_te, y_te) = datasets.cifar10.load_data()
X_tr, X_te = X_tr/255.0, X_te/255.0

# 2) Build a small VGG-style CNN
def build_cnn(input_shape=(32,32,3), num_classes=10):
    inputs = layers.Input(shape=input_shape)
    x = inputs

    for filters in [32, 64, 128]:
        x = layers.Conv2D(filters, 3, padding='same')(x)
        x = layers.BatchNormalization()(x)
        x = layers.ReLU()(x)
        x = layers.Conv2D(filters, 3, padding='same')(x)
        x = layers.BatchNormalization()(x)
        x = layers.ReLU()(x)
        x = layers.MaxPool2D()(x)
        x = layers.Dropout(0.25)(x)

    x = layers.Flatten()(x)
    x = layers.Dense(256)(x)
    x = layers.BatchNormalization()(x)
    x = layers.ReLU()(x)
    x = layers.Dropout(0.5)(x)
    outputs = layers.Dense(num_classes, activation='softmax')(x)

    return models.Model(inputs, outputs)

model = build_cnn()
model.compile(
    optimizer=AdamW(learning_rate=1e-3, weight_decay=1e-4),
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy'],
)
model.summary()

# 3) Augmentation in the input pipeline
aug = tf.keras.Sequential([
    layers.RandomFlip('horizontal'),
    layers.RandomRotation(0.1),
    layers.RandomZoom(0.1),
])

ds_tr = (tf.data.Dataset.from_tensor_slices((X_tr, y_tr))
         .shuffle(50_000)
         .map(lambda x, y: (aug(x, training=True), y), num_parallel_calls=tf.data.AUTOTUNE)
         .batch(128).prefetch(tf.data.AUTOTUNE))

ds_te = (tf.data.Dataset.from_tensor_slices((X_te, y_te))
         .batch(128).prefetch(tf.data.AUTOTUNE))

# 4) Train with callbacks
cbs = [
    callbacks.EarlyStopping(monitor='val_accuracy', patience=5, restore_best_weights=True),
    callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=3),
    callbacks.ModelCheckpoint('best.keras', save_best_only=True, monitor='val_accuracy'),
    callbacks.TensorBoard('runs/cnn'),
]
history = model.fit(ds_tr, validation_data=ds_te, epochs=40, callbacks=cbs)

# 5) Inspect
print(model.evaluate(ds_te, return_dict=True))

# 6) Transfer learning — often the better starting point
base = tf.keras.applications.EfficientNetV2B0(
    include_top=False, weights='imagenet',
    input_shape=(224,224,3), pooling='avg',
)
base.trainable = False

fine = tf.keras.Sequential([
    layers.Input((224,224,3)),
    layers.Lambda(tf.keras.applications.efficientnet_v2.preprocess_input),
    base,
    layers.Dropout(0.3),
    layers.Dense(num_classes, activation='softmax'),
])
fine.compile(
    optimizer=AdamW(1e-3),
    loss='sparse_categorical_crossentropy', metrics=['accuracy'],
)

# 7) Predict on a single image
import numpy as np
img = tf.io.decode_jpeg(tf.io.read_file('cat.jpg'))
img = tf.image.resize(img, [32,32]) / 255.0
probs = model.predict(np.expand_dims(img, 0))
print('class:', np.argmax(probs))

Why it matters

BatchNorm + dropout in every conv block, augmentation in the input pipeline, EarlyStopping + ReduceLROnPlateau callbacks — the four-piece kit that turns a textbook CNN into one that actually generalises.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
from tensorflow.keras import layers, Sequential
model = Sequential([
    layers.Input((28, 28, 1)),
    layers.Conv2D(32, 3, activation='relu'),
    layers.MaxPool2D(),
    layers.Conv2D(64, 3, activation='relu'),
    layers.GlobalAveragePooling2D(),
    layers.Dense(10, activation='softmax'),
])
Try it Yourself »

Discussion

Loading…