Chapter 21

ইমেজ ক্লাসিফিকেশন

Image Classification
🎬 CIFAR-10 হাতে-কলমে
এই অধ্যায়ে আমরা একটি পূর্ণ Image Classification পাইপলাইন বানাব — ডেটা লোড থেকে মডেল, augmentation, training, evaluation এবং inference পর্যন্ত।

ডেটা — CIFAR-10

from tensorflow.keras.datasets import cifar10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train, x_test = x_train/255.0, x_test/255.0

class_names = ["airplane","automobile","bird","cat","deer",
               "dog","frog","horse","ship","truck"]

Augmentation Pipeline

from tensorflow.keras import layers

aug = tf.keras.Sequential([
    layers.RandomFlip("horizontal"),
    layers.RandomRotation(0.1),
    layers.RandomZoom(0.1),
    layers.RandomContrast(0.1),
])

মডেল আর্কিটেকচার

from tensorflow.keras import models, layers

def build_cnn():
    inp = layers.Input((32,32,3))
    x = aug(inp)
    for filters in [32, 64, 128]:
        x = layers.Conv2D(filters, 3, padding="same")(x)
        x = layers.BatchNormalization()(x)
        x = layers.Activation("relu")(x)
        x = layers.Conv2D(filters, 3, padding="same")(x)
        x = layers.BatchNormalization()(x)
        x = layers.Activation("relu")(x)
        x = layers.MaxPooling2D()(x)
        x = layers.Dropout(0.25)(x)
    x = layers.GlobalAveragePooling2D()(x)
    x = layers.Dense(128, activation="relu")(x)
    x = layers.Dropout(0.5)(x)
    out = layers.Dense(10, activation="softmax")(x)
    return models.Model(inp, out)

model = build_cnn()
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy",
              metrics=["accuracy"])

Training + Callback

from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint

cb = [
    EarlyStopping(patience=8, restore_best_weights=True),
    ReduceLROnPlateau(factor=0.5, patience=3),
    ModelCheckpoint("best.h5", save_best_only=True),
]

history = model.fit(x_train, y_train, epochs=50, batch_size=128,
                    validation_split=0.1, callbacks=cb)

Evaluation ও Confusion Matrix

from sklearn.metrics import classification_report, confusion_matrix
import seaborn as sns, matplotlib.pyplot as plt

y_pred = model.predict(x_test).argmax(1)
print(classification_report(y_test, y_pred, target_names=class_names))

cm = confusion_matrix(y_test, y_pred)
sns.heatmap(cm, annot=True, fmt="d", xticklabels=class_names, yticklabels=class_names)
plt.show()

Inference

import numpy as np
img = load_image("cat.png", (32,32))
prob = model.predict(np.expand_dims(img/255.0, 0))[0]
print(class_names[prob.argmax()], prob.max())
🔑 Performance টিপ
Mixed precision (tf.keras.mixed_precision) + tf.data prefetch + cache ব্যবহার করলে training 2–3x দ্রুত হয় GPU-তে।

সাধারণ ভুল

⚠️ এড়িয়ে চলবেন
  • Normalization ভুলে যাওয়া — মডেল শেখেই না।
  • Augmentation test-এ apply করা — accuracy কমবে।
  • BatchNorm + Dropout-এর ভুল ক্রম।

অনুশীলন

১. CIFAR-10-এ 85%+ test accuracy অর্জন করুন।

২. Augmentation চালু/বন্ধ করে overfit pattern observe করুন।

৩. Confusion matrix থেকে কোন ২টি class সবচেয়ে বেশি বিভ্রান্ত — বের করুন।

সারসংক্ষেপ

✨ এই অধ্যায়ে যা শিখলাম
  • Data → Aug → Model → Train → Eval — পূর্ণ পাইপলাইন।
  • BatchNorm + Dropout + GAP আধুনিক CNN-এর স্ট্যান্ডার্ড।
  • Callback দিয়ে training স্বয়ংক্রিয় ও স্থিতিশীল।