Skip to content

Commit c92174c

Browse files
committed
add Predict function for LinearRegression
1 parent 9766e3b commit c92174c

2 files changed

Lines changed: 40 additions & 5 deletions

File tree

lib/learn_kit/regression/linear.ex

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ defmodule LearnKit.Regression.Linear do
88
alias LearnKit.Regression.Linear
99

1010
use Linear.Fit
11+
use Linear.Predict
1112

1213
@type factors :: [number]
1314
@type results :: [number]
@@ -38,8 +39,8 @@ defmodule LearnKit.Regression.Linear do
3839
3940
## Examples
4041
41-
iex> predictor = LearnKit.Regression.Linear.new([1, 2, 3, 4], [2, 3, 4, 5])
42-
%LearnKit.Regression.Linear{factors: [1, 2, 3, 4], results: [2, 3, 4, 5], coefficients: []}
42+
iex> predictor = LearnKit.Regression.Linear.new([1, 2, 3, 4], [3, 6, 10, 15])
43+
%LearnKit.Regression.Linear{factors: [1, 2, 3, 4], results: [3, 6, 10, 15], coefficients: []}
4344
4445
"""
4546
@spec new(factors, results) :: %LearnKit.Regression.Linear{factors: factors, results: results, coefficients: []}
@@ -57,11 +58,11 @@ defmodule LearnKit.Regression.Linear do
5758
5859
## Examples
5960
60-
iex> predictor |> LearnKit.Regression.Linear.fit
61+
iex> predictor = predictor |> LearnKit.Regression.Linear.fit
6162
%LearnKit.Regression.Linear{
62-
coefficients: [1.0, 1.0],
63+
coefficients: [-1.5, 4.0],
6364
factors: [1, 2, 3, 4],
64-
results: [2, 3, 4, 5]
65+
results: [3, 6, 10, 15]
6566
}
6667
6768
"""
@@ -70,4 +71,26 @@ defmodule LearnKit.Regression.Linear do
7071
def fit(%Linear{factors: factors, results: results}) do
7172
%Linear{factors: factors, results: results, coefficients: fit_data(factors, results)}
7273
end
74+
75+
@doc """
76+
Predict using the linear model
77+
78+
## Parameters
79+
80+
- predictor: %LearnKit.Regression.Linear{}
81+
- samples: Array of variables
82+
83+
## Examples
84+
85+
iex> predictor |> LearnKit.Regression.Linear.predict([4, 8, 13])
86+
[14.5, 30.5, 50.5]
87+
88+
"""
89+
@spec predict(%LearnKit.Regression.Linear{coefficients: coefficients}, list) :: list
90+
91+
def predict(%Linear{coefficients: coefficients}, samples) do
92+
IO.inspect coefficients
93+
samples
94+
|> Enum.map(fn sample -> predict_sample(sample, coefficients) end)
95+
end
7396
end
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
defmodule LearnKit.Regression.Linear.Predict do
2+
@moduledoc """
3+
Module for fit functions
4+
"""
5+
defmacro __using__(_opts) do
6+
quote do
7+
defp predict_sample(sample, [alpha, beta]) do
8+
sample * beta + alpha
9+
end
10+
end
11+
end
12+
end

0 commit comments

Comments
 (0)