knn算法c++代码实现
时间: 2024-03-15 19:17:23 浏览: 77
很高兴帮助您!以下是KNN算法C代码实现的示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define K 3
float distance(int x1[], int x2[], int n) {
float d = 0;
for (int i = 0; i < n; i++) {
d += pow(x1[i] - x2[i], 2);
}
return sqrt(d);
}
void knn(int train[][2], int test[], int labels[], int nTrain) {
float distances[nTrain];
int indices[nTrain];
for (int i = 0; i < nTrain; i++) {
distances[i] = distance(train[i], test, 2);
indices[i] = i;
}
for (int i = 0; i < K; i++) {
int minIndex = i;
for (int j = i + 1; j < nTrain; j++) {
if (distances[j] < distances[minIndex]) {
minIndex = j;
}
}
float tmpDist = distances[i];
distances[i] = distances[minIndex];
distances[minIndex] = tmpDist;
int tmpIndex = indices[i];
indices[i] = indices[minIndex];
indices[minIndex] = tmpIndex;
}
int counts[K] = {0};
for (int i = 0; i < K; i++) {
counts[labels[indices[i]]]++;
}
int maxLabel = 0;
int maxCount = 0;
for (int i = 0; i < K; i++) {
if (counts[i] > maxCount) {
maxCount = counts[i];
maxLabel = i;
}
}
printf("The predicted label is %d.\n", maxLabel);
}
int main() {
int train[][2] = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}, {8, 8}, {9, 9}, {10, 10}};
int test[] = {6, 7};
int labels[] = {1, 1, 1, 2, 2, 2, 3, 3, 3, 3};
int nTrain = sizeof(train) / sizeof(train[0]);
knn(train, test, labels, nTrain);
return 0;
}
```
此代码实现了一个简单的KNN分类器,用于根据训练集中的样本数据对测试数据进行分类。在这个例子中,训练集包含10个2维坐标点,每个点都有一个标签,标签为1、2或3。测试数据是坐标为(6, 7)的点,程序将其归为一个标签。
请注意,这只是一个简单的示例程序,并不能处理大规模数据或更复杂的情况。
阅读全文