Multiple regression: Difference between revisions

From Rosetta Code
Content added Content deleted
(New page: Given a set of data vectors in the following format: <math>y = \{ y_1, y_2, ..., y_n \}</math> <math>x_i = \{ x_{i1}, x_{i2}, ..., x_{in} \}, i \in 1..k</math> Compute the vector <math>...)
 
No edit summary
Line 1: Line 1:
{{task}}
Given a set of data vectors in the following format:
Given a set of data vectors in the following format:


Line 10: Line 11:


You can assume <i>y</i> is given to you as an array, and <i>x</i> is given to you as a two-dimensional array.
You can assume <i>y</i> is given to you as an array, and <i>x</i> is given to you as a two-dimensional array.
=={{header|Ruby}}==

Using the standard library Matrix class:

<lang ruby>require 'matrix'

def regression_coefficients y, x
y = Matrix.column_vector y.map { |i| i.to_f }
x = Matrix.columns x.map { |xi| xi.map { |i| i.to_f }}

(x.t * x).inverse * x.t * y
end
</lang>

Testing:
<lang ruby>
regression_coefficients([1, 2, 3, 4, 5], [ [2, 1, 3, 4, 5] ]) # => Matrix[[0.981818181818182]]
</lang>

Revision as of 16:59, 29 June 2009

Task
Multiple regression
You are encouraged to solve this task according to the task description, using any language you may know.

Given a set of data vectors in the following format:

Compute the vector using ordinary least squares regression using the following equation:

You can assume y is given to you as an array, and x is given to you as a two-dimensional array.

Ruby

Using the standard library Matrix class:

<lang ruby>require 'matrix'

def regression_coefficients y, x

 y = Matrix.column_vector y.map { |i| i.to_f }
 x = Matrix.columns x.map { |xi| xi.map { |i| i.to_f }}
 (x.t * x).inverse * x.t * y

end </lang>

Testing: <lang ruby> regression_coefficients([1, 2, 3, 4, 5], [ [2, 1, 3, 4, 5] ]) # => Matrix0.981818181818182 </lang>