Esta página também está disponível em português.

Ver em português

Tutorial · Google Earth Engine

Supervised classification with Random Forest in Google Earth Engine: a land cover map with artificial intelligence

Step by step, with complete commented code: a cloud-free Sentinel-2 image, training samples, Random Forest, confusion matrix, Kappa, area by class and export to QGIS. A real example in Chitwan, Nepal.

Imagem de satélite de Chitwan, no Nepal, que se transforma num mapa de uso do solo classificado com Random Forest
Image: Contém dados Copernicus Sentinel-2 modificados (2025). Chitwan, Nepal. Classificação Random Forest: GEOFLORESTA

What you will learn

  • Understand supervised classification and how Random Forest works
  • Prepare a cloud-free Sentinel-2 image with indices and terrain
  • Collect good training and validation samples
  • Train the model, classify the image and assess accuracy (confusion matrix and Kappa)
  • Calculate the area of each class and export the map to QGIS

Before you start

  • A Google account with access to Google Earth Engine (free for non-commercial use, at earthengine.google.com)
  • Basic remote sensing knowledge (bands and indices such as NDVI)
  • For the final step: QGIS installed (free, at qgis.org)
  • No programming experience needed: the code is complete and commented
In this tutorial
  1. What supervised classification and Random Forest are
  2. Prepare the image: cloud-free Sentinel-2, indices and terrain
  3. Collect the training samples
  4. Train the Random Forest and classify the image
  5. Assess the accuracy
  6. Variable importance and area of each class
  7. Export the map and finish in QGIS
  8. Limitations and good practice
  9. Frequently asked questions
  10. Hands-on exercise

Land use and land cover maps underpin almost every environmental study: forest inventories, impact assessments, land-use plans, deforestation monitoring and carbon projects. Today, the most widely used way to produce them from satellite imagery is supervised classification with Random Forest, an artificial intelligence (machine learning) method that is simple to apply, robust and free in Google Earth Engine.

In this tutorial you make a six-class map (forest, grassland and shrubland, cropland, built-up, sand and bare soil, and water) of the Chitwan region in Nepal: the city of Bharatpur, the Narayani and Rapti rivers, the farmland of the valley and the sal forest of Chitwan National Park, a UNESCO World Heritage Site. Once you understand the method, you apply it to your own area in any country.

1. What supervised classification and Random Forest are

In supervised classification, the analyst “teaches” the computer. First, you give examples of each class: points or polygons where you know there is forest, water, cropland and so on. The algorithm learns how each class looks in the image bands and then assigns a class to every pixel. This differs from unsupervised classification (for example k-means), where the computer groups the pixels by itself and the analyst only names the groups at the end.

Random Forest, proposed by Leo Breiman in 2001, is an ensemble of many decision trees. Each tree asks the data simple questions (“is NDVI greater than 0.6?”, “is the SWIR band lower than 0.1?”) until it reaches a class. To keep the trees from being identical, each one learns from a random sample of the examples and, at each question, can only choose among a few randomly drawn variables. In the end, the trees vote and the class with the most votes wins.

Why it is so popular in remote sensing:

  • It performs well with few samples and copes with some noise in the data.
  • It accepts very different variables (reflectances, indices, elevation, slope) without normalising them.
  • It needs almost no tuning: 100 to 500 trees and the default settings usually work.
  • It reports the importance of each variable, which helps you understand the model.

2. Prepare the image: cloud-free Sentinel-2, indices and terrain

Open the Earth Engine Code Editor, create a new script and paste the first block. The code defines the area, gathers every Sentinel-2 image from October and November 2025 (the start of the dry season in Nepal), removes clouds with Cloud Score+ and computes the median of each pixel. We also add NDVI (vegetation), NDWI (water), elevation and slope from NASADEM. These extra variables help the model a lot to separate similar classes.

// 1. Study area: Chitwan (Nepal). For another area, change the rectangle
// or draw a polygon.
var area = ee.Geometry.Rectangle([84.25, 27.45, 84.65, 27.75]);
Map.centerObject(area, 11);

// 2. Dry-season, cloud-free Sentinel-2 surface reflectance in a single
// image (median).
var csPlus = ee.ImageCollection('GOOGLE/CLOUD_SCORE_PLUS/V1/S2_HARMONIZED');
var s2 = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
  .filterBounds(area)
  .filterDate('2025-10-01', '2025-11-30')
  .linkCollection(csPlus, ['cs_cdf'])
  .map(function (img) {
    // Cloud Score+: keep only pixels scoring >= 0.6 (clear sky); reflectance
    // from 0 to 1.
    return img.updateMask(img.select('cs_cdf').gte(0.6))
      .select(['B2', 'B3', 'B4', 'B8', 'B11', 'B12'])
      .divide(10000);
  })
  .median();

// 3. Extra variables: vegetation and water indices, elevation and slope.
var ndvi = s2.normalizedDifference(['B8', 'B4']).rename('NDVI');
var ndwi = s2.normalizedDifference(['B3', 'B8']).rename('NDWI');
var elevation = ee.Image('NASA/NASADEM_HGT/001').select('elevation');
var slope = ee.Terrain.slope(elevation).rename('slope');

var image = s2.addBands([ndvi, ndwi, elevation, slope]).clip(area);
var bands = image.bandNames();
print('Variables', bands);

Map.addLayer(image, {bands: ['B4', 'B3', 'B2'], min: 0, max: 0.15}, 'Sentinel-2 natural colour');
Map.addLayer(image, {bands: ['B8', 'B11', 'B4'], min: 0, max: 0.4}, 'Sentinel-2 false colour', false);

Click Run. The image appears on the map; also turn on the false-colour layer in the layer manager. In false colour, vegetation shows in orange and brown, water in deep blue and cropland and built-up areas in light blue.

Sentinel-2 composite of Chitwan in natural colour and false colour
Figure 1. Sentinel-2 median for October and November 2025 in Chitwan (about 40 × 33 km). Left, natural colour; right, false colour (NIR, SWIR, red), where forest, fields, rivers and towns are easy to tell apart.

3. Collect the training samples

Samples are the most important part of the job: a model is never better than the samples it learns from. There are two ways to get them.

Option A: draw the samples (recommended for real work). On the Code Editor map, hover over Geometry Imports and click + new layer. In the layer’s gear icon, rename it forest, choose Import as: FeatureCollection and add a landcover property with the value 0. Repeat for the other classes:

landcover valueLayer nameClassWhere to look in Chitwan
0forestForestThe National Park (south of the Rapti) and the northern slopes
1grasslandGrassland and shrublandTall grasslands along the Rapti and Narayani
2croplandCroplandValley fields around Bharatpur and Ratnanagar
3builtupBuilt-upCentral Bharatpur, roads and villages
4sandSand and bare soilSand and gravel bars in the riverbeds
5waterWaterThe Narayani and Rapti rivers and lakes

Draw small polygons (or points) well inside each class and merge them with this block:

// 4A. Samples you drew: merge the six collections (landcover property from
// 0 to 5).
var samples = forest.merge(grassland).merge(cropland)
  .merge(builtup).merge(sand).merge(water);

Tips for good samples:

  • Quantity: at least 30 to 50 polygons or 100 points per class, especially for the harder classes.
  • Distribution: spread the samples across the whole area, not just one corner of the image.
  • Purity: draw away from class boundaries, so that each polygon holds a single class.
  • Variety: include the variations within each class (dense and open forest, fields with and without crops, wide and narrow rivers).
  • Check: use the high-resolution basemap (Satellite) and, if you can, field data.

Option B: automatic samples (to test right away). To see the method working before drawing, generate 250 points per class from the ESA WorldCover 2021 map, only on “pure” pixels (in the middle of a 5 × 5 pixel window of the same class). Use only one option: A or B.

// 4B. Automatic samples from ESA WorldCover 2021 (to test right away).
var worldcover = ee.ImageCollection('ESA/WorldCover/v200').first()
  .remap([10, 20, 30, 40, 50, 60, 80], [0, 1, 1, 2, 3, 4, 5])
  .rename('landcover');
// Only pixels in the middle of a 5 x 5 window of the same class ("pure"
// samples).
var pure = worldcover.reduceNeighborhood({
  reducer: ee.Reducer.countDistinct(),
  kernel: ee.Kernel.square(2)
}).eq(1);
var samples = worldcover.updateMask(pure).stratifiedSample({
  numPoints: 250, classBand: 'landcover', region: area,
  scale: 20, seed: 42, geometries: true
});

Option B is great for learning and for a first version of the map, but it has a limit: the model also learns WorldCover’s errors and any changes since 2021 (for example, rivers that have shifted course).

Training and validation samples of the six classes over the Sentinel-2 image of Chitwan
Figure 2. The 1,500 samples (250 per class) generated with option B: circles for training (70%) and triangles for validation (30%).

4. Train the Random Forest and classify the image

This block reads the values of the 10 variables at each sample, randomly splits them into 70% for training and 30% for validation, trains a Random Forest with 100 trees and classifies the whole image.

// 5. Variable values at each sample.
var data = image.sampleRegions({
  collection: samples, properties: ['landcover'], scale: 20, geometries: true
}).randomColumn('random', 42);

// 70% for training and 30% for validation.
var training = data.filter(ee.Filter.lt('random', 0.7));
var validation = data.filter(ee.Filter.gte('random', 0.7));
print('Training samples', training.size(), 'validation', validation.size());

// 6. Train the Random Forest (100 trees) and classify the image.
var classifier = ee.Classifier.smileRandomForest({numberOfTrees: 100, seed: 42})
  .train({features: training, classProperty: 'landcover', inputProperties: bands});

var classified = image.classify(classifier);
var palette = ['1f6b3a', 'a9c25d', 'f2c14e', 'd1495b', 'd8c8a8', '2f7fc1'];
Map.addLayer(classified, {min: 0, max: 5, palette: palette}, 'Random Forest');

Within seconds, the “Random Forest” layer appears on the map. Compare it with the image: toggle the layer on and off and look for misclassified areas. If you find systematic errors, add samples in those places and run the script again. Improving the samples is an iterative process.

Land cover map of Chitwan classified with Random Forest
Figure 3. Random Forest result for Chitwan, with 20 m pixels. The forest of the National Park (south) and the slopes (north) contrasts with the farmed valley, the city of Bharatpur and the Narayani and Rapti rivers.

5. Assess the accuracy

A map without an accuracy assessment cannot be used with confidence. We now classify the validation samples, which the model did not see during training, and compare the predicted class with the true one:

// 7. Accuracy with the validation samples (which the model has not seen).
var tested = validation.classify(classifier);
var matrix = tested.errorMatrix('landcover', 'classification');
print('Confusion matrix', matrix);
print('Overall accuracy', matrix.accuracy());
print('Kappa', matrix.kappa());
print('Producer’s accuracy', matrix.producersAccuracy());
print('User’s accuracy', matrix.consumersAccuracy());

How to read the results:

  • Confusion matrix: rows are the true class and columns the predicted class. The diagonal shows the correct answers; the rest shows which classes get confused.
  • Overall accuracy: the percentage of correctly classified samples. Above 85% is generally a good result for land cover maps.
  • Kappa index: measures agreement after removing what would be expected by chance. Above 0.8 is considered strong agreement.
  • Producer’s accuracy: of all the forest that exists, how much the map captured (omission errors).
  • User’s accuracy: of what the map calls forest, how much really is forest (commission errors). This is what matters to the map user. The console shows it as “List (1 element)”: expand the arrow to see the six values.
Random Forest confusion matrix for Chitwan and variable importance chart
Figure 4. Left, the confusion matrix of the 450 validation samples: overall accuracy of 84.9% and Kappa of 0.82. Right, the relative importance of each variable in the model.

In our test, forest was the most reliable class (99% user’s accuracy). The main confusions were between sand and water, in riverbeds that shift from year to year, and between cropland and grassland, which can look very similar at the end of the rainy season. That is where it pays to add samples or variables, such as imagery from another season.

The figures were produced by GEOFLORESTA with the same Sentinel-2 data, the same variables, the option B samples and a 100-tree Random Forest. Running the script in Earth Engine gave the same 84.9% and a Kappa of 0.82. If you change the samples, the area or the seed, the numbers will shift slightly.

6. Variable importance and area of each class

// 8. Importance of each variable.
var importance = ee.Dictionary(classifier.explain().get('importance'));
print(ui.Chart.feature.byProperty(ee.Feature(null, importance))
  .setChartType('ColumnChart')
  .setOptions({title: 'Variable importance', legend: {position: 'none'}}));

// 9. Area of each class, in hectares.
var areas = ee.Image.pixelArea().divide(10000).addBands(classified)
  .reduceRegion({
    reducer: ee.Reducer.sum().group({groupField: 1, groupName: 'landcover'}),
    geometry: area, scale: 20, maxPixels: 1e10
  });
print('Area by class (ha)', areas.get('groups'));

The chart shows how much each variable contributed to separating the classes. In Chitwan, NDVI and NDWI were the most useful variables, followed by the blue band (B2) and elevation, which helps separate hillside forest from valley fields. If a variable has very low importance, you can try removing it.

The areas appear in the console as a list of classes (0 to 5) with the sum in hectares. In our result:

ClassArea (ha)% of area
Forest77,05256.2
Cropland37,91627.7
Grassland and shrubland10,4927.7
Built-up6,4964.7
Sand and bare soil3,0032.2
Water2,0411.5

Note: area counted pixel by pixel carries the classification errors. In reports, it is better to adjust the areas with the confusion matrix (the method of Olofsson et al., 2014), which also gives a confidence interval for each area.

7. Export the map and finish in QGIS

// 10. Export the map to Google Drive (GeoTIFF, UTM 45N). Run it from the
// Tasks tab.
Export.image.toDrive({
  image: classified.toByte(),
  description: 'random_forest_chitwan_2025',
  folder: 'GEOFLORESTA',
  region: area,
  scale: 20,
  crs: 'EPSG:32645',
  maxPixels: 1e10
});

After running the script, open the Tasks tab (on the right) and click Run on the random_forest_chitwan_2025 task. The GeoTIFF lands in the GEOFLORESTA folder of your Google Drive, in UTM 45N (EPSG:32645). For another area, replace the EPSG with the matching UTM zone.

  1. Drag the file into QGIS.
  2. In Properties → Symbology, choose Paletted/Unique values, click Classify and give each value (0 to 5) its class name and colour.
  3. Add the legend, scale bar, north arrow and source (“Sentinel-2, ESA/Copernicus; Random Forest classification in Google Earth Engine”) in the Print Layout.
  4. To vectorise the result, use Raster → Conversion → Polygonize.

Prefer the full script in a single file? Download it, paste it into the Code Editor and click Run. Option B is active and option A is commented out.

Download the full script (.js)

8. Limitations and good practice

  • Neighbouring samples inflate accuracy. Training and validation points that are very close together are nearly identical, so accuracy looks better than it is. In real work, validate with independent samples, ideally collected in the field or split by polygon rather than by pixel.
  • Rare classes get overestimated when every class has the same number of samples. In Chitwan, grassland covers 7.7% of the map, more than in WorldCover. Check against high-resolution imagery and adjust the samples.
  • One season is not always enough. Crops, grasslands and bare soil change through the year. Combining medians from two seasons (dry and wet) often improves separation.
  • Clouds and shadows: in very cloudy regions, widen the date range or add Sentinel-1 radar imagery, which sees through clouds.
  • Commercial use: Earth Engine is free for research, education and non-profit organisations; commercial use requires a licence.

9. Frequently asked questions

How many trees should I use? Between 100 and 500. Beyond that, accuracy barely changes and computation gets slower.

Can I use Landsat instead of Sentinel-2? Yes. Replace the collection with LANDSAT/LC09/C02/T1_L2 (or Landsat 8’s), adapt the band names and scaling, and use 30 m. This is useful for maps from before 2017.

Does it work in another country? Yes, anywhere in the world. Change the area, the dates (choose your country’s dry season) and the export EPSG, and collect samples from your region.

Random Forest or deep learning? Deep neural networks can be more accurate on very high-resolution imagery, but they need thousands of samples and powerful computers. For Sentinel-2 and Landsat, Random Forest remains one of the best choices.

Need a field-validated land cover map, a multi-year change analysis or training for your team? Request a proposal from GEOFLORESTA.

Hands-on exercise

1. Run the full script with option B and note the overall accuracy and Kappa you get. 2. Change the area to your district (replace the rectangle and set the dates to your country’s dry season) and run it again. 3. Draw your own samples (option A), with at least 30 polygons per class, and compare the accuracy with option B. 4. Remove elevation and slope from the image and see how accuracy and variable importance change. 5. Export the map, open it in QGIS next to ESA WorldCover and describe the three largest differences.

Key points

  • Random Forest combines many voting decision trees; it is robust, fast and needs little tuning
  • Map quality depends mostly on the training samples: quantity, distribution, purity and variety
  • Indices (NDVI, NDWI) and terrain help a lot to separate similar classes
  • Always validate with samples the model has not seen and report the confusion matrix, overall accuracy and Kappa
  • For reports, adjust areas with the confusion matrix rather than just counting pixels

Sources and documentation

  1. Breiman, L. (2001). Random Forests. Machine Learning 45, 5–32
  2. Belgiu, M. & Drăguţ, L. (2016). Random forest in remote sensing: a review of applications and future directions
  3. Olofsson, P. et al. (2014). Good practices for estimating area and assessing accuracy of land change
  4. Google Earth Engine: Supervised Classification
  5. Copernicus Sentinel-2 Surface Reflectance (Harmonized)
  6. Cloud Score+ S2_HARMONIZED
  7. ESA WorldCover 10 m 2021 v200
  8. NASADEM

Need a map, a study or training for your project?