I used the linearFit() reducer to get trend analysis for NDVI (dependent variable), and time (t) is my one independent value.

What code can I use to calculate the residual sum of squares and standard error from this linearFit model in google earth engine?

  • in theory this should be possible with ee.Reducer.linearRegression but for me this solution always times out.
    – Joooeey
    Commented Apr 17, 2021 at 11:06

1 Answer 1


There are two options:

  1. Use ee.Reducer.linearRegression() instead of ee.linearFit(). Then you can take R2 from the band called 'residuals'.

  2. You go from the definition of r2 and code it yourself.

For my dataset, option 1 resulted in a timeout but you might get different mileage. Hence, I'll describe how to code r2 from it's definition. For instance over at Wikipedia the definition is given by:


For an explanation of the symbols, check out the Wikipedia page. In addition I used formula for the variance and n for the count of datapoints. I turned this formula into the following code and got decent performance.

var varcount_reducer = ee.Reducer.variance().combine(ee.Reducer.count(), '', true);
image_collection = image_collection.map(function (img) {
  return img.addBands(img.metadata('system:time_start'));
var trend_img = image_collection
  .select(['system:time_start', 'sigma0'])

// calculate R_squared, the coefficient of determination
// R_squared = 1 - SS_res / SS_tot
var offset = trend_img.select('offset');
var scale = trend_img.select('scale');
var SS_res = image_collection.map( function (img) {
  var fit = offset.add(img.select('system:time_start').multiply(scale)); // y_bar
  var error = img.select('sigma0').subtract(fit); // y_i - y_bar
  return error.multiply(error); // squared
var SS_tot = change_coll.reduce(varcount_reducer).expression(
var r2 = SS_res.divide(SS_tot).multiply(-1).add(1.0).rename('r2');

Not the answer you're looking for? Browse other questions tagged or ask your own question.