Multiple regression: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(18 intermediate revisions by 10 users not shown)
Line 20:
 
matrices.ads:
<langsyntaxhighlight Adalang="ada">generic
type Element_Type is private;
Zero : Element_Type;
Line 57:
Not_Square_Matrix : exception;
Not_Invertible : exception;
end Matrices;</langsyntaxhighlight>
 
matrices.adb:
<langsyntaxhighlight Adalang="ada">package body Matrices is
function "*" (Left, Right : Matrix) return Matrix is
Result : Matrix (Left'Range (1), Right'Range (2)) :=
Line 248:
return Result;
end Transpose;
end Matrices;</langsyntaxhighlight>
 
Example multiple_regression.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Matrices;
procedure Multiple_Regression is
Line 318:
Output_Matrix (Float_Matrices.To_Matrix (Coefficients));
end;
end Multiple_Regression;</langsyntaxhighlight>
 
{{out}}
Line 358:
-1.51161E+02
6.43514E+01</pre>
 
=={{header|ALGOL 68}}==
{{Trans|Visual Basic .NET}}...but using the "to reduced echelon form" routine from [[Reduced row echelon form#ALGOL_68]].
Algol 68 doesn't have classes, though it does have structures.
<br>Other than that, the main differences between this and the VB.NET sample are that Algol 68 has array slicing built in and generally uses a lower bound of 1 rather than 0 for arrays.
<br>Also, although <code>( ( 1, 2, 3 ), ( 6, 5, 4 ) )</code> is a 2x3 array, <code>( ( 1, 2, 3 ) )</code> is a 3x1 array (because <code>( x )</code> is not an array, so the outer brackets are superfluous, leaving <code>( 1, 2, 3 )</code> - i.e. a 1-dimensoional array - as the context requires a two-dimensional array, each value is coerced to an array resulting in a 3x1 two-dimensional array).
<syntaxhighlight lang="algol68">
BEGIN # Multiple Regression - trnslation of the VB.NET sample but using the #
# "to reduced row echelon form" routine from the Reduced row echelon Task #
 
PROC require = ( BOOL condition, STRING message )VOID:
IF NOT condition THEN
print( ( message, newline ) );
stop
FI # requiree # ;
 
MODE MATRIX = STRUCT( REF[,]REAL data
, INT row count
, INT col count
);
 
PRIO NEWMATRIX = 1;
OP NEWMATRIX = ( INT rows, INT cols )MATRIX:
BEGIN
MATRIX result;
require( rows > 0, "Need at least one row" );
row count OF result := rows;
require( cols > 0, "Need at least one column" );
col count OF result := cols;
data OF result := HEAP[ 1 : rows, 1 : cols ]REAL;
FOR r TO rows DO FOR c TO cols DO ( data OF result )[ r, c ] := 0 OD OD;
result
END # NEWMATRIX # ;
 
OP NEWMATRIX = ( [,]REAL source )MATRIX:
BEGIN
MATRIX result;
INT rows = 1 + ( 1 UPB source - 1 LWB source );
require( rows > 0, "Need at least one row" );
row count OF result := rows;
INT cols = 1 + ( 2 UPB source - 2 LWB source );
require( cols > 0, "Need at least one column" );
col count OF result := cols;
data OF result := HEAP[ 1 : rows, 1 : cols ]REAL := source[ AT 1, AT 1 ];
result
END # NEWMATRIX # ;
 
OP NEWMATRIX = ( []REAL source )MATRIX: # New Matrix(ConvertArray(source)) #
BEGIN
INT len = 1 + ( UPB source - LWB source );
[ 1 : 1, 1 : len ]REAL dest;
dest[ 1, : ] := source;
NEWMATRIX dest
END # NEWMATRIX # ;
 
OP * = ( MATRIX m1, m2 )MATRIX:
BEGIN
INT rc1 = row count OF m1;
INT cc1 = col count OF m1;
INT rc2 = row count OF m2;
INT cc2 = col count OF m2;
require( cc1 = rc2, "Cannot multiply if the first columns does not equal the second rows" );
MATRIX result := rc1 NEWMATRIX cc2;
FOR i TO rc1 DO
FOR j TO cc2 DO
FOR k TO rc2 DO
( data OF result ) [ i, j ] +:= ( data OF m1 )[ i, k ]
* ( data OF m2 )[ k, j ]
OD
OD
OD;
result
END # * # ;
 
PROC transpose = ( MATRIX m )MATRIX:
BEGIN
INT rc = row count OF m;
INT cc = col count OF m;
MATRIX trans := cc NEWMATRIX rc;
FOR i TO cc DO
FOR j TO rc DO
( data OF trans )[ i, j ] := ( data OF m )[ j, i ]
OD
OD;
trans
END # transpose # ;
 
# BEGIN code from the Reduced row echelon form task #
MODE FIELD = REAL; # FIELD can be REAL, LONG REAL etc, or COMPL, FRAC etc #
MODE VEC = [0]FIELD;
MODE MAT = [0,0]FIELD;
PROC to reduced row echelon form = (REF MAT m)VOID: (
INT lead col := 2 LWB m;
 
FOR this row FROM LWB m TO UPB m DO
IF lead col > 2 UPB m THEN return FI;
INT other row := this row;
WHILE m[other row,lead col] = 0 DO
other row +:= 1;
IF other row > UPB m THEN
other row := this row;
lead col +:= 1;
IF lead col > 2 UPB m THEN return FI
FI
OD;
IF this row /= other row THEN
VEC swap = m[this row,lead col:];
m[this row,lead col:] := m[other row,lead col:];
m[other row,lead col:] := swap
FI;
FIELD scale = 1/m[this row,lead col];
IF scale /= 1 THEN
m[this row,lead col] := 1;
FOR col FROM lead col+1 TO 2 UPB m DO m[this row,col] *:= scale OD
FI;
FOR other row FROM LWB m TO UPB m DO
IF this row /= other row THEN
REAL scale = m[other row,lead col];
m[other row,lead col]:=0;
FOR col FROM lead col+1 TO 2 UPB m DO m[other row,col] -:= scale*m[this row,col] OD
FI
OD;
lead col +:= 1
OD;
return: EMPTY
);
# END code from the Reduced row echelon form task #
PROC inverse = ( MATRIX m )MATRIX:
BEGIN
require( row count OF m = col count OF m, "Not a square matrix" );
INT len = row count OF m;
MATRIX aug := len NEWMATRIX ( 2 * len );
FOR i TO len DO
FOR j TO len DO
( data OF aug )[ i, j ] := ( data OF m )[ i, j ];
( data OF aug )[ i, j + len ] := 0
OD;
# augment identity matrix to right #
( data OF aug )[ i, i + len ] := 1.0
OD;
to reduced row echelon form( data OF aug );
MATRIX inv := len NEWMATRIX len;
FOR i TO len DO
FOR j FROM len + 1 TO 2 * len DO
( data OF inv)[ i, j - len ] := ( data OF aug )[ i, j ]
OD
OD;
inv
END # inverse # ;
 
PROC multiple regression = ( []REAL y, MATRIX x )[]REAL:
BEGIN
MATRIX tm := NEWMATRIX y;
MATRIX cy := NEWMATRIX data OF transpose( tm );
MATRIX cx := NEWMATRIX data OF transpose( x );
( data OF transpose( inverse( x * cx ) * x * cy ) )[ 1, : ]
END # multiple regression # ;
 
OP PRINTARRAY = ( []REAL list )VOID:
BEGIN
print( ( "[" ) );
FOR i FROM LWB list TO UPB list DO
# convert list[ i ] to a string, remove trailing 0s and leading spaces #
STRING v := fixed( list[ i ], -20, 15 )[ AT 1 ];
WHILE v[ UPB v ] = "0" DO v := v[ : UPB v - 1 ] OD;
IF v[ UPB v ] = "." THEN v := v[ : UPB v - 1 ] FI;
WHILE v[ 1 ] = " " DO v := v[ 2 : ] OD;
print( ( IF i > LWB list THEN ", " ELSE "" FI, v ) )
OD;
print( ( "]" ) )
END # PRINTARRAY # ;
 
BEGIN
[]REAL y = ( 1.0, 2.0, 3.0, 4.0, 5.0 );
MATRIX x := NEWMATRIX []REAL( 2.0, 1.0, 3.0, 4.0, 5.0 );
[]REAL v = multiple regression( y, x );
PRINTARRAY v;
print( ( newline ) )
END;
BEGIN
[]REAL y = ( 3.0, 4.0, 5.0 );
MATRIX x := NEWMATRIX [,]REAL( ( 1.0, 2.0, 1.0 )
, ( 1.0, 1.0, 2.0 )
);
[]REAL v = multiple regression( y, x );
PRINTARRAY v;
print( ( newline ) )
END;
BEGIN
[]REAL y = ( 52.21, 53.12, 54.48, 55.84, 57.2, 58.57, 59.93
, 61.29, 63.11, 64.47, 66.28, 68.1, 69.92, 72.19, 74.46
);
[]REAL a = ( 1.47, 1.5, 1.52, 1.55, 1.57, 1.6, 1.63, 1.65
, 1.68, 1.7, 1.73, 1.75, 1.78, 1.8, 1.83
);
[ 1 : 3, 1 : 1 + ( UPB a - LWB a ) ]REAL xs;
FOR i FROM LWB a TO UPB a DO
xs[ 1, i ] := 1.0;
xs[ 2, i ] := a[ i ];
xs[ 3, i ] := a[ i ] * a[ i ]
OD;
MATRIX x := NEWMATRIX xs;
[]REAL v = multiple regression( y, x );
PRINTARRAY v;
print( ( newline ) )
END
 
END
</syntaxhighlight>
{{out}}
<pre>
[0.981818181818182]
[1, 2]
[128.812803581374, -143.162022866676, 61.9603254433538]
</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> *FLOAT 64
INSTALL @lib$+"ARRAYLIB"
Line 389 ⟶ 605:
t() = t().m()
c() = y().t()
ENDPROC</langsyntaxhighlight>
{{out}}
<pre>
Line 396 ⟶ 612:
 
=={{header|C}}==
Using GNU gsl and c99, with the WP data<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_math.h>
Line 439 ⟶ 655:
gsl_multifit_linear_free(wspc);
 
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{trans|Java}}
<langsyntaxhighlight lang="cpp">#include <array>
#include <iostream>
 
Line 669 ⟶ 885:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>[0.981818]
Line 677 ⟶ 893:
=={{header|C sharp|C#}}==
{{libheader|Math.Net}}
<langsyntaxhighlight lang="csharp">using System;
using MathNet.Numerics.LinearRegression;
using MathNet.Numerics.LinearAlgebra;
Line 694 ⟶ 910:
Console.WriteLine(β);
}
}</langsyntaxhighlight>
 
{{out}}
Line 706 ⟶ 922:
Uses the routine (chol A) from [[Cholesky decomposition]], (mmul A B) from [[Matrix multiplication]], (mtp A) from [[Matrix transposition]].
 
<langsyntaxhighlight lang="lisp">
;; Solve a linear system AX=B where A is symmetric and positive definite, so it can be Cholesky decomposed.
(defun linsys (A B)
Line 740 ⟶ 956:
(linsys (mmul (mtp A) A)
(mmul (mtp A) b)))
</syntaxhighlight>
</lang>
 
To show an example of multiple regression, (polyfit x y n) from [[Polynomial regression]], which itself uses (linsys A B) and (lsqr A b), will be used to fit a second degree order polynomial to data.
 
<langsyntaxhighlight lang="lisp">(let ((x (make-array '(1 11) :initial-contents '((0 1 2 3 4 5 6 7 8 9 10))))
(y (make-array '(1 11) :initial-contents '((1 6 17 34 57 86 121 162 209 262 321)))))
(polyfit x y 2))
#2A((0.9999999999999759d0) (2.000000000000005d0) (3.0d0))</langsyntaxhighlight>
 
=={{header|D}}==
{{trans|Java}}
<langsyntaxhighlight lang="d">import std.algorithm;
import std.array;
import std.exception;
Line 975 ⟶ 1,191:
v = multipleRegression(y, x);
v.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[0.981818]
Line 983 ⟶ 1,199:
=={{header|Emacs Lisp}}==
 
{{libheader|calc}}
Multiple regression analysis by Emacs Lisp and built-in Emacs Calc.
 
<syntaxhighlight lang="lisp">(let ((x1 '(0 1 2 3 4 5 6 7 8 9 10))
<lang emacs-lisp>
(setq X1 (x2 '[(0 1 21 3 43 57 6 7 83 9 10]8))
(setq X2 '[0 1 1 3 3(y 7'(1 6 717 34 57 86 121 162 3209 9262 8]321)))
(apply #'calc-eval "fit(a*X1+b*X2+c,[X1,X2],[a,b,c],[$1 $2 $3])" nil
(setq Y '[1 6 17 34 57 86 121 162 209 262 321])
(mapcar (lambda (items) (cons 'vec items)) (list x1 x2 y))))</syntaxhighlight>
(calc-eval
(format "fit(a*X1+b*X2+c,[X1,X2],[a,b,c],[%s %s %s])" X1 X2 Y))
</lang>
 
{{out}}
 
<pre>
"35.2014388489 *X1 - 3.95683453237 *X2 - 42.7410071942"
</pre>
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM MULTIPLE_REGRESSION
 
!$DOUBLE
Line 1,080 ⟶ 1,293:
END FOR
 
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>LINEAR SYSTEM COEFFICENTS
Line 1,100 ⟶ 1,313:
{{libheader|SLATEC}} [http://netlib.org/slatec/ Available at the Netlib]
 
<langsyntaxhighlight Fortranlang="fortran">*-----------------------------------------------------------------------
* MR - multiple regression using the SLATEC library routine DHFTI
*
Line 1,185 ⟶ 1,398:
STOP 'program complete'
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,191 ⟶ 1,404:
STOP program complete
</pre>
 
=={{header|FreeBASIC}}==
{{trans|ERRE}}
<syntaxhighlight lang="vb">Const N = 14, M = 2, Q = 3 ' number of points and M.R. polynom degree
 
Dim As Double X(0 to N) = {1.47,1.50,1.52,1.55,1.57, _
1.60,1.63,1.65,1.68,1.70,1.73,1.75,1.78,1.80,1.83} ' data points
Dim As Double Y(0 to N) = {52.21,53.12,54.48,55.84,57.20, _
58.57,59.93,61.29,63.11,64.47,66.28,68.10,69.92,72.19,74.46} ' data points
Dim As Double S(N), T(N) ' linear system coefficient
Dim As Double A(M, Q) ' sistem to be solved
Dim As Integer i, k, j, fila, columna
Dim as Double z
 
For k = 0 To 2*M
S(k) = 0 : T(k) = 0
For i = 0 To N
S(k) += X(i) ^ k
If k <= M Then T(k) += Y(i) * X(i) ^ k
Next i
Next k
 
' build linear system
For fila = 0 To M
For columna = 0 To M
A(fila, columna) = S(fila+columna)
Next columna
A(fila, columna) = T(fila)
Next fila
 
Print "Linear system coefficents:"
For i = 0 To M
For j = 0 To M+1
Print Using "######.#"; A(i,j);
Next j
Print
Next i
 
For j = 0 To M
For i = j To M
If A(i,j) <> 0 Then Exit For
Next i
If i = M+1 Then
Print !"\nSINGULAR MATRIX '"
Sleep: End
End If
For k = 0 To M+1
Swap A(j,k), A(i,k)
Next k
z = 1 / A(j,j)
For k = 0 To M+1
A(j,k) = z * A(j,k)
Next k
For i = 0 To M
If i <> j Then
z = -A(i,j)
For k = 0 To M+1
A(i,k) += z * A(j,k)
Next k
End If
Next i
Next j
 
Print !"\nSolutions:"
For i = 0 To M
Print Using " #####.#######"; A(i,M+1);
Next i
 
Sleep</syntaxhighlight>
{{out}}
<pre>Linear system coefficents:
15.0 24.8 41.1 931.2
24.8 41.1 68.4 1548.2
41.1 68.4 114.3 2585.5
 
Solutions:
128.8128036 -143.1620229 61.9603254</pre>
 
=={{header|Go}}==
The [http://en.wikipedia.org/wiki/Ordinary_least_squares#Example_with_real_data example] on WP happens to be a polynomial regression example, and so code from the [[Polynomial regression]] task can be reused here. The only difference here is that givens x and y are computed in a separate function as a task prerequisite.
===Library gonum/matrix===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,227 ⟶ 1,517:
x, y := givens()
fmt.Printf("%.4f\n", mat64.Formatted(mat64.QR(x).Solve(y)))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,235 ⟶ 1,525:
</pre>
===Library go.matrix===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,280 ⟶ 1,570:
}
fmt.Println(c)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,288 ⟶ 1,578:
=={{header|Haskell}}==
Using package [http://hackage.haskell.org/package/hmatrix hmatrix] from HackageDB
<langsyntaxhighlight lang="haskell">import Numeric.LinearAlgebra
import Numeric.LinearAlgebra.LAPACK
 
Line 1,299 ⟶ 1,589:
v :: Matrix Double
v = (3><1)
[1.745005,-4.448092,-4.160842]</langsyntaxhighlight>
Using lapack::dgels
<langsyntaxhighlight lang="haskell">*Main> linearSolveLSR m v
(3><1)
[ 0.9335611922087276
, 1.101323491272865
, 1.6117769115824 ]</langsyntaxhighlight>
Or
<langsyntaxhighlight lang="haskell">*Main> inv m `multiply` v
(3><1)
[ 0.9335611922087278
, 1.101323491272865
, 1.6117769115824006 ]</langsyntaxhighlight>
 
=={{header|Hy}}==
<langsyntaxhighlight lang="lisp">(import
[numpy [ones column-stack]]
[numpy.random [randn]]
Line 1,326 ⟶ 1,616:
(print (first (lstsq
(column-stack (, (ones n) x1 x2 (* x1 x2)))
y)))</langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight lang="j"> NB. Wikipedia data
x=: 1.47 1.50 1.52 1.55 1.57 1.60 1.63 1.65 1.68 1.70 1.73 1.75 1.78 1.80 1.83
y=: 52.21 53.12 54.48 55.84 57.20 58.57 59.93 61.29 63.11 64.47 66.28 68.10 69.92 72.19 74.46
 
y %. x ^/ i.3 NB. calculate coefficients b1, b2 and b3 for 2nd degree polynomial
128.813 _143.162 61.9603</langsyntaxhighlight>
 
Breaking it down:
<langsyntaxhighlight lang="j"> X=: x ^/ i.3 NB. form Design matrix
X=: (x^0) ,. (x^1) ,. (x^2) NB. equivalent of previous line
4{.X NB. show first 4 rows of X
Line 1,349 ⟶ 1,639:
NB. y %. X does matrix division and gives the regression coefficients
y %. X
128.813 _143.162 61.9603</langsyntaxhighlight>
In other words <tt> beta=: y %. X </tt> is the equivalent of:<br>
<math> \hat\beta = (X'X)^{-1}X'y</math><br>
 
To confirm:
<langsyntaxhighlight lang="j"> mp=: +/ .* NB. matrix product
NB. %.X is matrix inverse of X
NB. |:X is transpose of X
Line 1,363 ⟶ 1,653:
X (%.@:xpy@[ mp xpy) y
128.814 _143.163 61.9606
</syntaxhighlight>
</lang>
 
LAPACK routines are also available via the Addon <tt>math/lapack</tt>.
<langsyntaxhighlight lang="j"> load 'math/lapack'
load 'math/lapack/gels'
gels_jlapack_ X;y
128.813 _143.162 61.9603</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="java">import java.util.Arrays;
import java.util.Objects;
 
Line 1,581 ⟶ 1,871:
printVector(v);
}
}</langsyntaxhighlight>
{{out}}
<pre>[0.9818181818181818]
Line 1,596 ⟶ 1,886:
Extends the Matrix class from [[Matrix Transpose#JavaScript]], [[Matrix multiplication#JavaScript]], [[Reduced row echelon form#JavaScript]].
Uses the IdentityMatrix from [[Matrix exponentiation operator#JavaScript]]
<langsyntaxhighlight lang="javascript">// modifies the matrix "in place"
Matrix.prototype.inverse = function() {
if (this.height != this.width) {
Line 1,642 ⟶ 1,932:
)
);
print(y.regression_coefficients(x));</langsyntaxhighlight>
{{out}}
<pre>0.9818181818181818
Line 1,649 ⟶ 1,939:
-143.1620228653037
61.960325442985436</pre>
 
=={{header|jq}}==
{{trans|Wren}}
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
See e.g. https://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion#jq
for a suitable definition of `inverse` as used here.
 
'''Preliminaries'''
<syntaxhighlight lang="jq">def dot_product(a; b):
reduce range(0;a|length) as $i (0; . + (a[$i] * b[$i]) );
 
# A and B should both be numeric matrices, A being m by n, and B being n by p.
def multiply(A; B):
(B[0]|length) as $p
| (B|transpose) as $BT
| reduce range(0; A|length) as $i
([];
reduce range(0; $p) as $j
(.;
.[$i][$j] = dot_product( A[$i]; $BT[$j] ) ));</syntaxhighlight>
 
'''Multiple Regression'''
<syntaxhighlight lang="jq">def multipleRegression(y; x):
(y|transpose) as $cy
| (x|transpose) as $cx
| multiply( multiply( multiply(x;$cx)|inverse; x); $cy)
| transpose[0];
def ys: [
[ [1, 2, 3, 4, 5] ],
[ [3, 4, 5] ],
[ [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29,
63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46] ]
];
def a:
[1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83];
 
def xs:[
[ [2, 1, 3, 4, 5] ],
[ [1, 2, 1], [1, 1, 2] ],
[ [range(0;a|length) | 1], a, (a|map(.*.))]
];
 
range(0; ys|length) as $i
| multipleRegression(ys[$i]; xs[$i])</syntaxhighlight>
{{out}}
<pre>
[0.9818181818181818]
[0.9999999999999996,2.000000000000001]
[128.8128035798277,-143.1620228653037,61.960325442985436]
</pre>
 
 
=={{header|Julia}}==
Line 1,655 ⟶ 2,000:
As in Matlab, the backslash or slash operator (depending on the matrix ordering) can be used for solving this problem, for example:
 
<langsyntaxhighlight lang="julia">x = [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83]
y = [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46]
X = [x.^0 x.^1 x.^2];
b = X \ y</langsyntaxhighlight>
{{out}}
<pre>
Line 1,669 ⟶ 2,014:
=={{header|Kotlin}}==
As neither the JDK nor the Kotlin Standard Library has matrix operations built-in, we re-use functions written for various other tasks.
<langsyntaxhighlight lang="scala">// Version 1.2.31
 
typealias Vector = DoubleArray
Line 1,789 ⟶ 2,134:
v = multipleRegression(y, x)
printVector(v)
}</langsyntaxhighlight>
 
{{out}}
Line 1,804 ⟶ 2,149:
First build a random dataset.
 
<langsyntaxhighlight lang="maple">n:=200:
X:=<ArrayTools[RandomArray](n,4,distribution=normal)|Vector(n,1,datatype=float[8])>:
Y:=X.<4.2,-2.8,-1.4,3.1,1.75>+convert(ArrayTools[RandomArray](n,1,distribution=normal),Vector):</langsyntaxhighlight>
 
Now the linear regression, with either the LinearAlgebra package, or the Statistics package.
 
<langsyntaxhighlight lang="maple">LinearAlgebra[LeastSquares](X,Y)^+;
# [4.33701132468683, -2.78654498997457, -1.41840666085642, 2.92065133466547, 1.76076442997642]
 
Line 1,828 ⟶ 2,173:
# R-squared: 0.9767, Adjusted R-squared: 0.9761
# 4.33701132468683 x1 - 2.78654498997457 x2 - 1.41840666085642 x3
# + 2.92065133466547 x4 + 1.76076442997642 c</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">x = {1.47, 1.50 , 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83};
y = {52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46};
X = {x^0, x^1, x^2};
LeastSquares[Transpose@X, y]</syntaxhighlight>
b = y.PseudoInverse[X]
{{out}}
 
-<pre>{128.813, -143.162, 61.9603}</langpre>
 
=={{header|MATLAB}}==
Line 1,842 ⟶ 2,187:
The slash and backslash operator can be used for solving this problem. Here some random data is generated.
 
<langsyntaxhighlight Matlablang="matlab"> n=100; k=10;
y = randn (1,n); % generate random vector y
X = randn (k,n); % generate random matrix X
b = y / X
b = 0.1457109 -0.0777564 -0.0712427 -0.0166193 0.0292955 -0.0079111 0.2265894 -0.0561589 -0.1752146 -0.2577663 </langsyntaxhighlight>
 
In its transposed form yt = Xt * bt, the backslash operator can be used.
 
<langsyntaxhighlight Matlablang="matlab"> yt = y'; Xt = X';
bt = Xt \ yt
bt =
Line 1,862 ⟶ 2,207:
-0.0561589
-0.1752146
-0.2577663</langsyntaxhighlight>
 
Here is the example for estimating the polynomial fit
 
<langsyntaxhighlight Matlablang="matlab"> x = [1.47 1.50 1.52 1.55 1.57 1.60 1.63 1.65 1.68 1.70 1.73 1.75 1.78 1.80 1.83]
y = [52.21 53.12 54.48 55.84 57.20 58.57 59.93 61.29 63.11 64.47 66.28 68.10 69.92 72.19 74.46]
X = [x.^0;x.^1;x.^2];
b = y/X
 
128.813 -143.162 61.960</langsyntaxhighlight>
 
Instead of "/", the slash operator, one can also write :
<langsyntaxhighlight Matlablang="matlab"> b = y * X' * inv(X * X') </langsyntaxhighlight>
or
<langsyntaxhighlight Matlablang="matlab"> b = y * pinv(X) </langsyntaxhighlight>
 
=={{header|Nim}}==
{{libheader|arraymancer}}
<langsyntaxhighlight Nimlang="nim"># Using Wikipedia data sample.
 
import math
Line 1,896 ⟶ 2,241:
var a = stack(height.ones_like, height, height *. height, axis = 1)
 
echo toSeq(least_squares_solver(a, weight).solution.items)</langsyntaxhighlight>
 
{{out}}
Line 1,902 ⟶ 2,247:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">pseudoinv(M)=my(sz=matsize(M),T=conj(M))~;if(sz[1]<sz[2],T/(M*T),(T*M)^-1*T)
addhelp(pseudoinv, "pseudoinv(M): Moore pseudoinverse of the matrix M.");
 
y*pseudoinv(X)</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use Statistics::Regression;
Line 1,920 ⟶ 2,265:
my @coeff = $reg->theta();
 
printf "%-6s %8.3f\n", $model[$_], $coeff[$_] for 0..@model-1;</langsyntaxhighlight>
{{out}}
<pre>const 128.813
Line 1,928 ⟶ 2,273:
=={{header|Phix}}==
{{trans|ERRE}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant N = 15, M=3
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
sequence x = {1.47,1.50,1.52,1.55,1.57,
<span style="color: #008080;">constant</span> <span style="color: #000000;">N</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">15</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">M</span><span style="color: #0000FF;">=</span><span style="color: #000000;">3</span>
1.60,1.63,1.65,1.68,1.70,
<span style="color: #004080;">sequence</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1.47</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.50</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.52</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.55</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.57</span><span style="color: #0000FF;">,</span>
1.73,1.75,1.78,1.80,1.83},
<span style="color: #000000;">1.60</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.63</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.65</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.68</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.70</span><span style="color: #0000FF;">,</span>
y = {52.21,53.12,54.48,55.84,57.20,
<span style="color: #000000;">1.73</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.75</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.78</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.80</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.83</span><span style="color: #0000FF;">},</span>
58.57,59.93,61.29,63.11,64.47,
<span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">52.21</span><span style="color: #0000FF;">,</span><span style="color: #000000;">53.12</span><span style="color: #0000FF;">,</span><span style="color: #000000;">54.48</span><span style="color: #0000FF;">,</span><span style="color: #000000;">55.84</span><span style="color: #0000FF;">,</span><span style="color: #000000;">57.20</span><span style="color: #0000FF;">,</span>
66.28,68.10,69.92,72.19,74.46},
<span style="color: #000000;">58.57</span><span style="color: #0000FF;">,</span><span style="color: #000000;">59.93</span><span style="color: #0000FF;">,</span><span style="color: #000000;">61.29</span><span style="color: #0000FF;">,</span><span style="color: #000000;">63.11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">64.47</span><span style="color: #0000FF;">,</span>
s = repeat(0,N),
<span style="color: #000000;">66.28</span><span style="color: #0000FF;">,</span><span style="color: #000000;">68.10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">69.92</span><span style="color: #0000FF;">,</span><span style="color: #000000;">72.19</span><span style="color: #0000FF;">,</span><span style="color: #000000;">74.46</span><span style="color: #0000FF;">},</span>
t = repeat(0,N),
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">),</span>
a = repeat(repeat(0,M+1),M)
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">M</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span><span style="color: #000000;">M</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">M</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">N</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">k</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">M</span> <span style="color: #008080;">then</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]*</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">k</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- build linear system</span>
for k=1 to 2*M do
for i=1 to N do
s[k] += power(x[i],k-1)
if k<=M then t[k] += y[i]*power(x[i],k-1) end if
end for
end for
<span style="color: #008080;">for</span> <span style="color: #000000;">row</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">M</span> <span style="color: #008080;">do</span>
-- build linear system
<span style="color: #008080;">for</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">M</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">row</span><span style="color: #0000FF;">,</span><span style="color: #000000;">col</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">row</span><span style="color: #0000FF;">+</span><span style="color: #000000;">col</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">row</span><span style="color: #0000FF;">,</span><span style="color: #000000;">M</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">row</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Linear system coefficents:\n"</span><span style="color: #0000FF;">)</span>
for row=1 to M do
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,{</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_IntFmt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%7.1f"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_FltFmt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%7.1f"</span><span style="color: #0000FF;">})</span>
for col=1 to M do
a[row,col] = s[row+col-1]
end for
a[row,M+1] = t[row]
end for
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">M</span> <span style="color: #008080;">do</span>
puts(1,"Linear system coefficents:\n")
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">j</span>
pp(a,{pp_Nest,1,pp_IntFmt,"%7.1f",pp_FltFmt,"%7.1f"})
<span style="color: #008080;">while</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
 
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">M</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
for j=1 to M do
<span style="color: #0000FF;">?</span><span style="color: #008000;">"SINGULAR MATRIX !"</span>
integer i = j
<span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span>
while a[i,j]=0 do i += 1 end while
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if i=M+1 then
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">M</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
?"SINGULAR MATRIX !"
<span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">],</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">],</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]}</span>
?9/0
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end if
<span style="color: #004080;">atom</span> <span style="color: #000000;">Y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span>
for k=1 to M+1 do
<span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">Y</span><span style="color: #0000FF;">)</span>
{a[j,k],a[i,k]} = {a[i,k],a[j,k]}
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">M</span> <span style="color: #008080;">do</span>
end for
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;"><></span><span style="color: #000000;">j</span> <span style="color: #008080;">then</span>
atom Y = 1/a[j,j]
<span style="color: #000000;">Y</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span>
a[j] = sq_mul(a[j],Y)
<span style="color: #008080;">for</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">M</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
for i=1 to M do
<span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">Y</span><span style="color: #0000FF;">*</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">]</span>
if i<>j then
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
Y=-a[i,j]
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
for k=1 to M+1 do
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
a[i,k] += Y*a[j,k]
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
end if
end for
end for
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Solutions:\n"</span><span style="color: #0000FF;">)</span>
puts(1,"Solutions:\n")
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">M</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
?columnize(a,M+1)[1]</lang>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,993 ⟶ 2,341:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(scl 20)
 
# Matrix transposition
Line 2,035 ⟶ 2,383:
(car X) ) ) ) )
(T (> (inc 'Lead) Cols)) ) )
Mat )</langsyntaxhighlight>
{{trans|JavaScript}}
<langsyntaxhighlight PicoLisplang="picolisp">(de matInverse (Mat)
(let N (length Mat)
(unless (= N (length (car Mat)))
Line 2,055 ⟶ 2,403:
X (columnVector (2.0 1.0 3.0 4.0 5.0)) )
 
(round (caar (regressionCoefficients Y X)) 17)</langsyntaxhighlight>
{{out}}
<pre>-> "0.98181818181818182"</pre>
Line 2,062 ⟶ 2,410:
{{libheader|NumPy}}
'''Method with matrix operations'''
<langsyntaxhighlight lang="python">import numpy as np
 
height = [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63,
Line 2,072 ⟶ 2,420:
y = np.mat(weight)
 
print(y * X.T * (X*X.T).I)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,078 ⟶ 2,426:
</pre>
'''Using numpy lstsq function'''
<langsyntaxhighlight lang="python">import numpy as np
 
height = [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63,
Line 2,088 ⟶ 2,436:
y = weight
 
print(np.linalg.lstsq(X, y)[0])</langsyntaxhighlight>
{{out}}
<pre>
Line 2,098 ⟶ 2,446:
R provides the '''lm''' function for linear regression.
 
<langsyntaxhighlight Rlang="rsplus">x <- c(1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83)
y <- c(52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46)
 
lm( y ~ x + I(x^2))</langsyntaxhighlight>
 
{{out}}
Line 2,115 ⟶ 2,463:
is useful to illustrate R's model description and linear algebra capabilities.
 
<langsyntaxhighlight Rlang="rsplus">simpleMultipleReg <- function(formula) {
 
## parse and evaluate the model formula
Line 2,121 ⟶ 2,469:
 
## create design matrix
X <- model.matrix(attr(mf, "terms"), mf)
 
## create dependent variable
Line 2,130 ⟶ 2,478:
}
 
simpleMultipleReg(y ~ x + I(x^2))</langsyntaxhighlight>
 
This produces the same coefficients as lm()
Line 2,144 ⟶ 2,492:
than the method above, is to solve the linear system directly
and use the crossprod function:
<langsyntaxhighlight Rlang="r">solve(crossprod(X), crossprod(X, Y))</langsyntaxhighlight>
 
A numerically more stable way is to use the QR decomposition of the design matrix:
 
<syntaxhighlight lang="rsplus">lm.impl <- function(formula) {
<lang R>qr.coef(qr(X), y)</lang>
mf <- model.frame(formula)
X <- model.matrix(mf)
Y <- model.response(mf)
qr.coef(qr(X), Y)
}
 
 
lm(y ~ x + I(x^2))
 
# Call:
# lm(formula = y ~ x + I(x^2))
#
# Coefficients:
# (Intercept) x I(x^2)
# 128.81 -143.16 61.96
 
lm.impl(y ~ x + I(x^2))
 
# (Intercept) x I(x^2)
# 128.81280 -143.16202 61.96033</syntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 2,158 ⟶ 2,526:
(define (fit X y)
(matrix-solve (matrix* (T X) X) (matrix* (T X) y)))
</syntaxhighlight>
</lang>
Test:
<langsyntaxhighlight lang="racket">
(fit (matrix [[1 2]
[2 5]
Line 2,171 ⟶ 2,539:
{{out}}
(array #[#[9 1/3] #[-3 1/3]])
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
{{broken}}
(formerly Perl 6)
We're going to solve the example on the Wikipedia article using [https://github.com/grondilu/clifford Clifford], a [https://en.wikipedia.org/wiki/Geometric_algebra geometric algebra] module. Optimization for large vector space does not quite work yet, so it's going to take (a lof of) time and a fair amount of memory, but it should work.
Line 2,201 ⟶ 2,570:
 
 
<syntaxhighlight lang="raku" perl6line>use Clifford;
my @height = <1.47 1.50 1.52 1.55 1.57 1.60 1.63 1.65 1.68 1.70 1.73 1.75 1.78 1.80 1.83>;
my @weight = <52.21 53.12 54.48 55.84 57.20 58.57 59.93 61.29 63.11 64.47 66.28 68.10 69.92 72.19 74.46>;
Line 2,216 ⟶ 2,585:
say "α = ", ($w∧$h1∧$h2)·$I.reversion/$I2;
say "β = ", ($w∧$h2∧$h0)·$I.reversion/$I2;
say "γ = ", ($w∧$h0∧$h1)·$I.reversion/$I2;</langsyntaxhighlight>
{{out}}
<pre>α = 128.81280357844
Line 2,229 ⟶ 2,598:
Using the standard library Matrix class:
 
<langsyntaxhighlight lang="ruby">require 'matrix'
 
def regression_coefficients y, x
Line 2,236 ⟶ 2,605:
 
(x.t * x).inverse * x.t * y
end</langsyntaxhighlight>
 
Testing 2-dimension:
<langsyntaxhighlight lang="ruby">puts regression_coefficients([1, 2, 3, 4, 5], [ [2, 1, 3, 4, 5] ])</langsyntaxhighlight>
{{out}}
<pre>Matrix[[0.981818181818182]]</pre>
Line 2,245 ⟶ 2,614:
Testing 3-dimension:
Points(x,y,z): [1,1,3], [2,1,4] and [1,2,5]
<langsyntaxhighlight lang="ruby">puts regression_coefficients([3,4,5], [ [1,2,1], [1,1,2] ])</langsyntaxhighlight>
{{out}}
<pre>Matrix[[0.9999999999999996], [2.0]]</pre>
Line 2,253 ⟶ 2,622:
First, build a random dataset:
 
<syntaxhighlight lang="text">set rng=mc seed=17760704.
new file.
input program.
Line 2,266 ⟶ 2,635:
end input program.
compute y=1.5+0.8*x1-0.7*x2+1.1*x3-1.7*x4+rv.normal(0,1).
execute.</langsyntaxhighlight>
 
Now use the regression command:
 
<syntaxhighlight lang="text">regression /dependent=y
/method=enter x1 x2 x3 x4.</langsyntaxhighlight>
 
{{out}}
 
<syntaxhighlight lang="text">Regression
Notes
|--------------------------------------------------------------------|---------------------------------------------------------------------------|
Line 2,351 ⟶ 2,720:
| |x4 |-1,770 |,073 |-,656 |-24,306|,000|
|----------------------------------------------------------------------------------------------|
a Dependent Variable: y</langsyntaxhighlight>
 
=={{header|Stata}}==
Line 2,357 ⟶ 2,726:
First, build a random dataset:
 
<langsyntaxhighlight lang="stata">clear
set seed 17760704
set obs 200
Line 2,363 ⟶ 2,732:
gen x`i'=rnormal()
}
gen y=1.5+0.8*x1-0.7*x2+1.1*x3-1.7*x4+rnormal()</langsyntaxhighlight>
 
Now, use the '''[https://www.stata.com/help.cgi?regress regress]''' command:
 
<syntaxhighlight lang ="stata">reg y x*</langsyntaxhighlight>
 
'''Output'''
Line 2,392 ⟶ 2,761:
The regress command also sets a number of '''[https://www.stata.com/help.cgi?ereturn ereturn]''' values, which can be used by subsequent commands. The coefficients and their standard errors also have a [https://www.stata.com/help.cgi?_variables special syntax]:
 
<langsyntaxhighlight lang="stata">. di _b[x1]
.75252466
 
Line 2,402 ⟶ 2,771:
 
. di _se[_cons]
.06978623</langsyntaxhighlight>
 
See '''[https://www.stata.com/help.cgi?regress_postestimation regress postestimation]''' for a list of commands that can be used after a regression.
Line 2,408 ⟶ 2,777:
Here we compute [[wp:Akaike information criterion|Akaike's AIC]], the covariance matrix of the estimates, the predicted values and residuals:
 
<langsyntaxhighlight lang="stata">. estat ic
 
Akaike's information criterion and Bayesian information criterion
Line 2,432 ⟶ 2,801:
 
. predict yhat, xb
. predict r, r</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{tcllib|math::linearalgebra}}
<langsyntaxhighlight lang="tcl">package require math::linearalgebra
namespace eval multipleRegression {
namespace export regressionCoefficients
Line 2,451 ⟶ 2,820:
}
}
namespace import multipleRegression::regressionCoefficients</langsyntaxhighlight>
Using an example from the Wikipedia page on the correlation of height and weight:
<langsyntaxhighlight lang="tcl"># Simple helper just for this example
proc map {n exp list} {
upvar 1 $n v
Line 2,468 ⟶ 2,837:
}
# Wikipedia states that fitting up to the square of x[i] is worth it
puts [regressionCoefficients $y [map n {map v {expr {$v**$n}} $x} {0 1 2}]]</langsyntaxhighlight>
{{out}} (a 3-vector of coefficients):
<pre>128.81280358170625 -143.16202286630732 61.96032544293041</pre>
Line 2,474 ⟶ 2,843:
=={{header|TI-83 BASIC}}==
{{works with|TI-83 BASIC|TI-84Plus 2.55MP}}
<langsyntaxhighlight lang="ti83b">{1.47,1.50,1.52,1.55,1.57,1.60,1.63,1.65,1.68,1.70,1.73,1.75,1.78,1.80,1.83}→L₁
{52.21,53.12,54.48,55.84,57.20,58.57,59.93,61.29,63.11,64.47,66.28,68.10,69.92,72.19,74.46}→L₂
QuadReg L₁,L₂ </langsyntaxhighlight>
{{out}}
<pre>
Line 2,489 ⟶ 2,858:
the Lapack library [http://www.netlib.org/lapack/lug/node27.html],
which is callable in Ursala like this:
<langsyntaxhighlight Ursalalang="ursala">regression_coefficients = lapack..dgelsd</langsyntaxhighlight>
test program:
<syntaxhighlight lang="ursala">x =
<lang Ursala>x =
 
<
Line 2,502 ⟶ 2,871:
#cast %eL
 
example = regression_coefficients(x,y)</langsyntaxhighlight>
The matrix x needn't be square, and has one row for each data point.
The length of y must equal the number of rows in x,
Line 2,519 ⟶ 2,888:
=={{header|Visual Basic .NET}}==
{{trans|Java}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Sub Swap(Of T)(ByRef x As T, ByRef y As T)
Line 2,748 ⟶ 3,117:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>[0.981818181818182]
Line 2,757 ⟶ 3,126:
{{trans|Kotlin}}
{{libheader|Wren-matrix}}
<langsyntaxhighlight ecmascriptlang="wren">import "./matrix" for Matrix
 
var multipleRegression = Fn.new { |y, x|
Line 2,784 ⟶ 3,153:
System.print(v)
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 2,797 ⟶ 3,166:
=={{header|zkl}}==
Using the GNU Scientific Library:
<langsyntaxhighlight lang="zkl">var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
height:=GSL.VectorFromData(1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63,
1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83);
Line 2,805 ⟶ 3,174:
v.format().println();
GSL.Helpers.polyString(v).println();
GSL.Helpers.polyEval(v,height).format().println();</langsyntaxhighlight>
{{out}}
<pre>
Line 2,815 ⟶ 3,184:
Or, using Lists:
{{trans|Common Lisp}}
<langsyntaxhighlight lang="zkl">// Solve a linear system AX=B where A is symmetric and positive definite, so it can be Cholesky decomposed.
fcn linsys(A,B){
n,m:=A.len(),B[1].len(); // A.rows,B.cols
Line 2,870 ⟶ 3,239:
if(M.len()==1) M[0].pump(List,List.create); // 1 row --> n columns
else M[0].zip(M.xplode(1));
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">height:=T(T(1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63,
1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83));
weight:=T(T(52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93,
61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46));
polyfit(height,weight,2).flatten().println();</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits