knn算法c++代码实现
时间: 2024-03-15 20:29:10 浏览: 74
Knn.rar_KNN C++实现
很高兴回答您的问题。KNN算法是一种常见的分类算法,其代码实现可以使用不同的编程语言来完成。以下是一个C语言实现的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
int class; // 样本的类别
double *values; // 样本的属性值
} Sample;
// 计算两个样本之间的欧几里得距离
double calcDistance(const Sample *a, const Sample *b, int numAttributes) {
double distance = 0;
int i;
for (i = 0; i < numAttributes; i++) {
double diff = a->values[i] - b->values[i];
distance += diff * diff;
}
return sqrt(distance);
}
// 找到k个距离最近的样本,并返回这些样本的类别众数
int classify(const Sample *samples, const Sample *target, int numSamples, int numAttributes, int k) {
int i, j;
// 构建一个数组,存储每个样本距离目标样本的距离
double *distances = (double *)malloc(numSamples * sizeof(double));
for (i = 0; i < numSamples; i++) {
distances[i] = calcDistance(&samples[i], target, numAttributes);
}
// 找到距离最近的k个样本,并统计它们的类别
int *votes = (int *)calloc(numSamples, sizeof(int));
for (i = 0; i < k; i++) {
double minDistance = INFINITY;
int minIndex = -1;
for (j = 0; j < numSamples; j++) {
if (distances[j] < minDistance && votes[j] == 0) {
minDistance = distances[j];
minIndex = j;
}
}
votes[minIndex] = 1;
}
int maxVotes = 0;
int maxClass = 0;
for (i = 0; i < numSamples; i++) {
if (votes[i] > 0) {
int count = 0;
for (j = 0; j < numSamples; j++) {
if (votes[j] > 0 && samples[j].class == samples[i].class) {
count++;
}
}
if (count > maxVotes) {
maxVotes = count;
maxClass = samples[i].class;
}
}
}
free(distances);
free(votes);
return maxClass;
}
int main() {
// 假设我们有5个样本,每个样本有3个属性,并且有两个类别
Sample samples[] = {
{1, (double[]){1.0, 2.0, 3.0}},
{2, (double[]){4.0, 5.0, 6.0}},
{1, (double[]){7.0, 8.0, 9.0}},
{2, (double[]){10.0, 11.0, 12.0}},
{1, (double[]){13.0, 14.0, 15.0}},
};
// 假设我们要分类一个新的样本
Sample target = {0, (double[]){4.5, 6.5, 8.5}};
// 使用k=3的KNN算法进行分类
int predictedClass = classify(samples, &target, 5, 3, 3);
printf("Predicted class: %d\n", predictedClass);
return 0;
}
希望这个代码能够对您有所帮助!如果您对KNN算法还有其他问题,请继续提问。
阅读全文