knn算法对鸢尾花进行分类,用欧氏距离计算的python代码
时间: 2023-07-05 09:21:35 浏览: 107
KNN算法对鸢尾花进行分类
好的,以下是KNN算法对鸢尾花进行分类,使用欧氏距离计算的Python代码:
首先,导入必要的库:
```python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
```
接着,载入鸢尾花数据集:
```python
iris = load_iris()
X = iris.data
y = iris.target
```
将数据集分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
定义欧氏距离计算函数:
```python
def euclidean_distance(x1, x2):
return np.sqrt(np.sum((x1 - x2)**2))
```
定义KNN分类器:
```python
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 = [self._predict(x) for x in X]
return np.array(y_pred)
def _predict(self, x):
distances = [euclidean_distance(x, x_train) for x_train in self.X_train]
k_indices = np.argsort(distances)[:self.k]
k_nearest_labels = [self.y_train[i] for i in k_indices]
most_common = Counter(k_nearest_labels).most_common(1)
return most_common[0][0]
```
最后,训练模型并进行预测:
```python
knn = KNN(k=3)
knn.fit(X_train, y_train)
predictions = knn.predict(X_test)
```
完整代码如下:
```python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from collections import Counter
def euclidean_distance(x1, x2):
return np.sqrt(np.sum((x1 - x2)**2))
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 = [self._predict(x) for x in X]
return np.array(y_pred)
def _predict(self, x):
distances = [euclidean_distance(x, x_train) for x_train in self.X_train]
k_indices = np.argsort(distances)[:self.k]
k_nearest_labels = [self.y_train[i] for i in k_indices]
most_common = Counter(k_nearest_labels).most_common(1)
return most_common[0][0]
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(k=3)
knn.fit(X_train, y_train)
predictions = knn.predict(X_test)
print(predictions)
```
希望对你有所帮助!
阅读全文