用cpp写一个KNN分类代码
时间: 2024-05-06 08:21:41 浏览: 9
好的,以下是一个用cpp写的简单KNN分类代码:
```
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
struct Data {
double feature1;
double feature2;
int label;
};
double calculateDistance(Data d1, Data d2) {
return sqrt(pow((d1.feature1 - d2.feature1), 2) + pow((d1.feature2 - d2.feature2), 2));
}
int knn(vector<Data>& data, Data& query, int k) {
vector<pair<double, int>> distances;
for (int i = 0; i < data.size(); i++) {
double distance = calculateDistance(query, data[i]);
distances.push_back(make_pair(distance, i));
}
sort(distances.begin(), distances.end());
int counts[2] = { 0, 0 }; // Assuming there are only two classes
for (int i = 0; i < k; i++) {
int index = distances[i].second;
counts[data[index].label]++;
}
return counts[0] > counts[1] ? 0 : 1; // Return the index with the most votes
}
int main() {
// Creating some sample data
vector<Data> data = {
{ 5.1, 3.5, 0 },
{ 4.9, 3.0, 0 },
{ 6.7, 3.0, 1 },
{ 6.0, 3.0, 1 },
{ 5.6, 2.5, 1 },
};
// Creating a sample query
Data query = { 5.9, 3.0 };
// Performing KNN with k=3
int prediction = knn(data, query, 3);
// Outputting the prediction
cout << "The prediction for (" << query.feature1 << ", " << query.feature2 << ") is class " << prediction << endl;
return 0;
}
```
这个KNN代码演示了如何使用欧几里得距离度量来计算特征空间中两个样本之间的距离。然后,我们用这个距离度量来找到与查询样本最接近的 k 个训练样本。最后,k-近邻法根据已知类别的邻居并返回最常见的类别作为预测值。这个简单的代码只考虑了两类,可以加以改进来处理更多的类别。