利用iris数据集进行原理代码的验证并且可视化显示
时间: 2024-06-06 12:11:27 浏览: 103
以下是利用iris数据集进行原理代码的验证并且可视化显示的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
# 加载iris数据集
iris = load_iris()
X = iris.data
y = iris.target
# 将数据集划分为训练集和测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
# 定义KNN分类器
class KNN_classifier():
def __init__(self, k=3):
self.k = k
def euclidean_distance(self, x1, x2):
return np.sqrt(np.sum((x1-x2)**2))
def predict(self, X_train, y_train, x_test):
distances = []
for i in range(len(X_train)):
dist = self.euclidean_distance(X_train[i], x_test)
distances.append((dist, y_train[i]))
distances = sorted(distances)
topk = distances[:self.k]
labels = [i[1] for i in topk]
prediction = max(set(labels), key=labels.count)
return prediction
# 训练模型
knn = KNN_classifier(k=3)
y_pred = []
for i in range(len(X_test)):
y_pred.append(knn.predict(X_train, y_train, X_test[i]))
# 计算模型准确率
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, y_pred)
print("模型准确率:", accuracy)
# 可视化结果
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111)
ax.scatter(X_test[:, 0], X_test[:, 1], c=y_pred, cmap='viridis')
ax.set_xlabel('Sepal length')
ax.set_ylabel('Sepal width')
ax.set_title('KNN分类器结果')
plt.show()
```
运行以上代码可以得到如下的可视化结果:
![KNN分类器结果](https://i.imgur.com/2qV8bZL.png)
从图中可以看出,在Sepal length和Sepal width这两个特征下,KNN分类器对iris数据集进行了分类,不同颜色的点代表不同的类别。
阅读全文