Linear Regression

test_lin_reg(M, C):-
  lin_reg([1.5,3,4.25,6,8], [2.25,3,5.5,3.5,7], M, C).
  % M = 0.622577519379845, C = 1.41727228682171

/* lin_reg(Xs, Ys, M, C) is true if y = Mx + C is the best straight line   */
/*   fit for the given points (X, Y).                                      */
lin_reg(Xs, Ys, M, C):-
  sums(Xs, Ys, 0, N, 0, S_X, 0, S_Y, 0, S_XY, 0, S_XX),
  M is (S_X * S_Y / N - S_XY) / (S_X * S_X / N - S_XX),
  C is S_Y / N - M * S_X / N.

sums([], [], N, N, S_X, S_X, S_Y, S_Y, S_XY, S_XY, S_XX, S_XX).
sums([X|Xs], [Y|Ys], N0, N, S_X0, S_X, S_Y0, S_Y, S_XY0, S_XY, S_XX0, S_XX):-
  N1 is N0 + 1,
  S_X1 is S_X0 + X,
  S_Y1 is S_Y0 + Y,
  S_XY1 is S_XY0 + X * Y,
  S_XX1 is S_XX0 + X * X,
  sums(Xs, Ys, N1, N, S_X1, S_X, S_Y1, S_Y, S_XY1, S_XY, S_XX1, S_XX).

LPA Index     Home Page