|
1 | | -defmodule LearnKit.Knn.Predict do |
| 1 | +defmodule LearnKit.Knn.Classify do |
2 | 2 | @moduledoc """ |
3 | 3 | Module for knn prediction functions |
4 | 4 | """ |
5 | | - |
6 | 5 | defmacro __using__(_opts) do |
7 | 6 | quote do |
8 | 7 | defp prediction(data_set, options) do |
@@ -52,23 +51,42 @@ defmodule LearnKit.Knn.Predict do |
52 | 51 |
|
53 | 52 | # brute algorithm for prediction |
54 | 53 | 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 |
56 | 62 | |> 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] |
65 | 85 | end) |
66 | | - |> List.flatten |
67 | 86 | end |
68 | 87 |
|
69 | 88 | 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) |
72 | 90 | end |
73 | 91 |
|
74 | 92 | defp calc_distance_between_points(acc, feature_from_data_set, feature, current_index, size) when current_index <= size do |
|
0 commit comments