Multivariate cost function

Machine learning course from coursera

by de Montalembert Jonathan

JavaScript

// multivariate cost function
function cost(x, y, theta) {
  var m = x.length;
  var prediction = 0;
  x.forEach(function(xi, i) {
    var prediction_i = 0;
    xi.forEach(function(xij, j) {
      prediction_i += xij * theta[j][0];
    });
    prediction += Math.pow(prediction_i - y[i][0], 2)
  });
  return prediction / (2 * m)
}

var X_with_ones = [
  [1, 5, 3],
  [1, 14, 7]
];

var y = [
  [29],
  [72]
];

var theta_transposed = [
  [2],
  [3],
  [4]
]

console.log(cost(X_with_ones, y, theta_transposed)) // 0
  // Because (1*2 + 5*3 + 3*4 -29)^2 + (1*2 + 14*3 + 7*4 - 72)^2/2*3 = 0