# Earth Engine API and geemap are pre-installed on Colab; this makes sure they are present elsewhere
%pip install -q earthengine-api geemapSession 1 Lab: Palawan Land Cover Classification with Random Forest
Day 2 · Session 1 (Part B) | Duration: ~90 minutes | Instructor: Dimitrios Kasampalis (Anefelo)
Learning objectives
By the end of this lab you will be able to:
- Authenticate and initialise Google Earth Engine (GEE) from Python
- Build a cloud-masked Sentinel-2 median composite (Cloud Score+ masking)
- Calculate spectral indices (NDVI, NDWI, NDBI, EVI)
- Derive training and validation samples from an open reference map (ESA WorldCover)
- Train a Random Forest classifier in GEE and classify Palawan
- Assess accuracy (overall, kappa, producer’s/user’s accuracy) and compute class areas
What you’ll need
- A Google account with Earth Engine access and a Google Cloud project registered for Earth Engine (free for non-commercial and research use — see the access guide)
- Google Colab (CPU runtime is enough — all heavy computation runs on Earth Engine servers)
- No local data: everything is read from the Earth Engine catalogue
Study area: Palawan Province
- UNESCO Biosphere Reserve (since 1990), high biodiversity, critical for conservation
- Pressures: deforestation, mining, agricultural expansion, coastal development
- We use a simple bounding box around the province (it includes sea and a few neighbouring islands)
A. Setup and Authentication
# Import all libraries
import os
import ee
import geemap
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# Set plot style
plt.style.use('seaborn-v0_8-darkgrid')
sns.set_palette("husl")
print("✓ Libraries imported successfully")# Authenticate and initialise Earth Engine
# Earth Engine requires a Google Cloud project registered for Earth Engine use.
# 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() # opens a sign-in prompt the first time
ee.Initialize(project=PROJECT_ID)
print(f"✓ Earth Engine initialised (project: {PROJECT_ID})")B. Define Study Area
# Define a bounding box around Palawan (lon, lat)
palawan_coords = [
[117.0, 8.5], # Southwest
[117.0, 12.5], # Northwest
[120.5, 12.5], # Northeast
[120.5, 8.5], # Southeast
[117.0, 8.5] # Close polygon
]
palawan = ee.Geometry.Polygon(palawan_coords)
# Area of the box (land + sea)
area_km2 = palawan.area(maxError=1).divide(1e6).getInfo()
print("Study area: Palawan Province (bounding box)")
print(f"Box area (incl. sea): {area_km2:,.0f} km²")# Create interactive map
Map = geemap.Map(center=[10.5, 118.8], zoom=8, height='600px')
Map.addLayer(palawan, {'color': 'red'}, 'Palawan Boundary')
MapC. Sentinel-2 Data Acquisition
# Date range: one full year of imagery
start_date = '2024-01-01'
end_date = '2025-01-01' # filterDate end is exclusive
# Bands used throughout the lab
BANDS = ['B2', 'B3', 'B4', 'B8', 'B11', 'B12']
# Cloud masking with Cloud Score+ (recommended by Google for Sentinel-2; the old QA60 band
# was not populated between January 2022 and February 2024, so QA60-based masks fail for that period)
CS_PLUS = ee.ImageCollection('GOOGLE/CLOUD_SCORE_PLUS/V1/S2_HARMONIZED')
CLEAR_THRESHOLD = 0.60 # 0 = certainly cloudy, 1 = certainly clear
def mask_s2_clouds(image):
"""Keep clear pixels and scale reflectance to 0-1."""
clear = image.select('cs_cdf').gte(CLEAR_THRESHOLD)
return image.select(BANDS).updateMask(clear).divide(10000)
print(f"Date range: {start_date} to {end_date} (end exclusive)")# Load Sentinel-2 surface reflectance, attach the Cloud Score+ band and mask clouds
s2_collection = (ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
.filterBounds(palawan)
.filterDate(start_date, end_date)
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 40))
.linkCollection(CS_PLUS, ['cs_cdf'])
.map(mask_s2_clouds))
# Median composite of the clear pixels
s2_composite = s2_collection.median().clip(palawan)
print("✓ Sentinel-2 composite created")
print(f"Images in collection: {s2_collection.size().getInfo()}")# Visualize RGB composite
rgb_vis = {'bands': ['B4', 'B3', 'B2'], 'min': 0.0, 'max': 0.3, 'gamma': 1.4}
Map.addLayer(s2_composite, rgb_vis, 'Sentinel-2 RGB')
MapD. Calculate Spectral Indices
# Calculate all indices
ndvi = s2_composite.normalizedDifference(['B8', 'B4']).rename('NDVI')
ndwi = s2_composite.normalizedDifference(['B3', 'B8']).rename('NDWI')
ndbi = s2_composite.normalizedDifference(['B11', 'B8']).rename('NDBI')
evi = s2_composite.expression(
'2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))',
{
'NIR': s2_composite.select('B8'),
'RED': s2_composite.select('B4'),
'BLUE': s2_composite.select('B2')
}
).rename('EVI')
print("✓ Spectral indices calculated")E. Feature Stack Preparation
# Create feature stack
feature_stack = (s2_composite
.addBands(ndvi)
.addBands(ndwi)
.addBands(ndbi)
.addBands(evi))
feature_names = feature_stack.bandNames().getInfo()
print(f"✓ Feature stack created with {len(feature_names)} features")
print(f"Features: {feature_names}")F. Training Data from an Open Reference Map
Collecting field data is out of scope for a 90-minute lab, so we derive labels from ESA WorldCover 2021 (v200) — a 10 m global land cover map with a reported global overall accuracy of about 77%. WorldCover classes are re-mapped to our 5 classes; classes we don’t model (shrubland, grassland, bare, wetland, …) are excluded from sampling.
⚠️ Important caveat: labels taken from another map inherit its errors, and validating against the same map only measures agreement with WorldCover, not true accuracy. For operational work use independent reference data (field plots, photo-interpretation of very-high-resolution imagery).
# Define class properties
class_info = {
1: {'name': 'Forest', 'color': '006400'},
2: {'name': 'Agriculture', 'color': 'FFFF00'},
3: {'name': 'Water', 'color': '0000FF'},
4: {'name': 'Urban', 'color': 'FF0000'},
5: {'name': 'Mangrove', 'color': '008B8B'}
}
print("Land Cover Classes:")
for class_id, info in class_info.items():
print(f" {class_id}: {info['name']}")# Load ESA WorldCover 2021 (v200 is a single 2021 image)
worldcover = ee.ImageCollection('ESA/WorldCover/v200').first().clip(palawan)
# Remap WorldCover codes to our classes (0 = not used for training)
# 10 Tree cover → 1 Forest | 40 Cropland → 2 Agriculture | 80 Permanent water → 3 Water
# 50 Built-up → 4 Urban | 95 Mangroves → 5 Mangrove
# 20 Shrubland, 30 Grassland, 60 Bare, 70 Snow, 90 Herbaceous wetland, 100 Moss → 0 (excluded)
worldcover_remapped = worldcover.remap(
[10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100],
[1, 0, 0, 2, 4, 0, 0, 3, 0, 5, 0],
0
).rename('landcover')
print("✓ ESA WorldCover 2021 loaded and remapped to 5 classes")# Generate stratified random training points (up to 500 per class)
training_points = worldcover_remapped.stratifiedSample(
numPoints=500,
classBand='landcover',
region=palawan,
scale=30,
seed=42,
geometries=True,
tileScale=4
).filter(ee.Filter.neq('landcover', 0))
print(f"✓ Training points generated: {training_points.size().getInfo()} total")# Add extra urban samples around the main towns (urban is a small, easily under-sampled class).
# We only keep pixels that WorldCover maps as built-up inside a buffer around each town centre.
town_centres = {
'Puerto Princesa': ([118.7438, 9.7399], 5000),
'Taytay': ([119.5179, 10.8250], 2000),
'El Nido': ([119.3905, 11.1800], 2000),
'Bataraza': ([117.6287, 8.6733], 2000),
}
urban_zone = ee.FeatureCollection([
ee.Feature(ee.Geometry.Point(lonlat).buffer(radius_m), {'town': name})
for name, (lonlat, radius_m) in town_centres.items()
]).geometry()
urban_points = (worldcover_remapped.updateMask(worldcover_remapped.eq(4))
.stratifiedSample(numPoints=200, classBand='landcover', region=urban_zone,
scale=10, seed=42, geometries=True))
# Combine all training points
all_training_points = training_points.merge(urban_points)
print(f"✓ Final training dataset: {all_training_points.size().getInfo()} points")
print(all_training_points.aggregate_histogram('landcover').getInfo())# Sample spectral values from training points
training_samples = feature_stack.sampleRegions(
collection=all_training_points,
properties=['landcover'],
scale=10,
geometries=False,
tileScale=4
)
print(f"✓ Training samples extracted: {training_samples.size().getInfo()} pixels")# Visualize training points
Map_training = geemap.Map(center=[10.5, 118.8], zoom=8, height='600px')
Map_training.addLayer(s2_composite, rgb_vis, 'Sentinel-2 RGB')
for class_id, info in class_info.items():
class_points = all_training_points.filter(ee.Filter.eq('landcover', class_id))
Map_training.addLayer(class_points, {'color': info['color']}, f"Training: {info['name']}")
Map_trainingG. Random Forest Training
# Train Random Forest classifier
rf_classifier = ee.Classifier.smileRandomForest(
numberOfTrees=100,
variablesPerSplit=None,
minLeafPopulation=1,
bagFraction=0.632,
seed=42
)
trained_classifier = rf_classifier.train(
features=training_samples,
classProperty='landcover',
inputProperties=feature_names
)
print("✓ Random Forest training complete")H. Image Classification
# Apply classifier
classified_image = feature_stack.classify(trained_classifier)
# Define palette
class_palette = [class_info[i]['color'] for i in sorted(class_info.keys())]
# Visualize
Map_classified = geemap.Map(center=[10.5, 118.8], zoom=8, height='700px')
Map_classified.addLayer(s2_composite, rgb_vis, 'Sentinel-2 RGB', False)
Map_classified.addLayer(classified_image, {'min': 1, 'max': 5, 'palette': class_palette}, 'Land Cover')
print("✓ Classification complete")
Map_classifiedI. Accuracy Assessment
# Create a validation dataset with a different seed.
# Note: points come from the same reference map, so this measures agreement with WorldCover.
validation_points = worldcover_remapped.stratifiedSample(
numPoints=100,
classBand='landcover',
region=palawan,
scale=30,
seed=123, # different seed from training
geometries=True,
tileScale=4
).filter(ee.Filter.neq('landcover', 0))
validation_samples = feature_stack.sampleRegions(
collection=validation_points,
properties=['landcover'],
scale=10,
geometries=False,
tileScale=4
)
# Classify validation set and build the error (confusion) matrix
validation_classified = validation_samples.classify(trained_classifier)
confusion_matrix = validation_classified.errorMatrix('landcover', 'classification')
overall_accuracy = confusion_matrix.accuracy().getInfo()
kappa = confusion_matrix.kappa().getInfo()
print(f"Overall Accuracy: {overall_accuracy*100:.2f}%")
print(f"Kappa Coefficient: {kappa:.4f}")
# Per-class accuracies. errorMatrix rows/columns are indexed by class value (0..5); drop the unused 0
cm = np.array(confusion_matrix.getInfo())[1:, 1:]
names = [class_info[i]['name'] for i in sorted(class_info)]
producers = np.diag(cm) / cm.sum(axis=1).clip(min=1) # recall
users = np.diag(cm) / cm.sum(axis=0).clip(min=1) # precision
print(pd.DataFrame(cm, index=[f"ref {n}" for n in names], columns=[f"map {n}" for n in names]))
print(pd.DataFrame({"Producer's acc.": producers.round(3), "User's acc.": users.round(3)}, index=names))J. Area Statistics
# Area per class (km²). A 100 m scale keeps this interactive; use 10 m in an export for final numbers.
pixel_area = ee.Image.pixelArea().divide(1e6) # km² per pixel
area_image = pixel_area.addBands(classified_image)
area_stats = area_image.reduceRegion(
reducer=ee.Reducer.sum().group(groupField=1, groupName='landcover'),
geometry=palawan,
scale=100,
maxPixels=1e10,
tileScale=4
)
print("Calculating area statistics (about a minute)...")
area_table = pd.DataFrame(area_stats.get('groups').getInfo())
area_table['class'] = area_table['landcover'].map(lambda c: class_info[int(c)]['name'])
area_table = area_table.rename(columns={'sum': 'area_km2'})[['class', 'area_km2']]
print(area_table.round(1).to_string(index=False))K. Export Results
# Export the classification to Google Drive (runs as a background task on Earth Engine)
export_classification = ee.batch.Export.image.toDrive(
image=classified_image.toByte(),
description='Palawan_LandCover_Classification',
folder='EarthEngine',
fileNamePrefix='palawan_landcover_2024',
region=palawan,
scale=10,
crs='EPSG:4326',
maxPixels=1e10,
fileFormat='GeoTIFF'
)
print("✓ Export configured")
print("To start the export, run: export_classification.start()")
print("Check progress at: https://code.earthengine.google.com/tasks")L. Exercises
Each exercise is self-contained — edit the line marked # TODO, run the cell, compare with the expected output.
Exercise 1 — Number of trees
Task: change N_TREES to 10, 50 and 200 and re-run.
Expected output: overall accuracy changes by only one or two percentage points once you have ~50 trees; 10 trees is usually noticeably less stable. More trees = slower, rarely much better.
N_TREES = 100 # TODO: try 10, 50, 200
clf = ee.Classifier.smileRandomForest(numberOfTrees=N_TREES, seed=42).train(
features=training_samples, classProperty='landcover', inputProperties=feature_names)
acc = validation_samples.classify(clf).errorMatrix('landcover', 'classification').accuracy().getInfo()
print(f"{N_TREES} trees → overall accuracy {acc*100:.2f}%")Exercise 2 — Which features matter?
Task: inspect the Random Forest variable importance, then set FEATURES to only the raw bands (['B2', 'B3', 'B4', 'B8', 'B11', 'B12']) and compare the accuracy with the full feature set.
Expected output: a dictionary of importance scores (vegetation indices and SWIR bands usually rank high); removing the indices typically costs a few points of accuracy, mostly for water/urban/mangrove.
importance = trained_classifier.explain().get('importance').getInfo()
for name, score in sorted(importance.items(), key=lambda kv: -kv[1]):
print(f"{name:6s} {score:8.1f}")
FEATURES = feature_names # TODO: try ['B2', 'B3', 'B4', 'B8', 'B11', 'B12']
clf = ee.Classifier.smileRandomForest(numberOfTrees=100, seed=42).train(
features=training_samples, classProperty='landcover', inputProperties=FEATURES)
acc = validation_samples.classify(clf).errorMatrix('landcover', 'classification').accuracy().getInfo()
print(f"\nFeatures used: {FEATURES}\nOverall accuracy: {acc*100:.2f}%")Exercise 3 — Classify another Philippine region (optional)
Task: replace the Palawan box with another area (e.g. Bohol: ee.Geometry.Rectangle([123.7, 9.5, 124.65, 10.2])), re-run sections B–I, and look at which classes behave differently.
Expected output: a new map and accuracy figures; class balance (e.g. less mangrove, more cropland) changes the per-class accuracies.
Exercise 4 — Export (optional)
Run export_classification.start() and follow the task in the Tasks page. Expected output: a GeoTIFF named palawan_landcover_2024*.tif in the EarthEngine folder of your Google Drive.
Recap
- Sentinel-2 composite + spectral indices → a 10-feature stack per pixel
- Labels from an open reference map are fast to obtain but are not independent ground truth
- Random Forest in GEE:
smileRandomForest→train→classify→errorMatrix - Always report per-class (producer’s/user’s) accuracy, not just overall accuracy
Next: Session 2 adds seasonal composites, texture, terrain, an 8-class scheme and change detection.
EO AI/ML Training · Day 2 · Dimitrios Kasampalis (Anefelo) · CC BY-SA 4.0