基于KNN算法的Iris数据集分类的代码实现
时间: 2023-10-05 20:13:00 浏览: 135
您好!以下是基于KNN算法的Iris数据集分类的代码实现:
```python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
def euclidean_distance(a, b):
return np.linalg.norm(a - b)
class KNNClassifier:
def __init__(self, k=5):
self.k = k
self.X_train = None
self.y_train = None
def fit(self, X_train, y_train):
self.X_train = X_train
self.y_train = y_train
def predict(self, X_test):
y_pred = []
for i in range(X_test.shape[0]):
distance = []
for j in range(self.X_train.shape[0]):
dist = euclidean_distance(X_test[i], self.X_train[j])
distance.append((dist, self.y_train[j]))
distance.sort()
top_k = [x[1] for x in distance[:self.k]]
counts = np.bincount(top_k)
y_pred.append(np.argmax(counts))
return y_pred
iris = load_iris()
X, y = shuffle(iris.data, iris.target, random_state=13)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=13)
knn = KNNClassifier()
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print("Accuracy:", acc)
```
希望对您有所帮助!如果您有其它问题,可以继续提问。祝您生活愉快!
阅读全文