k最近邻分类算法实现代码
时间: 2023-07-05 12:08:10 浏览: 57
下面是一个简单的k最近邻分类算法实现的代码示例:
```python
import numpy as np
class KNN:
def __init__(self, k=3):
self.k = k
def fit(self, X, y):
self.X_train = X
self.y_train = y
def predict(self, X):
y_pred = []
for x in X:
distances = np.sqrt(np.sum((self.X_train - x) ** 2, axis=1))
nearest_neighbors = np.argsort(distances)[:self.k]
nearest_labels = self.y_train[nearest_neighbors]
y_pred.append(np.bincount(nearest_labels).argmax())
return np.array(y_pred)
```
其中, `fit` 方法用于训练模型, `predict` 方法用于预测新的数据。该实现使用欧氏距离作为距离度量,并且采用简单的多数表决法进行分类。
相关问题
用C语言写出k最近邻分类算法实现代码
以下是用C语言实现k最近邻分类算法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
double x;
double y;
int label;
} Point;
int main() {
int k, n;
printf("Enter the value of k: ");
scanf("%d", &k);
printf("Enter the number of points: ");
scanf("%d", &n);
Point* points = (Point*) malloc(n * sizeof(Point));
printf("Enter the coordinates and label of each point:\n");
for (int i = 0; i < n; i++) {
scanf("%lf %lf %d", &points[i].x, &points[i].y, &points[i].label);
}
// Classify new points
int q;
printf("Enter the number of new points to classify: ");
scanf("%d", &q);
printf("Enter the coordinates of each new point:\n");
for (int i = 0; i < q; i++) {
double x, y;
printf("Point %d: ", i+1);
scanf("%lf %lf", &x, &y);
// Compute distance between new point and all points in dataset
double distances[n];
for (int j = 0; j < n; j++) {
double dx = x - points[j].x;
double dy = y - points[j].y;
distances[j] = sqrt(dx*dx + dy*dy);
}
// Find k nearest points
int indices[n];
for (int j = 0; j < n; j++) {
indices[j] = j;
}
for (int j = 0; j < k; j++) {
int min_index = j;
for (int l = j+1; l < n; l++) {
if (distances[l] < distances[min_index]) {
min_index = l;
}
}
double temp_dist = distances[j];
distances[j] = distances[min_index];
distances[min_index] = temp_dist;
int temp_index = indices[j];
indices[j] = indices[min_index];
indices[min_index] = temp_index;
}
// Classify new point by majority vote of k nearest points
int label_counts[3] = {0, 0, 0};
for (int j = 0; j < k; j++) {
int label = points[indices[j]].label;
label_counts[label-1]++;
}
int max_count = 0;
int max_label = 1;
for (int j = 0; j < 3; j++) {
if (label_counts[j] > max_count) {
max_count = label_counts[j];
max_label = j+1;
}
}
printf("Classified as label %d\n", max_label);
}
free(points);
return 0;
}
```
这里实现了一个简单的k最近邻分类器,可以处理二维空间中的点,并将它们分为三个类别。用户可以输入要分类的新点的坐标,并得到它所属的类别。注意,这里假设数据集中有且仅有三个类别,因此在实际应用中可能需要根据具体情况作出调整。
K最近邻算法多分类算法
K最近邻(K-Nearest Neighbors,KNN)算法是一种常用的多分类算法。它基于样本之间的距离来进行分类,具体操作如下:
1. 计算距离:对于测试样本,计算它与训练集中每个样本的距离。常见的距离度量方法有欧氏距离、曼哈顿距离等。
2. 选择K个最近邻:根据距离,选择与测试样本最近的K个训练样本。
3. 进行投票或求平均:根据K个最近邻样本的标签,进行投票决策或求平均值,得到测试样本的分类结果。
以下是一个使用K最近邻算法进行多分类的Python代码示例:
```python
from sklearn.neighbors import KNeighborsClassifier
import pandas as pd
from sklearn.model_selection import train_test_split
# 读取数据集
data = pd.read_csv('final_data1.csv')
Y = data.y
X = data.drop('y', axis=1)
# 数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
# 创建并训练KNN分类器
knn = KNeighborsClassifier(n_neighbors=3) # 设置K值为3
knn.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = knn.predict(X_test)
```
上述代码使用了`sklearn`库中的`neighbors`模块,通过导入`KNeighborsClassifier`创建了一个K最近邻分类器对象`knn`。在创建分类器对象时,通过参数`n_neighbors`设置了K的值为3。然后使用训练集数据`X_train`和对应的标签`y_train`调用`knn.fit()`方法进行训练。最后,使用训练好的模型在测试集数据`X_test`上进行预测,预测结果存储在`y_pred`中。
需要注意的是,KNN算法的性能很大程度上依赖于选择合适的K值和距离度量方法。在实际应用中,可以使用交叉验证等方法来选择最佳的K值,并根据数据集的特点选择合适的距离度量方法。