Skip to main content

Session 2 Lab: Advanced Palawan Land Cover Classification

Multi-temporal features, an 8-class scheme and change detection

Open In Colab

Day 2 · Session 2 | Duration: ~2 hours | Difficulty: Intermediate | Instructor: Dimitrios Kasampalis (Anefelo)


🎯 Learning objectives

By the end of this lab, you will be able to:

  1. Build dry- and wet-season Sentinel-2 composites for the Philippine climate
  2. Engineer texture (GLCM), temporal and topographic features in Earth Engine
  3. Derive an 8-class training set from open reference layers and train a Random Forest
  4. Assess accuracy with a held-out validation set and per-class metrics
  5. Tune hyperparameters and post-process the map
  6. Detect land cover change (2020 vs 2024) and summarise it for stakeholders

🧰 What you’ll need

  • Earth Engine access with a registered Google Cloud project (as in Session 1)
  • Google Colab, CPU runtime (all heavy computation runs on Earth Engine)
  • About 2 hours; some cells take 1–3 minutes because Earth Engine computes them on request

📍 Study area and labels

  • A 1° × 1° box (~12,000 km², land and sea) in central Palawan around Puerto Princesa.
  • Labels: there is no open, field-verified 8-class dataset for Palawan, so we derive proxy labels from ESA WorldCover 2021 and the Hansen Global Forest Change dataset (see Part B). This is a teaching shortcut — accuracy figures measure agreement with those products, not true map accuracy.

Part A: Setup and Feature Engineering

# geemap is pre-installed on Colab; this makes sure it is present elsewhere
%pip install -q geemap
# Import libraries
import os
import ee
import geemap
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime

sns.set_style("whitegrid")
plt.rcParams['figure.figsize'] = (12, 8)

print("✔ Libraries imported successfully")
# Authenticate and initialise Earth Engine
# TODO: replace the placeholder with YOUR Cloud project ID (or set the EE_PROJECT environment variable)
PROJECT_ID = os.environ.get("EE_PROJECT", "your-cloud-project-id")

try:
    ee.Initialize(project=PROJECT_ID)
except Exception:
    ee.Authenticate()
    ee.Initialize(project=PROJECT_ID)

print(f"✓ Earth Engine initialised (project: {PROJECT_ID})")

Define the study area

# Central Palawan subset (west, south, east, north)
palawan_bbox = [118.5, 9.5, 119.5, 10.5]
aoi = ee.Geometry.Rectangle(palawan_bbox)

print(f"Study area: {palawan_bbox}")
print(f"Area (land + sea): {aoi.area(maxError=1).divide(1e6).getInfo():,.0f} km²")

Map = geemap.Map(center=[10.0, 119.0], zoom=9)
Map.addLayer(aoi, {'color': 'red'}, 'Study Area')
Map

Seasonal composites

The Philippines has a dry season (roughly December–May) and a wet/south-west monsoon season (June–November). We build one cloud-masked median composite per season. Cloud masking uses Cloud Score+ (the old QA60 band was not populated from January 2022 to February 2024, so QA60 masks silently fail).

BANDS = ['B2', 'B3', 'B4', 'B8', 'B11', 'B12']
CS_PLUS = ee.ImageCollection('GOOGLE/CLOUD_SCORE_PLUS/V1/S2_HARMONIZED')
CLEAR_THRESHOLD = 0.60

def mask_s2_clouds(image):
    """Keep clear pixels (Cloud Score+) and scale reflectance to 0-1."""
    clear = image.select('cs_cdf').gte(CLEAR_THRESHOLD)
    return image.select(BANDS).updateMask(clear).divide(10000)

def s2_composite(start, end, max_cloud=60):
    """Cloud-masked Sentinel-2 SR median composite for [start, end)."""
    return (ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
            .filterBounds(aoi)
            .filterDate(start, end)
            .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', max_cloud))
            .linkCollection(CS_PLUS, ['cs_cdf'])
            .map(mask_s2_clouds)
            .median()
            .clip(aoi))

dry_season = s2_composite('2024-01-01', '2024-06-01')   # Jan–May 2024
wet_season = s2_composite('2024-06-01', '2024-12-01')   # Jun–Nov 2024
print("✔ Seasonal composites defined")
print(f"  Bands: {dry_season.bandNames().getInfo()}")
# Visualise both seasons (toggle layers in the top-right control)
Map2 = geemap.Map(center=[10.0, 119.0], zoom=10)
vis_params = {'min': 0, 'max': 0.3, 'bands': ['B4', 'B3', 'B2']}
Map2.addLayer(dry_season, vis_params, 'Dry season (Jan–May 2024)')
Map2.addLayer(wet_season, vis_params, 'Wet season (Jun–Nov 2024)')
Map2

Spectral indices

def add_indices(image):
    """Add NDVI, NDWI, NDBI and EVI to a 0-1 reflectance image."""
    ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')   # vegetation
    ndwi = image.normalizedDifference(['B3', 'B8']).rename('NDWI')   # open water (McFeeters)
    ndbi = image.normalizedDifference(['B11', 'B8']).rename('NDBI')  # built-up / bare
    evi = image.expression(
        '2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))', {
            'NIR': image.select('B8'), 'RED': image.select('B4'), 'BLUE': image.select('B2')
        }).rename('EVI')
    return image.addBands([ndvi, ndwi, ndbi, evi])

dry_with_indices = add_indices(dry_season)
wet_with_indices = add_indices(wet_season)
print(f"✔ Dry-season bands: {dry_with_indices.bandNames().getInfo()}")

GLCM texture

glcmTexture only accepts integer images, so we first quantise NIR reflectance (0–0.5) to 0–255. We keep three of the 18 GLCM outputs: contrast, entropy and inverse difference moment (homogeneity).

def texture_features(image):
    nir_8bit = image.select('B8').multiply(255 / 0.5).clamp(0, 255).toUint8()
    glcm = nir_8bit.glcmTexture(size=1)   # 3x3 window keeps it fast
    return glcm.select(['B8_contrast', 'B8_ent', 'B8_idm'],
                       ['texture_contrast', 'texture_entropy', 'texture_homogeneity'])

texture = texture_features(dry_season)
print(f"✔ Texture features: {texture.bandNames().getInfo()}")

Topographic features

# SRTM 30 m DEM: elevation, slope and aspect
dem = ee.Image('USGS/SRTMGL1_003').clip(aoi)
topo_features = ee.Image.cat([
    dem.select('elevation'),
    ee.Terrain.slope(dem).rename('slope'),
    ee.Terrain.aspect(dem).rename('aspect'),
])
print(f"✔ Topographic features: {topo_features.bandNames().getInfo()}")

Temporal features

def temporal_features(dry, wet):
    ndvi_dry = dry.select('NDVI').rename('NDVI_dry')
    ndvi_wet = wet.select('NDVI').rename('NDVI_wet')
    return ee.Image.cat([
        ndvi_dry, ndvi_wet,
        ndvi_wet.subtract(ndvi_dry).rename('NDVI_diff'),   # phenological signal
        ndvi_dry.add(ndvi_wet).divide(2).rename('NDVI_mean'),
        dry.select('NDWI').rename('NDWI_dry'),
        wet.select('NDWI').rename('NDWI_wet'),
    ])

temporal = temporal_features(dry_with_indices, wet_with_indices)
print(f"✔ Temporal features: {temporal.bandNames().getInfo()}")

Stack all features

We wrap everything in one function so that exactly the same features can be computed for another year (needed for change detection in Part D).

def build_feature_stack(year):
    """22-band feature stack (spectral, indices, texture, temporal, terrain) for one year."""
    dry = add_indices(s2_composite(f'{year}-01-01', f'{year}-06-01'))
    wet = add_indices(s2_composite(f'{year}-06-01', f'{year}-12-01'))
    return ee.Image.cat([
        dry.select(BANDS),                              # 6 spectral bands (dry season)
        dry.select(['NDVI', 'NDWI', 'NDBI', 'EVI']),    # 4 indices
        texture_features(dry),                          # 3 texture
        temporal_features(dry, wet),                    # 6 temporal
        topo_features,                                  # 3 topographic
    ]).toFloat()

feature_stack = build_feature_stack(2024)
all_bands = feature_stack.bandNames().getInfo()
print(f"✔ Feature stack: {len(all_bands)} features")
for i, band in enumerate(all_bands, 1):
    print(f"  {i:2d}. {band}")

Part B: 8-class Classification

Reference labels

ID Class Proxy rule (reference layers)
1 Primary forest WorldCover tree cover and ≥ 75% tree cover in 2000 and no forest loss 2001–2024 (Hansen GFC)
2 Secondary forest WorldCover tree cover and (< 50% tree cover in 2000 or forest loss 2001–2018, i.e. regrown)
3 Mangroves WorldCover mangroves
4 Agricultural WorldCover cropland
5 Grassland/scrub WorldCover grassland or shrubland
6 Water WorldCover permanent water
7 Urban WorldCover built-up
8 Bare soil WorldCover bare / sparse vegetation

“Primary” vs “secondary” here is only a proxy (canopy density and disturbance history), not an ecological survey.

worldcover = ee.ImageCollection('ESA/WorldCover/v200').first().clip(aoi)
gfc = ee.Image('UMD/hansen/global_forest_change_2025_v1_13').clip(aoi)

tree = worldcover.eq(10)
treecover2000 = gfc.select('treecover2000')
lossyear = gfc.select('lossyear')          # 0 = no loss, 1..25 = loss in 2001..2025

labels = (ee.Image(0)
          .where(tree.And(treecover2000.gte(75)).And(lossyear.eq(0)), 1)
          .where(tree.And(treecover2000.lt(50).Or(lossyear.gt(0).And(lossyear.lte(18)))), 2)
          .where(worldcover.eq(95), 3)
          .where(worldcover.eq(40), 4)
          .where(worldcover.eq(20).Or(worldcover.eq(30)), 5)
          .where(worldcover.eq(80), 6)
          .where(worldcover.eq(50), 7)
          .where(worldcover.eq(60), 8)
          .rename('class_id').toInt()
          .clip(aoi))

class_names = {1: 'Primary Forest', 2: 'Secondary Forest', 3: 'Mangroves', 4: 'Agricultural',
               5: 'Grassland', 6: 'Water', 7: 'Urban', 8: 'Bare Soil'}
class_colors = ['#0A5F0A', '#4CAF50', '#009688', '#FFC107',
                '#FFEB3B', '#2196F3', '#F44336', '#795548']

# Stratified random sample: up to 300 points per class, then a 70/30 train/validation split
samples = labels.stratifiedSample(
    numPoints=300, classBand='class_id', region=aoi, scale=30, seed=42,
    geometries=True, tileScale=4
).filter(ee.Filter.neq('class_id', 0)).randomColumn('split', 42)

training_points = samples.filter(ee.Filter.lt('split', 0.7))
validation_points = samples.filter(ee.Filter.gte('split', 0.7))

counts = samples.aggregate_histogram('class_id').getInfo()
print("✔ Reference points per class:")
for k, v in sorted(counts.items(), key=lambda kv: int(kv[0])):
    print(f"  {int(k)} {class_names[int(k)]:17s} {v}")
# Look at the reference labels and the sample points
Map_training = geemap.Map(center=[10.0, 119.0], zoom=10)
Map_training.addLayer(labels.selfMask(), {'min': 1, 'max': 8, 'palette': class_colors}, 'Proxy labels', False)
for i in range(1, 9):
    Map_training.addLayer(training_points.filter(ee.Filter.eq('class_id', i)),
                          {'color': class_colors[i-1]}, f'Train: {class_names[i]}')
Map_training.addLayer(aoi, {'color': 'black'}, 'Study Area', False)
Map_training

Sample features and train the classifier

training = feature_stack.sampleRegions(
    collection=training_points, properties=['class_id'], scale=30, tileScale=4)
validation = feature_stack.sampleRegions(
    collection=validation_points, properties=['class_id'], scale=30, tileScale=4)

print(f"✔ Training samples: {training.size().getInfo()}")
print(f"✔ Validation samples: {validation.size().getInfo()}")
print("Training Random Forest classifier...")
classifier = ee.Classifier.smileRandomForest(
    numberOfTrees=100,
    variablesPerSplit=None,   # default: sqrt(number of features)
    minLeafPopulation=1,
    bagFraction=0.5,
    seed=42
).train(features=training, classProperty='class_id', inputProperties=all_bands)

explanation = classifier.explain().getInfo()
print("✔ Random Forest trained (100 trees)")
print(f"  Out-of-bag error estimate: {explanation['outOfBagErrorEstimate']:.3f}")

# Feature importance
importance = pd.Series(explanation['importance']).sort_values()
importance.plot.barh(figsize=(8, 7), color='steelblue', title='Random Forest feature importance')
plt.xlabel('Importance (Gini decrease, summed over trees)')
plt.tight_layout()
plt.show()

Apply the classification

classified = feature_stack.classify(classifier).rename('classification')

Map3 = geemap.Map(center=[10.0, 119.0], zoom=10)
Map3.addLayer(classified, {'min': 1, 'max': 8, 'palette': class_colors}, 'Land Cover 2024')
Map3.addLayer(aoi, {'color': 'black'}, 'Study Area', False)
Map3.add_legend(title='Land Cover Classes', keys=list(class_names.values()), colors=class_colors)
Map3

Accuracy assessment

validated = validation.classify(classifier)
confusion_matrix = validated.errorMatrix('class_id', 'classification')

overall_accuracy = confusion_matrix.accuracy().getInfo()
kappa = confusion_matrix.kappa().getInfo()
cm = np.array(confusion_matrix.getInfo())[1:, 1:]          # drop unused class 0
names = list(class_names.values())

print("=" * 60)
print("ACCURACY ASSESSMENT (agreement with proxy labels)")
print("=" * 60)
print(f"Overall Accuracy: {overall_accuracy*100:.2f}%")
print(f"Kappa Coefficient: {kappa:.4f}")

per_class = pd.DataFrame({
    "Producer's acc.": np.diag(cm) / cm.sum(axis=1).clip(min=1),
    "User's acc.": np.diag(cm) / cm.sum(axis=0).clip(min=1),
    'n (reference)': cm.sum(axis=1),
}, index=names)
print(per_class.round(3))

sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=names, yticklabels=names)
plt.xlabel('Map (predicted)'); plt.ylabel('Reference')
plt.title('Confusion matrix — validation points')
plt.tight_layout(); plt.show()

Area statistics

print("Calculating area statistics...")
area_dict = (ee.Image.pixelArea().divide(10000)          # hectares
             .addBands(classified)
             .reduceRegion(reducer=ee.Reducer.sum().group(groupField=1, groupName='class_id'),
                           geometry=aoi, scale=30, maxPixels=1e13, tileScale=4)
             .get('groups').getInfo())
area_stats = {class_names[int(g['class_id'])]: g['sum'] for g in area_dict}
for name, ha in area_stats.items():
    print(f"  {name:17s}: {ha:12,.0f} ha")
fig, ax = plt.subplots(figsize=(12, 6))
bars = ax.bar(list(area_stats), list(area_stats.values()),
              color=[class_colors[names.index(n)] for n in area_stats], edgecolor='black')
ax.set_ylabel('Area (hectares)')
ax.set_title('Central Palawan land cover (2024, Random Forest)')
ax.tick_params(axis='x', rotation=45)
for bar, value in zip(bars, area_stats.values()):
    ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(), f'{value:,.0f}', ha='center', va='bottom')
plt.tight_layout()
plt.show()

Part C: Model Optimisation

Worked example — number of trees

tree_counts = [50, 100, 200]
results = {}
for n_trees in tree_counts:
    clf = ee.Classifier.smileRandomForest(numberOfTrees=n_trees, seed=42).train(
        features=training, classProperty='class_id', inputProperties=all_bands)
    acc = validation.classify(clf).errorMatrix('class_id', 'classification').accuracy().getInfo()
    results[n_trees] = acc
    print(f"Trees: {n_trees:3d} | Accuracy: {acc*100:.2f}%")

best = max(results, key=results.get)
print(f"\n✔ Best tree count on this validation set: {best} ({results[best]*100:.2f}%)")

🎯 Exercise 1 — Tune another hyperparameter

Task: set PARAM_GRID to test variablesPerSplit values (e.g. [2, 5, 10]; default is √22 ≈ 4) or change the loop to test minLeafPopulation ([1, 5, 10]).

Expected output: one accuracy line per value. Differences are usually small (≤ 2 points) — with proxy labels and a few hundred points, the validation set itself has ±2–3 points of sampling uncertainty.

PARAM_GRID = [None]  # TODO: e.g. [2, 5, 10]

for value in PARAM_GRID:
    clf = ee.Classifier.smileRandomForest(numberOfTrees=100, variablesPerSplit=value, seed=42).train(
        features=training, classProperty='class_id', inputProperties=all_bands)
    acc = validation.classify(clf).errorMatrix('class_id', 'classification').accuracy().getInfo()
    print(f"variablesPerSplit={value}: accuracy {acc*100:.2f}%")

Post-processing: majority filter

# 3x3 majority (mode) filter reduces salt-and-pepper noise
classified_filtered = classified.focal_mode(radius=1, kernelType='square')

Map4 = geemap.Map(center=[10.0, 119.0], zoom=11)
Map4.addLayer(classified, {'min': 1, 'max': 8, 'palette': class_colors}, 'Original classification')
Map4.addLayer(classified_filtered, {'min': 1, 'max': 8, 'palette': class_colors}, 'Filtered classification')
Map4.addLayerControl()
Map4

Part D: Change Detection (2020 vs 2024)

We compute the same 22 features for 2020 and apply the 2024 classifier (“post-classification comparison”). Errors of both maps add up, so map differencing tends to overestimate change — we sanity-check against Hansen GFC.

print("Building 2020 features and classifying...")
feature_stack_2020 = build_feature_stack(2020)
classified_2020 = feature_stack_2020.classify(classifier)
classified_2020_filtered = classified_2020.focal_mode(radius=1, kernelType='square')
print("✔ 2020 classification ready")
# Forest (classes 1-2) in 2020 that is no longer forest in 2024
forest_2020 = classified_2020_filtered.lte(2)
forest_2024 = classified_filtered.lte(2)
forest_loss = forest_2020.And(forest_2024.Not()).rename('forest_loss')

loss_ha = ee.Number(forest_loss.multiply(ee.Image.pixelArea()).reduceRegion(
    reducer=ee.Reducer.sum(), geometry=aoi, scale=30, maxPixels=1e13, tileScale=4
).get('forest_loss')).divide(10000).getInfo()
print(f"🌳 Forest → non-forest (2020→2024, map differencing): {loss_ha:,.0f} ha")
Map5 = geemap.Map(center=[10.0, 119.0], zoom=10)
Map5.addLayer(classified_filtered, {'min': 1, 'max': 8, 'palette': class_colors}, '2024 land cover', False)
Map5.addLayer(forest_loss.selfMask(), {'palette': ['red']}, 'Forest loss 2020–2024 (map differencing)')
Map5.addLayer(gfc.select('lossyear').gte(21).selfMask(), {'palette': ['yellow']}, 'Hansen GFC loss 2021–2024', False)
Map5.add_legend(title='Change', keys=['Map-differencing loss', 'Hansen GFC loss'], colors=['red', 'yellow'])
Map5
# Land use transitions: code = class_2020 * 10 + class_2024 (e.g. 14 = primary forest → agricultural)
change_code = classified_2020_filtered.multiply(10).add(classified_filtered).rename('change_code')

def transition_area_ha(codes):
    mask = change_code.remap(codes, [1] * len(codes), 0)
    return ee.Number(mask.multiply(ee.Image.pixelArea()).reduceRegion(
        reducer=ee.Reducer.sum(), geometry=aoi, scale=30, maxPixels=1e13, tileScale=4
    ).values().get(0)).divide(10000).getInfo()

forest_ag_ha = transition_area_ha([14, 24])
forest_mining_ha = transition_area_ha([18, 28])
print(f"Forest → Agriculture:       {forest_ag_ha:,.0f} ha")
print(f"Forest → Bare soil/mining:  {forest_mining_ha:,.0f} ha")

🎯 Exercise 2 — Sanity-check against Hansen Global Forest Change

Task: complete the TODO to compute the Hansen GFC forest loss area for 2021–2024 (lossyear 21–24) inside the AOI and compare it with loss_ha.

Expected output: two numbers in hectares. Expect the map-differencing estimate to be larger than GFC (classification errors in either year look like change); if it is many times larger, that is a sign that the classifier, not the landscape, is changing.

LOSS_FROM, LOSS_TO = 21, 24   # TODO: try other periods, e.g. 2016–2020 → 16, 20 (lossyear = year - 2000)
gfc_loss_2021_2024 = gfc.select('lossyear').gte(LOSS_FROM).And(gfc.select('lossyear').lte(LOSS_TO))

gfc_loss_ha = ee.Number(gfc_loss_2021_2024.multiply(ee.Image.pixelArea()).reduceRegion(
    reducer=ee.Reducer.sum(), geometry=aoi, scale=30, maxPixels=1e13, tileScale=4
).values().get(0)).divide(10000).getInfo()
print(f"Hansen GFC loss 2021–2024: {gfc_loss_ha:,.0f} ha  vs  map differencing: {loss_ha:,.0f} ha")

Stakeholder summary

total_area_ha = aoi.area(maxError=1).divide(10000).getInfo()

print("=" * 70)
print("CENTRAL PALAWAN — LAND COVER AND CHANGE SUMMARY (2020–2024)")
print("=" * 70)
print(f"Study area (land + sea): {total_area_ha:,.0f} ha")
print(f"Forest → non-forest (map differencing): {loss_ha:,.0f} ha  (≈ {loss_ha/4:,.0f} ha/yr)")
print(f"Hansen GFC forest loss 2021–2024:       {gfc_loss_ha:,.0f} ha")
print("\n--- 2024 land cover ---")
for name, area in area_stats.items():
    print(f"  {name:17s}: {area:10,.0f} ha ({area / total_area_ha * 100:5.2f}% of box)")
print("\n--- Accuracy (agreement with proxy labels) ---")
print(f"  Overall accuracy: {overall_accuracy*100:.1f}%   Kappa: {kappa:.3f}")
print("\nCaveats: proxy reference labels; change from map differencing includes classification error.")
print("Report generated:", datetime.now().strftime('%Y-%m-%d %H:%M'))

Export results (optional)

export_task = ee.batch.Export.image.toDrive(
    image=classified_filtered.toUint8(),
    description='Palawan_LULC_2024',
    folder='EO_Training_Exports',
    fileNamePrefix='palawan_lulc_2024',
    region=aoi,
    scale=30,
    maxPixels=1e13,
    crs='EPSG:4326'
)
print("✔ Export task configured. To start it, run: export_task.start()")
print("Then check status at: https://code.earthengine.google.com/tasks")

🎉 Lab complete

Recap

  • Seasonal composites + indices + GLCM texture + terrain → a 22-feature stack, built by one reusable function
  • Proxy labels from WorldCover + Hansen GFC give a quick 8-class training set — but they are not ground truth
  • Random Forest in Earth Engine reports variable importance and an out-of-bag error estimate via explain()
  • Per-class producer’s/user’s accuracy shows which classes (often primary vs secondary forest, grassland vs agriculture) are unreliable
  • Post-classification change detection must use identical features for both years and should be checked against an independent product

Next steps

  1. Session 3: deep learning and CNNs — features learned from pixels instead of engineered by hand
  2. Extend: replace the proxy labels with photo-interpreted or field points for your own area
  3. Production: use independent reference data and area-adjusted accuracy estimates (Olofsson et al., 2014)

EO AI/ML Training · Day 2 · Dimitrios Kasampalis (Anefelo) · CC BY-SA 4.0