import ee
import geemap
Supervised Classification of National Landcover
Note: the following notebook is taken verbatim from Dr. Qiusheng Wu’s geemap
website with only extremely minor modifications. I have removed the image download at the end and added a model evaluation step, but otherwise it remains his work.
Supervised classification algorithms available in Earth Engine
Source: https://developers.google.com/earth-engine/classification
The Classifier
package handles supervised classification by traditional ML algorithms running in Earth Engine. These classifiers include CART, RandomForest, NaiveBayes and SVM. The general workflow for classification is:
- Collect training data. Assemble features which have a property that stores the known class label and properties storing numeric values for the predictors.
- Instantiate a classifier. Set its parameters if necessary.
- Train the classifier using the training data.
- Classify an image or feature collection.
- Estimate classification error with independent validation data.
The training data is a FeatureCollection
with a property storing the class label and properties storing predictor variables. Class labels should be consecutive, integers starting from 0. If necessary, use remap() to convert class values to consecutive integers. The predictors should be numeric.
Step-by-step tutorial
Import libraries
Authenticate and Initialize Earth Engine
ee.Authenticate()
True
='remotesensing-musa6500') ee.Initialize(project
Create an interactive map
= geemap.Map()
Map Map
Add data to the map
= ee.Geometry.Point([-122.4439, 37.7538])
point # point = ee.Geometry.Point([-87.7719, 41.8799])
= (
image "LANDSAT/LC08/C01/T1_SR")
ee.ImageCollection(
.filterBounds(point)"2016-01-01", "2016-12-31")
.filterDate("CLOUD_COVER")
.sort(
.first()"B[1-7]")
.select(
)
= {"min": 0, "max": 3000, "bands": ["B5", "B4", "B3"]}
vis_params
8)
Map.centerObject(point, "Landsat-8") Map.addLayer(image, vis_params,
Check image properties
"system:time_start")).format("YYYY-MM-dd").getInfo() ee.Date(image.get(
'2016-11-18'
"CLOUD_COVER").getInfo() image.get(
0.08
Make training dataset
There are several ways you can create a region for generating the training dataset.
- Draw a shape (e.g., rectangle) on the map and the use
region = Map.user_roi
- Define a geometry, such as
region = ee.Geometry.Rectangle([-122.6003, 37.4831, -121.8036, 37.8288])
- Create a buffer zone around a point, such as
region = ee.Geometry.Point([-122.4439, 37.7538]).buffer(10000)
- If you don’t define a region, it will use the image footprint by default
# region = Map.user_roi
# region = ee.Geometry.Rectangle([-122.6003, 37.4831, -121.8036, 37.8288])
# region = ee.Geometry.Point([-122.4439, 37.7538]).buffer(10000)
In this example, we are going to use the USGS National Land Cover Database (NLCD) to create label dataset for training
= ee.Image("USGS/NLCD/NLCD2016").select("landcover").clip(image.geometry())
nlcd "NLCD")
Map.addLayer(nlcd, {}, Map
# Make the training dataset.
= nlcd.sample(
points **{
"region": image.geometry(),
"scale": 30,
"numPixels": 5000,
"seed": 0,
"geometries": True, # Set this to False to ignore geometries
}
)
"training", False) Map.addLayer(points, {},
print(points.size().getInfo())
3583
print(points.first().getInfo())
{'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [-122.25798986874739, 38.2706212827936]}, 'id': '0', 'properties': {'landcover': 31}}
Train the classifier
# Randomly split the sample into 70% training and 30% validation
= points.randomColumn() # Adds a random column to each feature
sample = sample.filter(ee.Filter.lt('random', 0.7))
trainingSample = sample.filter(ee.Filter.gte('random', 0.7))
validationSample
# Use these bands for prediction.
= ["B1", "B2", "B3", "B4", "B5", "B6", "B7"]
bands
# This property of the table stores the land cover labels.
= "landcover"
label
# Overlay the points on the imagery to get training.
= image.select(bands).sampleRegions(
training =trainingSample,
collection=[label],
properties=30
scale
)= ee.Classifier.smileCart().train(training, label, bands) trained
Evaluate accuracy and kappa coefficient
# Classify the validation sample
= image.select(bands).sampleRegions(
validation =validationSample,
collection=[label],
properties=30
scale
)= validation.classify(trained)
validated
# Compare the classified values against the actual labels
= validated.errorMatrix(label, 'classification')
errorMatrix
# compute overall accuracy
print('Overall Accuracy:', errorMatrix.accuracy().getInfo())
# Compute Kappa statistic
print('Kappa Coefficient:', errorMatrix.kappa().getInfo())
Overall Accuracy: 0.5014084507042254
Kappa Coefficient: 0.4326718191339521
print(training.first().getInfo())
{'type': 'Feature', 'geometry': None, 'id': '0_0', 'properties': {'B1': 575, 'B2': 814, 'B3': 1312, 'B4': 1638, 'B5': 1980, 'B6': 2091, 'B7': 1967, 'landcover': 31}}
Classify the image
# Classify the image with the same bands used for training.
= image.select(bands).classify(trained)
result
# # Display the clusters with random colors.
"classified")
Map.addLayer(result.randomVisualizer(), {}, Map
Render categorical map
To render a categorical map, we can set two image properties: landcover_class_values
and landcover_class_palette
. We can use the same style as the NLCD so that it is easy to compare the two maps.
= nlcd.get("landcover_class_values").getInfo() class_values
= nlcd.get("landcover_class_palette").getInfo() class_palette
= result.set("classification_class_values", class_values)
landcover = landcover.set("classification_class_palette", class_palette) landcover
"Land cover")
Map.addLayer(landcover, {}, Map
Visualize the result
print("Change layer opacity:")
= Map.layers[-1]
cluster_layer =(0, 1, 0.1)) cluster_layer.interact(opacity
Change layer opacity:
Add a legend to the map
="NLCD")
Map.add_legend(builtin_legend Map