Skip to content

Scripts

JuliePeeling edited this page Nov 29, 2021 · 8 revisions

01_search_and_display

/** START AND END DATES (SELECT TIME PERIODS THAT YOU WANT THE DATA FOR) **/
// Dates are specified in the format YYYY-MM-DD
var ST_DATE = '2017-12-01'; // Start date
var EN_DATE = '2018-03-01'; // End date

/** CREATE A GEOMETRIC REGION OF INTEREST WITH COORDINATES **/
//Comment this out for Exercise 1 and draw a polygon
//Format means [xmin, ymin, xmax, ymax]
//var geometry = ee.Geometry.Rectangle([-1.60, 10.30, -1.30, 10.60]); //rectangle in Northeastern Ghana

/** LANDSAT PRODUCTS **/
var IMG_L5 = 'LANDSAT/LT05/C01/T1_SR'; //use for years between 1984 and 2012
var IMG_L7 = 'LANDSAT/LE07/C01/T1_SR'; //use for years between 1999 and 2021
var IMG_L8 = 'LANDSAT/LC08/C01/T2_SR'; // use for years between 2014 and 2021

// Select image product, filter by region, filter by date, filter by cloud cover
var IMG_L5=ee.ImageCollection(IMG_L5)
  .filterBounds(geometry) //Filter image footprints to those that intersect rectangle
  .filterDate(ST_DATE, EN_DATE) // Filter images to dates we require
  .filterMetadata('CLOUD_COVER','less_than',70) // Filter images to ones with less than 70% cloud cover
  .map(function(image){return image.clip(geometry)}) // Clip images to rectangle
  .median() //Take the median image in the data collection
  ;
print(IMG_L5); // The print statement displays the content of the collection in the console, use this to inspect what is going on

var IMG_L7=ee.ImageCollection(IMG_L7)
  .filterBounds(geometry) //Filter image footprints to those that intersect rectangle
  .filterDate(ST_DATE, EN_DATE) // Filter images to dates we require
  .filterMetadata('CLOUD_COVER','less_than',70) // Filter images to ones with less than 20% cloud cover
  .map(function(image){return image.clip(geometry)}) // Clip images to rectangle
  .median() //Take the median of all pixel values in the image collection
  ;
print(IMG_L7);

var IMG_L8=ee.ImageCollection(IMG_L8)
  .filterBounds(geometry) //Filter image footprints to those that intersect rectangle
  .filterDate(ST_DATE, EN_DATE) // Filter images to dates we require
  .filterMetadata('CLOUD_COVER','less_than',70) // Filter images to ones with less than 20% cloud cover
  .map(function(image){return image.clip(geometry)}) // Clip images to rectangle
  .median() //Take the median of all pixel values in the image collection
  ;
print(IMG_L8);

// Set up visualization parameters for showing image in map below
//parameters for Landsat 5 and 7
var visParams57 = { 
  bands: ['B4', 'B3', 'B2'],
  min: 100, // Value in the satellite image to translate to darkest pixel in display (0)
  max: 3500, //Value in the satellite image to translate to brightest pixel in display (255)
  gamma: 1.5, //gamma correction factor controls the brightness
};

//parameters for Landsat 8
var visParams08 = { 
  bands: ['B5', 'B4', 'B3'],
  min: 0, //Value to map to 0
  max: 3000, //Value to map to 255
  gamma: 1.4, //gamma correction factor controls the brightness
};

Map.centerObject(geometry, 9); //Center the map at the region of interest
// Add image for each satellite to the map
Map.addLayer(IMG_L5,visParams57,'Landsat 5'); 
Map.addLayer(IMG_L7,visParams57,'Landsat 7');
Map.addLayer(IMG_L8,visParams08,'Landsat 8');

//Export the image to Google Drive by clicking 'Run' in task bar
Export.image.toDrive({ 
  image: IMG_L5,
  description: 'landsat5',
  scale: 30,
  region: geometry,
  maxPixels: 1000000000 //default value of maximum pixels
  //if image size is too large, maxPixels may need to be increased
});
Export.image.toDrive({ //This will expore the image to Google Drive once run in task bar
  image: IMG_L7,
  description: 'landsat7',
  scale: 30,
  region: geometry,
  maxPixels: 1000000000 //default value of maximum pixels
});
Export.image.toDrive({ 
  image: IMG_L8,
  description: 'landsat8',
  scale: 30,
  region: geometry,
  maxPixels: 1000000000 //1000000000 //default value of maximum pixels
});

02_image_indices_environmental_data

/** ############################### DEFAULTS  ############################### **/

// REGION OF INTEREST
var REG_GH = geometry;
// NOTE: we are overwriting the variable "geometry" imported above with this variable. 
//       ...doing this allows you to potentially use another geometry, say, built using coordinates like this:
/**
var xMin1 = -0.25;
var yMin1 = 7.45;
var xMax1 = -0.26;
var yMax1 = 7.46;
var REG_GH = ee.Geometry.Rectangle([xMin1, yMin1, xMax1, yMax1]);
**/


// SET IMAGE SOURCES
var IMG_L5 = 'LANDSAT/LT05/C01/T1_SR';  // FOR 2000 - 2012
var IMG_L7 = 'LANDSAT/LE07/C01/T1_SR';  // FOR 2000 - 2012
var IMG_L8 = 'LANDSAT/LC08/C01/T1_SR';  // FOR 2017 - Present
                                        // Remember, the bands of Landsat 5 and 7 are not the same as Lansat 8

// SET IMAGE ATTRIBUTES
// var MAXCLOUDTHRESH = 50;             // We won't be using this, we will develop a cloud mask instead
var YEAR1 = 2000;
var YEAR2 = 2010;

// SET DATES OF INTEREST
var ST_DATE = YEAR1+'-01-01';           // Note, the variable YEAR is defined above 
var EN_DATE = YEAR2+'-12-31';           // Note, the variable YEAR is defined above


/** ############################### DEFINE FUNCTIONS ############################### **/

// RENAMING BANDS [This is a 'helper function' that will allow us to work across all Landsat functions, see in-class discussion]
// This function gets us images for out start and end dates, clips them to the region, applies cloud masks, and renames bands.
// ...Notice that this is exactly the same as for exercise 1, just a few more lines to help regularize band names.
var getLSAT = function(imgColl,REG_GH,stDate,enDate) {
    var IMG_SR=ee.ImageCollection(imgColl)
    .filterDate(stDate, enDate)                                                   // Filter images to dates we require
    .filterBounds(REG_GH)                                                         // Filter image footprints by region
    .map(function(image){return image.clip(REG_GH)})                              // Clip images to region
    .map(cloudMask)                                                               // Mask clouds using the 'cloudMask' function
                                                                                  // NEW: Rename bands to harmonize across sensors
    .select(['B1','B2','B3','B4','B5','B6','B7','pixel_qa']);                     // Note: These are standard band names in all Landsat products
    var bNames = ['blu','grn','red','nir','sw1','t1','sw2','pixel_qa'];           // ... we create 'new' band names for Landsat 5 and 7
    if (imgColl == 'LANDSAT/LC08/C01/T1_SR')                                      // ... if we're looking at Landsat 8 though 
    {
      bNames = ['ubl','blu','grn','red','nir','sw1','sw2','pixel_qa'];            // ... we add in the corresponding new names (note ultra-blue, and changes in the thermal and swir2 bands)
    }
    var IMG_RN=IMG_SR.select(['B1','B2','B3','B4','B5','B6','B7','pixel_qa'],bNames); // ... we finally extract the only ones we want and rename them to the new names.
    return IMG_RN;                                                                // Return the image collection with the renamed bands
};

// MASKING CLOUDS
var cloudMask = function(image) {
  var qa = image.select('pixel_qa');
  var cloud = qa.bitwiseAnd(1 << 5)
                    .and(qa.bitwiseAnd(1 << 7))
                    .or(qa.bitwiseAnd(1 << 3));
  var mask2 = image.mask().reduce(ee.Reducer.min());
  return image.updateMask(cloud.not()).updateMask(mask2);
  };

// GETTING INDICES (see other indices at the end of the script)
var getNDVI = function(image) {
  var nir = image.select('nir');                                                  // Select the band called 'nir'
  var red = image.select('red');                                                  // Select the band called 'red'
  var ind = (nir.subtract(red)).divide(nir.add(red));                             // Divide the difference of the two with the sum of the two
  var ret = ind.copyProperties({source: image,properties: ['system:time_start']});// Copy over the timestamp of the image (for later use)
  return ret;                                                                     // Return the index
  };

// OTHER EQUIVALENT TECHNIQUES
/**
var getNDVI = function(image) {
  var ind = image.normalizedDifference(['nir', 'red']).rename('NDVI');
  var ret = ind.copyProperties({source: image,properties: ['system:time_start']});
  return ret;
  };

  // ...OR

var getNDVI = function(image){
  var ind = image.expression('(nir-red)/(nir+red)',{'nir':image.select('nir'),'red':image.select('red')}
  var ret = ind.copyProperties({source: image,properties: ['system:time_start']});
  return ret;
  };
**/

/** ############################### PROCESS ############################### **/

// Select image product, filter by region, filter by date, filter by cloud cover
/** 
// THIS IS HOW WE WERE DOING IT IN THE PAST...
var IMG_LT=ee.ImageCollection(IMG_L7)
  .filterBounds(REG_GH)                                           // Filter image footprints to those that intersect rectangle
  .filterDate(ST_DATE, EN_DATE)                                   // Filter images to dates we require
  //.filterMetadata('CLOUD_COVER','less_than',CLOUD_COVER)        // Filter images to ones with less than 70% cloud cover
  .map(function(image){return image.clip(geometry)})              // Clip images to rectangle
  .map(cloudMask)                                                 // Apply cloud mask function
  ;
print(IMG_LT);                                                    // Inquire the image collection
var MED_LT = IMG_LT.median();                                     // Get median of the image collection
print(MED_LT); // The print statement displays the content of the collection in the console, use this to inspect what is going on

// NOW, WE WILL SIMPLY CALL THE HELPER FUNCTION
**/

// var IMG_L5 = 'LANDSAT/LT05/C01/T1_SR';  // FOR 2000 - 2012     // For reference from above
// var IMG_L7 = 'LANDSAT/LE07/C01/T1_SR';  // FOR 2000 - 2012
// var IMG_L8 = 'LANDSAT/LC08/C01/T1_SR';  // FOR 2017 - Present

var IMG_LT = getLSAT(IMG_L5, REG_GH, ST_DATE, EN_DATE);           // Alternative formulation that renames bandnames
print(IMG_LT);                                                    // Inquire the image collection
var MED_LT = IMG_LT.median();                                     // Get median of the image collection
print(MED_LT); // The print statement displays the content of the collection in the console, use this to inspect what is going on

// GET NDVI
var IMG_IND=IMG_LT.map(getNDVI);                                        // Apply the image index function [CHANGE THIS TO GET ANOTHER INDEX]
print(IMG_IND);                                                   // Inquire the image collection
var MED_IND = IMG_IND.median();                                   // Get median of the image indices
print(MED_IND); // The print statement displays the content of the collection in the console, use this to inspect what is going on

/** ############################### VISUALIZE ############################### **/

// Visualization parameters are now common for Landsat 5, 7, and 8
var visParams = { 
  bands: ['nir', 'red', 'grn'],
  min: 0, //Value to map to 0
  max: 3000, //Value to map to 255
  gamma: 1.4, //gamma correction factor controls the brightness
};

var visNDVI = { 
  min: -0.4, //Value to map to 0
  max: 0.4, //Value to map to 255
  palette: ['blue', 'white', 'green'],
};


Map.centerObject(REG_GH, 9);                      //Center the map at the region of interest
Map.addLayer(MED_LT,visParams,'Landsat'); // Add image to the map
Map.addLayer(MED_IND,visNDVI,'NDVI'); // Add image to the map

/** ############################### PLOT TIME SERIES ############################### **/

var chart =
    ui.Chart.image                              // Initiate image                                 
        .series({                               // Start defining series to plot
          imageCollection: IMG_IND,             // Image collection to extract from
          region: REG_GH,                       // Region to average over
          reducer: ee.Reducer.mean(),           // Aggregating operation to use
          scale: 1000,                          // Aggregation scale
          //xProperty: 'system:time_start'
        })
        .setSeriesNames(['NDVI'])               // Plotting parameters
        .setOptions({
          title: 'Average Vegetation Index Value by Date',
          hAxis: {title: 'Date', titleTextStyle: {italic: false, bold: true}},
          vAxis: {
            title: 'Vegetation index',
            titleTextStyle: {italic: false, bold: true}
          },
          lineWidth: 4,
          maxPixels: 1e11,
          colors: ['e37d05', '1d6b99'],
          curveType: 'function'
          
        });
print(chart);

/** ############################### OTHER ENVIRONMENTAL DATA ############################### **/

// ######### LAND SURFACE ELEVATION
var SRTM=ee.Image("CGIAR/SRTM90_V4")
    .select('elevation')  
    .clip(geometry)
    ;

var visSRTM = { 
  min: 0,  //Value to map to 0
  max: 800, //Value to map to 255
  palette: ['blue', 'white', 'green'],
};
Map.addLayer(SRTM,visSRTM,'SRTM Elevation'); // Add image to the map

// ######### LAND SURFACE TEMPERATURE
var lsTemp=ee.ImageCollection("MODIS/006/MOD11A1")
    .filterDate(ST_DATE, EN_DATE)                                   // Filter images to dates we require
    .filterBounds(REG_GH)                                           // Filter image footprints to those that intersect rectangle
    .map(function(image){return image.clip(geometry)})              // Clip images to rectangle
    .select('LST_Day_1km')
  ;
var tempMean=lsTemp.mean();

var visTEMP = { 
  min: 15300,  //Value to map to 0
  max: 15400, //Value to map to 255
  //palette: ['blue', 'white', 'orange'],
};
Map.addLayer(tempMean,visTEMP,'LST'); // Add image to the map

var chart =
    ui.Chart.image
        .series({
          imageCollection: lsTemp,
          region: REG_GH,
          reducer: ee.Reducer.mean(),
          scale: 1000,
          //xProperty: 'system:time_start'
        })
        .setSeriesNames(['Land Surface Temperature'])
        .setOptions({
          title: 'Land Surface Temperature by Date',
          hAxis: {title: 'Date', titleTextStyle: {italic: false, bold: true}},
          vAxis: {
            title: 'LST',
            titleTextStyle: {italic: false, bold: true}
          },
          lineWidth: 1,
          maxPixels: 1e11,
          colors: ['e37d05', '1d6b99'],
          curveType: 'function'
          
        });
print(chart);


/** ############################### IMAGE INDEX FUNCTIONS ############################### **/

/** Other indices
  var evi = image.expression(
    '2.5 * ((NIR - Red) / (NIR + 6.0 * Red - 7.5 * Blue + 1))', {'NIR': image.select('nir'),'Red': image.select('red'),'Blue': image.select('blu')}
    );
  var ndvi = image.expression(
    '((NIR - Red) / (NIR + Red))', {'NIR': image.select('nir'),'Red': image.select('red')}
    );
  var msavi = image.expression(
  'MSAVI = (1/2)*(2*(NIR+1)-sqrt((2*NIR+1)**2-8*(NIR-Red)))',{'NIR': image.select('nir'),'Red': image.select('red')}
  );
  var savi = image.expression(
  'SAVI = ((NIR - Red) / (NIR + Red + 0.5)) * (1 + 0.5)',{'NIR': image.select('nir'),'Red': image.select('red')}
  );
  var vari = image.expression(
  'VARI = (Green - Red)/ (Green + Red - Blue)',{'Green': image.select('grn'),'Red': image.select('red'),'Blue': image.select('blu')  }
  );
  var ndsi = image.expression(
  'NDSI = (Green - SWIR) / (Green + SWIR)',{
      'Green': image.select('grn'),'SWIR': image.select('sw1')}
  );
  var mndwi = image.expression(
  'NDSI = (Green - SWIR) / (Green + SWIR)',{'Green': image.select('grn'),'SWIR': image.select('sw2')}
  );
  var ndmi = image.expression(
  'NDMI = (NIR - SWIR1)/(NIR + SWIR1)',{'NIR': image.select('nir'),'SWIR1': image.select('sw1')}
  );
  var msi = image.expression(
  'MSI = (NIR - SWIR) / (NIR+ SWIR)',{'NIR': image.select('nir'),'SWIR': image.select('sw1')}
  );
  var ndbi = image.expression(
  'NDBI = (SWIR - NIR) / (SWIR + NIR)',{'NIR': image.select('nir'),'SWIR': image.select('sw1')}
  );

**/

03_Landcover_Classification

// Note: table comes from the shapefile given to you from the UF team
// ... geometry is drawn by you. 
// Note: Make sure the geometry covers the points in the classification table

/** ############################### DEFAULTS  ############################### **/

// REGION OF INTEREST
var REG_GH = geometry;

// var label = 'LCODE';                    // This is the field containing the land cover class coded as a number.

// SET IMAGE SOURCES
var IMG_L5 = 'LANDSAT/LT05/C01/T1_SR';  // FOR 2000 - 2012
var IMG_L7 = 'LANDSAT/LE07/C01/T1_SR';  // FOR 2000 - 2012
var IMG_L8 = 'LANDSAT/LC08/C01/T1_SR';  // FOR 2017 - Present

// SET IMAGE ATTRIBUTES
var YEAR1 = 2019;                       // Note: we keep this the same as we have data from just one year.
var YEAR2 = 2019;

// SET DATES OF INTEREST
var ST_DATE = YEAR1+'-01-01';           // Note, the variable YEAR is defined above 
var EN_DATE = YEAR2+'-12-31';           // Note, the variable YEAR is defined above


/** ############################### DEFINE FUNCTIONS ############################### **/

// RENAMING BANDS [This is a 'helper function' that will allow us to work across all Landsat functions, see in-class discussion]
// This function gets us images for out start and end dates, clips them to the region, applies cloud masks, and renames bands.
// ...Notice that this is exactly the same as for exercise 1, just a few more lines to help regularize band names.

var getLSAT = function(imgColl,REG_GH,stDate,enDate) {
    var IMG_SR=ee.ImageCollection(imgColl)
    .filterDate(stDate, enDate)                                                   // Filter images to dates we require
    .filterBounds(REG_GH)                                                         // Filter image footprints by region
    .map(function(image){return image.clip(REG_GH)})                              // Clip images to region
    .map(cloudMask)                                                               // Mask clouds using the 'cloudMask' function
                                                                                  // NEW: Rename bands to harmonize across sensors
    .select(['B1','B2','B3','B4','B5','B6','B7','pixel_qa']);                     // Note: These are standard band names in all Landsat products
    var bNames = ['blu','grn','red','nir','sw1','t1','sw2','pixel_qa'];           // ... we create 'new' band names for Landsat 5 and 7
    if (imgColl == 'LANDSAT/LC08/C01/T1_SR')                                      // ... if we're looking at Landsat 8 though 
    {
      bNames = ['ubl','blu','grn','red','nir','sw1','sw2','pixel_qa'];            // ... we add in the corresponding new names (note ultra-blue, and changes in the thermal and swir2 bands)
    }
    var IMG_RN=IMG_SR.select(['B1','B2','B3','B4','B5','B6','B7','pixel_qa'],bNames); // ... we finally extract the only ones we want and rename them to the new names.
    return IMG_RN.select(['blu','grn','red','nir','sw1','sw2','pixel_qa']);       // Return the image collection with the renamed bands
};

// MASKING CLOUDS
var cloudMask = function(image) {
  var qa = image.select('pixel_qa');
  var cloud = qa.bitwiseAnd(1 << 5)
                    .and(qa.bitwiseAnd(1 << 7))
                    .or(qa.bitwiseAnd(1 << 3));
  var mask2 = image.mask().reduce(ee.Reducer.min());
  return image.updateMask(cloud.not()).updateMask(mask2);
  };

// GET INDICES (see other indices at the end of the script)
var getNDVI = function(image){
  var ind = image.expression('(nir-red)/(nir+red)',{'nir':image.select('nir'),'red':image.select('red')});
  return ind.copyProperties({source: image,properties: ['system:time_start']});
  };

var getEVI = function(image){
  var ind = image.expression('2.5 * ((NIR - Red) / (NIR + 6.0 * Red - 7.5 * Blue + 1))', {'NIR': image.select('nir'),'Red': image.select('red'),'Blue': image.select('blu')});
  return ind.copyProperties({source: image,properties: ['system:time_start']});
  };
  
var getMSAVI = function(image){
  var ind = image.expression('MSAVI = (1/2)*(2*(NIR+1)-sqrt((2*NIR+1)**2-8*(NIR-Red)))',{'NIR': image.select('nir'),'Red': image.select('red')});
  return ind.copyProperties({source: image,properties: ['system:time_start']});
  };

var getSAVI = function(image){
  var ind = image.expression('SAVI = ((NIR - Red) / (NIR + Red + 0.5)) * (1 + 0.5)',{'NIR': image.select('nir'),'Red': image.select('red')});
  return ind.copyProperties({source: image,properties: ['system:time_start']});
  };
  
var getVARI = function(image){
  var ind = image.expression('VARI = (Green - Red)/ (Green + Red - Blue)',{'Green': image.select('grn'),'Red': image.select('red'),'Blue': image.select('blu')  });
  return ind.copyProperties({source: image,properties: ['system:time_start']});
  };
  
var getNDSI = function(image){
  var ind = image.expression('NDSI = (Green - SWIR) / (Green + SWIR)',{'Green': image.select('grn'),'SWIR': image.select('sw1')});
  return ind.copyProperties({source: image,properties: ['system:time_start']});
  };
  
var getMSI = function(image){
  var ind = image.expression('MSI = (NIR - SWIR) / (NIR+ SWIR)',{'NIR': image.select('nir'),'SWIR': image.select('sw1')});
  return ind.copyProperties({source: image,properties: ['system:time_start']});
  };

/** ############################### PROCESS ############################### **/

// LET US GET ALL SATELLITE DATA THAT IS AVAILABLE

// var IMG_L5 = 'LANDSAT/LT05/C01/T1_SR';  // FOR 2000 - 2012     // For reference from above
// var IMG_L7 = 'LANDSAT/LE07/C01/T1_SR';  // FOR 2000 - 2012
// var IMG_L8 = 'LANDSAT/LC08/C01/T1_SR';  // FOR 2017 - Present

var IMG_LT5 = getLSAT(IMG_L5, REG_GH, ST_DATE, EN_DATE);          // Landsat 5 (See details in last exercise)
var IMG_LT7 = getLSAT(IMG_L7, REG_GH, ST_DATE, EN_DATE);          // Landsat 7 (See details in last exercise)
var IMG_LT8 = getLSAT(IMG_L8, REG_GH, ST_DATE, EN_DATE);          // Landsat 8 (See details in last exercise)

// COMBINE ALL IMAGES INTO ONE STACK

var IMG_LTX = IMG_LT5.merge(IMG_LT7);                             // First, merge L5 and L7 into one...
var IMG_LTX = IMG_LTX.merge(IMG_LT8);                             // Then, merge L8 into this one
var IMG_LTX = IMG_LTX.sort('system:time_start');
print('Landsat collection for this model');                       // Check total number of images available
print(IMG_LTX);
var LTX_MED = IMG_LTX.median().select(['blu','grn','red','nir','sw1','sw2']);// Get median of all bands

// GENERATE INDEX STACKS
var IMG_IND = IMG_LTX.map(getNDVI).median();                      // Generate stack of NDVIs, take median
var IMG_IND = IMG_IND.addBands(IMG_LTX.map(getEVI).median());     // Generate stack of EVIs, take median, add to median NDVI as band
var IMG_IND = IMG_IND.addBands(IMG_LTX.map(getMSI).median());     // ...so on and so forth,
var IMG_IND = IMG_IND.addBands(IMG_LTX.map(getSAVI).median());
var IMG_IND = IMG_IND.addBands(IMG_LTX.map(getMSAVI).median());
var IMG_IND = IMG_IND.addBands(IMG_LTX.map(getVARI).median());

/** ############################### CLASSIFY ############################### **/
var table = table2;
var label='LCODE2';

// add a random column (by default named 'random'), will contain random numbers between 0-1
table = table.randomColumn();
// split in a training (80%) and validation (20%)
var train_samp = table.filter(ee.Filter.gt('random',0.2));  // 80% training
var test_samp = table.filter(ee.Filter.lte('random',0.2));  // 20% testing

// Select the image you want to classify with
//var IMG_CLS = IMG_IND;
var IMG_CLS = LTX_MED;

// SAMPLE FROM GROUND-TRUTH LOCATIONS
var training = IMG_CLS.sampleRegions({
  collection: train_samp,
  properties: [label],
  scale: 30
});

print('Training dataset');
print(training);

var testing = IMG_CLS.sampleRegions({
  collection: test_samp,
  properties: [label],
  scale: 30
});
print('Testing dataset');
print(testing);

// BUILD CLASSIFIER (see Classifier in the Docs pane on the left)
//var classifier = ee.Classifier.minimumDistance().train(training,label);
//var classifier = ee.Classifier.libsvm().train(training,label);
//var classifier = ee.Classifier.smileCart().train(training,label);
var classifier = ee.Classifier.smileRandomForest(10).train(training,label);

// Get a confusion matrix representing resubstitution accuracy.
var trainAccuracy = classifier.confusionMatrix();
print('Resubstitution error matrix: ', trainAccuracy);              // Training accuracy matrix
print('Training overall accuracy: ', trainAccuracy.accuracy());     // Training accuracy

// Overlay the points on the imagery to get training.
var classified = IMG_CLS.classify(classifier,'Classified');         // Classify the input imagery.

// VALIDATE
var testclass = testing.classify(classifier,'Classified');          // Apply the classifier on the testing data.
print(testclass);
var testAccuracy = testclass.errorMatrix(label, 'Classified');    // Compute confusion matrix
print('Validation error matrix: ', testAccuracy);                   // Testing confusion matrix
print('Validation overall accuracy: ', testAccuracy.accuracy());    // Validation accuracy

/** ############################### VISUALIZE ############################### **/

// Visualization parameters are now common for Landsat 5, 7, and 8
var visParams = { 
  bands: ['nir', 'red', 'grn'],
  min: 0, //Value to map to 0
  max: 3000, //Value to map to 255
  gamma: 1.4, //gamma correction factor controls the brightness
};

var visNDVI = { 
  min: -0.2, //Value to map to 0
  max: 1.0, //Value to map to 255
  palette: ['blue', 'white', 'green'],
};

/**
var palette = [
  'FFFFFF', //0 Nodata?
  'FFFF33', //1 Agriculture
  'CCCCCC', //2 Barren
  '006633', //3 Forest
  'CC0000', //4 Urban
  '0000CC', //5 Water
  ];
**/

var palette1 = [
  'FFFFFF', // 0 Nodata?
  '9aa4a6', // 1 Bare
  'fbe839', // 2 Cropland
  'e5071d', // 3 Built up
  '0c8000', // 4 Forest
  'a3d06c', // 5 Herbaceous
  'b6ab08', // 6 Shrub
  '030edb', // 7 Water
  ];

var palette2 = [
  'FFFFFF', // 0 Nodata?
  'BEC5C6',//Bare_Bare soil
  '9AA4A6',//Bare_Rocky land
  'C5C4B3',//Bare_Sandy area
  'FBE839',//Cropland_Agriculture
  'E5D005',//Cropland_Agriculture in shallows and recession
  'C4B204',//Cropland_Cropland and fallow with oil palm
  'C7A309',//Cropland_Irrigated agriculture
  'AB0515',//Developed_Open mine
  'E5071D',//Developed_Settlements
  '546113',//Forest_Degraded forest
  '0C8000',//Forest_Forest
  '1E625C',//Forest_Gallery and riparian forest
  '2B8D84',//Forest_Mangrove
  '10AC00',//Forest_Plantation
  '18FE00',//Forest_Swamp forest
  'CAE4AA',//Herbaceous_Bowe
  'A3D06C',//Herbaceous_Herbaceous savanna
  '7DB43A',//Herbaceous_Steppe
  'FCF7B2',//Shrub_Sahelian shortgrass savana
  'F6D238',//Shrub_Savanna
  'EFF509',//Shrub_Shrubland
  'CDD208',//Shrub_Thicket
  'A19607',//Shrub_Woodland
  '030EDB',//Water bodies_Water bodies
  '0199DD',//Water bodies_Wetland floodplain
  ];

Map.centerObject(REG_GH, 9);                              //Center the map at the region of interest
Map.addLayer(table,{},'Sampling ponits');                 // Add sampling shapefile to the map
Map.addLayer(IMG_LTX.median(),visParams,'Landsat');       // Add image to the map
//Map.addLayer(classified,{min: 0, max: 7,  palette: palette1},'Land cover 1');
Map.addLayer(classified,{min: 0, max: 25, palette: palette2},'Land cover 2');