Class: Lurn::Neighbors::KNNRegression

Inherits:
KNNBase
  • Object
show all
Defined in:
lib/lurn/neighbors/knn_regression.rb

Instance Attribute Summary

Attributes inherited from KNNBase

#k, #predictors, #targets

Instance Method Summary collapse

Methods inherited from KNNBase

#fit, #initialize, #nearest_neighbors

Constructor Details

This class inherits a constructor from Lurn::Neighbors::KNNBase

Instance Method Details

#predict(vector) ⇒ Float

Predicts the value of the given observation by averaging the target value of the closest k predictor observations based on euclidian distance.

Parameters:

  • vector (Array-like)

    An array (or array-like) of the same length as the predictors used to fit the model

Returns:

  • (Float)

    The predicted value



12
13
14
15
16
# File 'lib/lurn/neighbors/knn_regression.rb', line 12

def predict(vector)
  _, neighboring_targets = nearest_neighbors(vector)

  neighboring_targets.inject(:+).to_f / neighboring_targets.length.to_f
end