|
| 1 | +#include <bits/stdc++.h> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +// A simple structure for data points |
| 5 | +struct Point |
| 6 | +{ |
| 7 | + vector<double> features; // coordinates/features |
| 8 | + int label; // class label (e.g., 0 or 1) |
| 9 | +}; |
| 10 | + |
| 11 | +// Function to compute Euclidean distance |
| 12 | +double euclideanDistance(const vector<double> &a, const vector<double> &b) |
| 13 | +{ |
| 14 | + double sum = 0.0; |
| 15 | + for (size_t i = 0; i < a.size(); i++) |
| 16 | + { |
| 17 | + sum += (a[i] - b[i]) * (a[i] - b[i]); |
| 18 | + } |
| 19 | + return sqrt(sum); |
| 20 | +} |
| 21 | + |
| 22 | +// k-NN classification |
| 23 | +int classifyKNN(const vector<Point> &dataset, const vector<double> &query, int k) |
| 24 | +{ |
| 25 | + // Compute distances from query to all dataset points |
| 26 | + vector<pair<double, int>> distances; |
| 27 | + for (const auto &p : dataset) |
| 28 | + { |
| 29 | + double dist = euclideanDistance(p.features, query); |
| 30 | + distances.push_back({dist, p.label}); |
| 31 | + } |
| 32 | + |
| 33 | + // Sort by distance |
| 34 | + sort(distances.begin(), distances.end()); |
| 35 | + |
| 36 | + // Count labels among k nearest neighbors |
| 37 | + unordered_map<int, int> freq; |
| 38 | + for (int i = 0; i < k; i++) |
| 39 | + { |
| 40 | + freq[distances[i].second]++; |
| 41 | + } |
| 42 | + |
| 43 | + // Find majority class |
| 44 | + int maxCount = 0, predictedLabel = -1; |
| 45 | + for (auto &entry : freq) |
| 46 | + { |
| 47 | + if (entry.second > maxCount) |
| 48 | + { |
| 49 | + maxCount = entry.second; |
| 50 | + predictedLabel = entry.first; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return predictedLabel; |
| 55 | +} |
| 56 | + |
| 57 | +int main() |
| 58 | +{ |
| 59 | + // Example dataset: 2D points with labels (0 or 1) |
| 60 | + vector<Point> dataset = { |
| 61 | + {{1.0, 2.0}, 0}, |
| 62 | + {{2.0, 3.0}, 0}, |
| 63 | + {{3.0, 3.0}, 0}, |
| 64 | + {{6.0, 5.0}, 1}, |
| 65 | + {{7.0, 7.0}, 1}, |
| 66 | + {{8.0, 6.0}, 1}}; |
| 67 | + |
| 68 | + // Query point to classify |
| 69 | + vector<double> query = {5.0, 5.0}; |
| 70 | + |
| 71 | + int k = 3; // Number of neighbors |
| 72 | + int predictedLabel = classifyKNN(dataset, query, k); |
| 73 | + |
| 74 | + cout << "Query Point: (" << query[0] << ", " << query[1] << ")" << endl; |
| 75 | + cout << "Predicted Class: " << predictedLabel << endl; |
| 76 | + |
| 77 | + return 0; |
| 78 | +} |
0 commit comments