Learnx.LinearRegression (Learnx v0.2.0)
Ordinary least squares Linear Regression.
LinearRegression fits a linear model with coefficients w = (w1, ..., wp) to minimize the residual sum of squares between the observed targets in the dataset, and the targets predicted by the linear approximation.
Link to this section Summary
Link to this section Types
regressor()
@type regressor() :: %Learnx.LinearRegression{ coef: tensor(), intercept: number(), n_features: number() }
Linear regressor.
coef : tensor of shape {n_features, }. Estimated coefficients for the linear regression problem.
intercept : float. Independent term in the linear model. Set to nil if fit_intercept = False.
n_features : int. Number of features seen during fit.
tensor()
@type tensor() :: Nx.Tensor.t()
Link to this section Functions
fit(x, y, opts \\ [])
Fits linear model.
parameters
Parameters
x : list or tensor of shape {n_samples, n_features} or {n_samples,}. Training data.
y : list or tensor of shape {n_samples,}. Target values. Will be cast to X's type if necessary.
intercept : boolean. Wether or not to use intercept in calculations. Simple linear regression will always use intercept.
returns
Returns
A linear regressor containing the coefficients, intercept (if chosen) and number of features.
examples
Examples
With lists as inputs:
iex> x = [-1, 1, 3, 5]
iex> y = [6, 8, 10, 12]
iex> reg = Learnx.LinearRegression.fit(x, y)
iex> reg.coef
#Nx.Tensor<
f32
1.0
>
iex> reg.intercept
7.0
iex> reg.n_features
1
With tensors:
iex> x = Nx.tensor([-1, 1, 3, 5])
iex> y = Nx.tensor([6, 8, 10, 12])
iex> reg = Learnx.LinearRegression.fit(x, y)
iex> reg.coef
#Nx.Tensor<
f32
1.0
>
iex> reg.intercept
7.0
iex> reg.n_features
1
With multiple features as the input:
iex> x = [[1, 1], [1, 2], [2, 2], [2, 3]]
iex> y = [6, 8, 9, 11]
iex> reg = Learnx.LinearRegression.fit(x, y)
iex> reg.coef
#Nx.Tensor<
f32[2]
[1.0, 2.0]
>
iex> reg.intercept
2.999993324279785
iex> reg.n_features
2
predict(regressor, x)
Predicts using the linear model.
parameters
Parameters
regressor : trained regressor to use for the predictions.
x : number, list or tensor of shape {n_observations, n_features}. Observations to predict.
returns
Returns
Predicted value or values. Returns the prediction(s) in the type of the input, i. e. if x is a tensor, it returns a tensor; and if x is a number, it returns a number.
examples
Examples
Single feature regression:
iex> x = [-1, 1, 3, 5]
iex> y = [6, 8, 10, 12]
iex> reg = Learnx.LinearRegression.fit(x, y)
iex> reg |> Learnx.LinearRegression.predict(2)
9.0
iex> reg |> Learnx.LinearRegression.predict([4, 6])
[11.0, 13.0]
Multiple features regression:
iex> x = [[1, 1], [1, 2], [2, 2], [2, 3]]
iex> y = [6, 8, 10, 12]
iex> reg = Learnx.LinearRegression.fit(x, y)
iex> reg |> Learnx.LinearRegression.predict([3, 3])
[13.999992370605469]