Skip to content

Commit fb1b233

Browse files
committed
add score function for calc accuracy
1 parent e1eeb68 commit fb1b233

2 files changed

Lines changed: 59 additions & 0 deletions

File tree

lib/learn_kit/naive_bayes/gaussian.ex

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ defmodule LearnKit.NaiveBayes.Gaussian do
99

1010
use Gaussian.Fit
1111
use Gaussian.Classify
12+
use Gaussian.Score
1213

1314
@type label :: atom
1415
@type feature :: [integer]
@@ -145,4 +146,26 @@ defmodule LearnKit.NaiveBayes.Gaussian do
145146
|> Enum.sort_by(&(elem(&1, 1)))
146147
|> Enum.at(-1)
147148
end
149+
150+
@doc """
151+
Returns the mean accuracy on the given test data and labels
152+
153+
## Parameters
154+
155+
- classificator: %LearnKit.NaiveBayes.Gaussian{}
156+
157+
## Examples
158+
159+
iex> classificator = LearnKit.NaiveBayes.Gaussian.new([{:label1, [[-1, -1], [-2, -1], [-3, -2]]}, {:label2, [[1, 1], [2, 1], [3, 2], [-2, -2]]}])
160+
iex> classificator = classificator |> LearnKit.NaiveBayes.Gaussian.fit
161+
iex> classificator |> LearnKit.NaiveBayes.Gaussian.score
162+
0.857143
163+
164+
"""
165+
@spec score(%LearnKit.NaiveBayes.Gaussian{data_set: data_set, fit_data: fit_data}) :: number
166+
167+
def score(%Gaussian{data_set: data_set, fit_data: fit_data}) do
168+
fit_data
169+
|> calc_score(data_set)
170+
end
148171
end
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
defmodule LearnKit.NaiveBayes.Gaussian.Score do
2+
@moduledoc """
3+
Module for calculating accuracy of prediction
4+
"""
5+
6+
alias LearnKit.NaiveBayes.Gaussian
7+
alias LearnKit.Math
8+
9+
defmacro __using__(_opts) do
10+
quote do
11+
defp calc_score(fit_data, data_set) do
12+
data_set
13+
|> Enum.map(fn {label, features} ->
14+
features
15+
|> check_features(fit_data, label)
16+
end)
17+
|> List.flatten
18+
|> Math.mean
19+
|> Float.ceil(6)
20+
end
21+
22+
defp check_features(features, fit_data, label) do
23+
features
24+
|> Enum.map(fn feature ->
25+
feature
26+
|> check_feature(fit_data, label)
27+
end)
28+
end
29+
30+
defp check_feature(feature, fit_data, label) do
31+
{predicted_label, _} = Gaussian.predict(%Gaussian{fit_data: fit_data}, feature)
32+
if predicted_label == label, do: 1, else: 0
33+
end
34+
end
35+
end
36+
end

0 commit comments

Comments
 (0)