Skip to content

Commit b319d87

Browse files
committed
modify knn classification structure
1 parent 04b0568 commit b319d87

2 files changed

Lines changed: 33 additions & 15 deletions

File tree

lib/learn_kit/knn.ex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ defmodule LearnKit.Knn do
77

88
alias LearnKit.{Knn}
99

10-
use Knn.Predict
10+
use Knn.Classify
1111

1212
@doc """
1313
Creates classificator with empty data_set
Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
defmodule LearnKit.Knn.Predict do
1+
defmodule LearnKit.Knn.Classify do
22
@moduledoc """
33
Module for knn prediction functions
44
"""
5-
65
defmacro __using__(_opts) do
76
quote do
87
defp prediction(data_set, options) do
@@ -52,23 +51,42 @@ defmodule LearnKit.Knn.Predict do
5251

5352
# brute algorithm for prediction
5453
defp brute_algorithm(data_set, options) do
55-
Keyword.keys(data_set)
54+
data_set
55+
|> Keyword.keys
56+
|> handle_features_in_label(data_set, Keyword.get(options, :feature))
57+
|> List.flatten
58+
end
59+
60+
defp handle_features_in_label(keys, data_set, current_feature) do
61+
keys
5662
|> Enum.map(fn key ->
57-
Keyword.get(data_set, key)
58-
|> Enum.reduce([], fn feature, acc ->
59-
distance = feature |> calc_distance_between_features(Keyword.get(options, :feature))
60-
if distance == 0 do
61-
raise "Feature exists in train data set with label #{key}"
62-
end
63-
acc = [{distance, key} | acc]
64-
end)
63+
data_set
64+
|> Keyword.get(key)
65+
|> filter_features_by_size(current_feature)
66+
|> calc_distances_in_label(current_feature, key)
67+
end)
68+
end
69+
70+
defp filter_features_by_size(features, current_feature) do
71+
features
72+
|> Enum.filter(fn feature ->
73+
length(feature) == length(current_feature)
74+
end)
75+
end
76+
77+
defp calc_distances_in_label(features, current_feature, key) do
78+
features
79+
|> Enum.reduce([], fn feature, acc ->
80+
distance = feature |> calc_distance_between_features(current_feature)
81+
if distance == 0 do
82+
raise "Feature exists in train data set with label #{key}"
83+
end
84+
acc = [{distance, key} | acc]
6585
end)
66-
|> List.flatten
6786
end
6887

6988
defp calc_distance_between_features(feature_from_data_set, feature) do
70-
size = length(feature_from_data_set)
71-
calc_distance_between_points(0, feature_from_data_set, feature, 0, size - 1)
89+
calc_distance_between_points(0, feature_from_data_set, feature, 0, length(feature_from_data_set) - 1)
7290
end
7391

7492
defp calc_distance_between_points(acc, feature_from_data_set, feature, current_index, size) when current_index <= size do

0 commit comments

Comments
 (0)