使用sklearn中鸢尾花数据集手写knn算法,得出数据结论
时间: 2023-07-24 12:05:47 浏览: 125
模式识别与机器学习实战 - KNN算法python实现 - 简单入门 -内含数据集和源码
好的,我们可以使用sklearn中的鸢尾花数据集,手动实现KNN算法,并得出数据结论。下面是一个示例代码:
```python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 定义KNN算法类
class KNN:
def __init__(self, n_neighbors=3):
self.n_neighbors = n_neighbors
def fit(self, X, y):
self.X = X
self.y = y
def euclidean_distance(self, x1, x2):
return np.sqrt(np.sum((x1 - x2) ** 2))
def predict(self, X_test):
y_pred = []
for test_sample in X_test:
distances = [self.euclidean_distance(test_sample, x) for x in self.X]
nearest_indices = np.argsort(distances)[:self.n_neighbors]
nearest_labels = self.y[nearest_indices]
unique_labels, counts = np.unique(nearest_labels, return_counts=True)
predicted_label = unique_labels[np.argmax(counts)]
y_pred.append(predicted_label)
return np.array(y_pred)
# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 实例化KNN算法类
knn = KNN(n_neighbors=3)
# 拟合模型
knn.fit(X_train, y_train)
# 预测测试集
y_pred = knn.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)
```
这段代码会将鸢尾花数据集划分为训练集和测试集,然后使用手动实现的KNN算法进行训练和预测。最后,计算预测结果与真实标签之间的准确率。
希望这对你有帮助!
阅读全文