c++实现KNN算法
时间: 2024-01-12 15:21:20 浏览: 81
使用C++来实现KNN算法
5星 · 资源好评率100%
以下是使用C++实现KNN算法的示例代码:
```cpp
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
// 定义数据点结构体
struct DataPoint {
std::vector<double> features;
int label;
};
// 计算欧式距离
double calculateDistance(const std::vector<double>& point1, const std::vector<double>& point2) {
double distance = 0.0;
for (int i = 0; i < point1.size(); i++) {
distance += pow(point1[i] - point2[i], 2);
}
return sqrt(distance);
}
// KNN算法
int knn(const std::vector<DataPoint>& trainingData, const std::vector<double>& testPoint, int k) {
// 计算测试点与所有训练点的距离
std::vector<std::pair<double, int>> distances;
for (const auto& dataPoint : trainingData) {
double distance = calculateDistance(dataPoint.features, testPoint);
distances.push_back(std::make_pair(distance, dataPoint.label));
}
// 根据距离排序
std::sort(distances.begin(), distances.end());
// 统计前k个最近邻的标签
std::vector<int> labels(10, 0);
for (int i = 0; i < k; i++) {
labels[distances[i].second]++;
}
// 找到出现次数最多的标签
int maxCount = 0;
int maxLabel = -1;
for (int i = 0; i < labels.size(); i++) {
if (labels[i] > maxCount) {
maxCount = labels[i];
maxLabel = i;
}
}
return maxLabel;
}
int main() {
// 训练数据
std::vector<DataPoint> trainingData = {
{{1.0, 2.0}, 0},
{{2.0, 1.0}, 0},
{{4.0, 5.0}, 1},
{{5.0, 4.0}, 1}
};
// 测试数据
std::vector<double> testPoint = {3.0, 3.0};
// 设置k值
int k = 3;
// 进行KNN分类
int predictedLabel = knn(trainingData, testPoint, k);
// 输出预测结果
std::cout << "Predicted label: " << predictedLabel << std::endl;
return 0;
}
```
阅读全文