I am creating training and test data for a Random Forest model using Google Earth Engine (Python API).
I have used stratifiedSample() to create a Feature Collection of sample points within my training polygons. I would like to use randomColumn() to assign a pseudo-random float to each feature so I can then split them into training and test sets using a threshold.
How do I ensure the random numbers are assigned per strata, in this case per the column class
?
I see that ee.Reducer has a group method but this is not applicable for Feature Collections.
My current code, in which I am unsure if the strata were respected when adding the randomColumn
:
## make a feature collection of training polygons
fc = ee.FeatureCollection(polygons)
## create an empty object to hold stratified points
classes = ee.Image().byte().paint(polygons, "class").rename("class")
## stratify sample points per feature
stratified = classes.addBands(ee.Image.pixelLonLat()).stratifiedSample(
numPoints = 1000,
classBand = 'class',
projection = 'EPSG:4326',
scale = 10,
region = fc,
geometries = True
)
## add a random number to each feature
stratified = stratified.randomColumn()
## sample image using stratified points ('random' is the default column name given by randomColumn)
sample = img.select(train_bands).sampleRegions(collection=stratified, properties=['class', 'random'], scale=10)
## define fraction for training (remainder is for testing)
split = 0.7
## divide into training and testing sets based on the split
training = sample.filter(ee.Filter.lt('random', split))
validation = sample.filter(ee.Filter.gte('random', split))