linreg(x,y)
linreg(x, y) -> a, b
Perform linear regression. Returns a
and b
such that a + b*x
is the closest
straight line to the given points (x, y)
, i.e., such that the squared error
between y
and a + b*x
is minimized.
Example:
using PyPlot
x = [1.0:12.0;]
y = [5.5, 6.3, 7.6, 8.8, 10.9, 11.79, 13.48, 15.02, 17.77, 20.81, 22.0, 22.99]
a, b = linreg(x, y) # Linear regression
plot(x, y, "o") # Plot (x, y) points
plot(x, [a+b*i for i in x]) # Plot line determined by linear regression
Examples
julia> x = [1, 2, 3, 4, 5];
julia> y = [2, 4, 6, 8, 10];
julia> w = [1, 1, 1, 1, 1];
julia> linreg(x, y, w)
(2.0, 0.0)
This example performs a weighted least-squares linear regression on the given x
and y
data points, using the weights w
. It returns a tuple (slope, intercept)
representing the coefficients of the linear regression model.
julia> x = [1, 2, 3, 4, 5];
julia> y = [1, 3, 5, 7, 9];
julia> w = [1, 1, 1, 1, 1];
julia> linreg(x, y, w)
(2.0, -1.0)
In this example, the x
and y
values represent a perfect linear relationship with a slope of 2 and an intercept of -1.
Common mistake example:
julia> x = [1, 2, 3, 4, 5];
julia> y = [2, 4, 6, 8];
julia> w = [1, 1, 1, 1, 1];
julia> linreg(x, y, w)
ERROR: DimensionMismatch("arrays could not be broadcast to a common size")
In this example, the dimensions of x
and y
do not match, causing a DimensionMismatch
error. It's important to ensure that the input arrays have the same length to perform linear regression correctly.
See Also
User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.