The link to my code is included here but I will paste it as well: https://code.earthengine.google.com/c9b3aec923007e896a3a079446001dac
I am trying to dynamically classify ground cover using supervised random forest classification. Meaning, I want to be able to enter any coordinates and have the model classify the area. I thought by changing the "roi" (region of interest) variable I have setup I could do this but I get the error "No valid training data" because my training points are outside the new roi. Is it possible to save the "training" for the model and reuse it at any given roi?
Code:
// Random Forest Supervised Classification
//Landsat 9 Data
var dataSet = ee.ImageCollection("LANDSAT/LC09/C02/T1_L2")
.filterDate('2022-01-01', '2022-05-30')
.filterBounds(roi)
.filterMetadata('CLOUD_COVER', 'less_than', 10);
//Scaling Factors
function applyScaleFactors(image){
var opticalBands = image.select('SR_B.').multiply(0.0000275).add(-0.2);
var thermalBands = image.select('SR_B.').multiply(0.00341802).add(149.0);
return image.addBands(opticalBands, null, true).addBands(thermalBands, null, true);
}
var rescale = dataSet.map(applyScaleFactors);
var image = rescale.median();
var mapOptions = {
bands: ['SR_B4', 'SR_B3', 'SR_B2'],
min: 174.17200829,
max: 196.77195653,
};
//Create map layers
Map.addLayer(image, mapOptions, 'Landsat 9');
Map.centerObject(roi);
//Train
var training = barren.merge(forest).merge(water).merge(crop).merge(urban);
print(training);
Export.table.toAsset(training);
var label = 'Class';
var bands = ['SR_B1', 'SR_B2', 'SR_B3', 'SR_B4', 'SR_B5', 'SR_B6', 'SR_B7'];
var input = image.select(bands);
var trainImage = input.sampleRegions({
collection: training,
properties: [label],
scale: 20
});
var trainingData = trainImage.randomColumn();
var trainSet = trainingData.filter(ee.Filter.lessThan('random', 0.8));
var testSet = trainingData.filter(ee.Filter.greaterThan('random', 0.8));
//Classification Model
var classifier = ee.Classifier.smileRandomForest(10)
.train({
features:trainSet,
classProperty:label,
inputProperties:bands
});
var classify = input.classify(classifier);
//Classification Colors
var palette = [
'#0c2c84', //water
'#e31a1c', //urban
'#005a32', //forest
'FF8000', //crop
'969696' //barren
];
Map.addLayer(classify, {palette: palette, min:0, max:4}, 'classification');
//Assess Accuracy
var confusionMatrix = ee.ConfusionMatrix(testSet.classify(classifier)
.errorMatrix({
actual: 'Class',
predicted: 'classification'
}));
print ('Confusion Matrix: ', confusionMatrix);
print('Overall Accuracy: ', confusionMatrix.accuracy());
print('Producers Accuracy: ', confusionMatrix.producersAccuracy());
print('Consumers Accuracy: ', confusionMatrix.consumersAccuracy());