Skip to content

Commit dd8a16b

Browse files
committed
modify distance calculation between points for KNN
1 parent 1558dbc commit dd8a16b

2 files changed

Lines changed: 24 additions & 9 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
66

77
## Unreleased
88
### Modified
9-
- K-Nearest Neighbours algorithm, add errors conditions and tests
9+
- errors conditions and tests for KNN
10+
- distance calculation between points for KNN
1011

1112
## [0.1.3] - 2018-11-22
1213
### Modified

lib/learn_kit/knn/classify.ex

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -83,22 +83,36 @@ defmodule LearnKit.Knn.Classify do
8383

8484
defp calc_distances_in_label(features, current_feature, key) do
8585
Enum.reduce(features, [], fn feature, acc ->
86-
distance = calc_distance_between_points(0, feature, current_feature, 0, length(feature) - 1)
86+
distance = calc_distance_between_features(feature, current_feature)
8787
acc = [{distance, key} | acc]
8888
end)
8989
end
9090

91-
defp calc_distance_between_points(acc, feature_from_data_set, feature, current_index, size) when current_index <= size do
92-
Enum.at(feature_from_data_set, current_index) - Enum.at(feature, current_index)
93-
|> :math.pow(2)
94-
|> Math.summ(acc)
95-
|> calc_distance_between_points(feature_from_data_set, feature, current_index + 1, size)
91+
defp calc_distance_between_features(feature_from_data_set, feature) do
92+
Enum.zip(feature_from_data_set, feature)
93+
|> calc_distance_between_points()
94+
|> :math.sqrt()
9695
end
9796

98-
defp calc_distance_between_points(acc, _, _, _, _) do
99-
:math.sqrt(acc)
97+
defp calc_distance_between_points(list) do
98+
Enum.reduce(list, 0, fn {xi, yi}, acc ->
99+
xi - yi
100+
|> :math.pow(2)
101+
|> Math.summ(acc)
102+
end)
100103
end
101104

105+
#defp calc_distance_between_points(acc, feature_from_data_set, feature, current_index, size) when current_index <= size do
106+
# Enum.at(feature_from_data_set, current_index) - Enum.at(feature, current_index)
107+
# |> :math.pow(2)
108+
# |> Math.summ(acc)
109+
# |> calc_distance_between_points(feature_from_data_set, feature, current_index + 1, size)
110+
#end
111+
112+
#defp calc_distance_between_points(acc, _, _, _, _) do
113+
# :math.sqrt(acc)
114+
#end
115+
102116
defp calc_feature_weight(weight, distance) do
103117
case weight do
104118
"uniform" -> 1

0 commit comments

Comments
 (0)