1 #ifndef KNN_REGRESSOR_HPP
2 #define KNN_REGRESSOR_HPP
35 void fit(
const std::vector<std::vector<double>>& X,
const std::vector<double>& y);
42 std::vector<double>
predict(
const std::vector<std::vector<double>>& X)
const;
46 std::vector<std::vector<double>> X_train;
47 std::vector<double> y_train;
55 double euclidean_distance(
const std::vector<double>& a,
const std::vector<double>& b)
const;
62 double predict_sample(
const std::vector<double>& x)
const;
69 void KNNRegressor::fit(
const std::vector<std::vector<double>>& X,
const std::vector<double>& y) {
75 std::vector<double> predictions;
76 predictions.reserve(X.size());
77 for (
const auto& x : X) {
78 predictions.push_back(predict_sample(x));
83 double KNNRegressor::euclidean_distance(
const std::vector<double>& a,
const std::vector<double>& b)
const {
84 double distance = 0.0;
85 for (
size_t i = 0; i < a.size(); ++i) {
86 double diff = a[i] - b[i];
87 distance += diff * diff;
89 return std::sqrt(distance);
92 double KNNRegressor::predict_sample(
const std::vector<double>& x)
const {
94 std::vector<std::pair<double, double>> distances;
95 distances.reserve(X_train.size());
98 for (
size_t i = 0; i < X_train.size(); ++i) {
99 double dist = euclidean_distance(x, X_train[i]);
100 distances.emplace_back(dist, y_train[i]);
104 std::nth_element(distances.begin(), distances.begin() + k, distances.end(),
105 [](
const std::pair<double, double>& a,
const std::pair<double, double>& b) {
106 return a.first < b.first;
111 for (
int i = 0; i < k; ++i) {
112 sum += distances[i].second;
K-Nearest Neighbors Regressor for regression tasks.
Definition: KNNRegressor.hpp:17
~KNNRegressor()
Destructor for KNNRegressor.
Definition: KNNRegressor.hpp:67
void fit(const std::vector< std::vector< double >> &X, const std::vector< double > &y)
Fits the regressor to the training data.
Definition: KNNRegressor.hpp:69
std::vector< double > predict(const std::vector< std::vector< double >> &X) const
Predicts target values for the given input data.
Definition: KNNRegressor.hpp:74
KNNRegressor(int k=3)
Constructs a KNNRegressor.
Definition: KNNRegressor.hpp:65