Building and Training CNNs for EO Image Classification
Anefelo
Duration: 2.5 hours
Type: Intensive hands‑on lab
Goal: Turn CNN theory into a working model
You will: - Prepare the EuroSAT dataset - Build a CNN from scratch in TensorFlow/Keras - Train with GPU acceleration in Colab - Evaluate with confusion matrix and F1 - Apply transfer learning (ResNet50)
Prerequisites: - Session 3 complete (CNN basics) - Colab account with GPU enabled - Python & NumPy fundamentals
Notebooks:
session4_cnn_classification_STUDENT.ipynb
session4_transfer_learning_STUDENT.ipynb
Steps: 1. Runtime → Change runtime type → Hardware accelerator → GPU
2. Verify with !nvidia-smi
3. TensorFlow 2.16+ (Keras 3) is pre‑installed on Colab
4. Set seeds for reproducibility
Preprocessing: Normalize to [0,1], integer labels (sparse loss), split 70/15/15
from tensorflow.keras import Sequential, Input
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Flatten
model = Sequential([
Input(shape=(64, 64, 3)),
Conv2D(32, (3,3), activation='relu'),
MaxPooling2D(),
Conv2D(64, (3,3), activation='relu'),
MaxPooling2D(),
Conv2D(128,(3,3), activation='relu'),
MaxPooling2D(),
Flatten(), Dropout(0.5),
Dense(128, activation='relu'), Dropout(0.5),
Dense(10, activation='softmax')
])model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']) # integer labels → sparse loss
cb = [
tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True),
tf.keras.callbacks.ModelCheckpoint('best_model.keras', save_best_only=True), # .h5 is legacy
tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=3)
]
norm = lambda x, y: (tf.cast(x, tf.float32) / 255.0, y)
history = model.fit(ds_train.map(norm).shuffle(1000).batch(64).prefetch(2),
validation_data=ds_val.map(norm).batch(64).prefetch(2),
epochs=30, callbacks=cb)Healthy curves: train↓, val↓ then plateau; small gap
Overfitting: large gap → add dropout/augmentation
import numpy as np, matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, classification_report
y_true, y_pred = [], []
for x, y in ds_test.map(norm).batch(64):
p = model.predict(x, verbose=0).argmax(axis=1)
y_pred.extend(p); y_true.extend(y.numpy())
cm = confusion_matrix(y_true, y_pred)
print(classification_report(y_true, y_pred))Look for: - Which pairs are confused? (e.g., AnnualCrop vs Herbaceous)
- Per‑class precision/recall balance
names = meta.features['label'].names
wrong = np.where(np.array(y_true) != np.array(y_pred))[0][:12]
imgs = [img for img, _ in ds_test.as_numpy_iterator()] # ~4k chips: fits in memory
fig, axes = plt.subplots(3, 4, figsize=(10, 8))
for ax, i in zip(axes.flat, wrong):
ax.imshow(imgs[i]); ax.set_title(f'T:{names[y_true[i]]}\nP:{names[y_pred[i]]}', fontsize=8); ax.axis('off')from tensorflow.keras.applications import ResNet50
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout, Input
from tensorflow.keras.models import Model
# Feed 0-255 images through preprocess_input (ImageNet BGR mean subtraction), not /255
base = ResNet50(include_top=False, weights='imagenet', input_shape=(64,64,3))
for l in base.layers[:int(0.8*len(base.layers))]:
l.trainable = False
x = GlobalAveragePooling2D()(base.output)
x = Dense(256, activation='relu')(x)
x = Dropout(0.5)(x)
out = Dense(10, activation='softmax')(x)
model = Model(base.input, out)Strategy: - Start with frozen base → quick convergence
- Unfreeze top blocks for small accuracy gains
| Approach | Train time (T4) | Typical accuracy |
|---|---|---|
| From scratch | 5–10 min | ~90–95% |
| Feature extraction | 5–15 min | ~93–96% |
| Partial fine‑tune | 15–30 min | ~95–98% |
Indicative — the notebooks measure your own numbers
Tip: Use the fastest path during live sessions, fine‑tune offline later
Next steps: move to Day 3 (U‑Net segmentation, flood mapping)
Notebooks:
session4_cnn_classification_STUDENT.ipynb
session4_transfer_learning_STUDENT.ipynb
EO AI/ML Training · Day 2 · Session 4 | CNN Hands‑on Lab