KNN=KNearestNeighbor() KNN.train(X_train, y_train) y_pred = KNN.predict(X_test, k=6) accuracy = np.mean(y_pred == y_test) print('测试集预测准确率:%f' % accuracy) plt.scatter(X_setosa_train[:, 0], X_setosa_train[:, 2], color='red', marker='o', label='setosa_train') plt.scatter(X_versicolor_train[:, 0], X_versicolor_train[:, 2], color='blue', marker='^', label='versicolor_train') plt.scatter(X_virginica_train[:, 0], X_virginica_train[:, 2], color='green', marker='s', label='virginica_train') plt.scatter(X_setosa_test[:, 0], X_setosa_test[:, 2], color='y', marker='o', label='setosa_test') plt.scatter(X_versicolor_test[:, 0], X_versicolor_test[:, 2], color='y', marker='^', label='versicolor_test') plt.scatter(X_virginica_test[:, 0], X_virginica_test[:, 2], color='y', marker='s', label='virginica_test') plt.xlabel('sepal length') plt.ylabel('petal length') plt.legend(loc = 4) plt.show()注释每一行代码
时间: 2023-11-28 09:50:01 浏览: 93
以下是对每一行代码的注释:
```python
# 初始化 KNN 模型
KNN = KNearestNeighbor()
# 使用训练集数据进行模型训练
KNN.train(X_train, y_train)
# 使用测试集数据进行预测,并指定 k=6
y_pred = KNN.predict(X_test, k=6)
# 计算模型的准确率
accuracy = np.mean(y_pred == y_test)
# 绘制散点图,展示不同种类的花的数据分布
plt.scatter(X_setosa_train[:, 0], X_setosa_train[:, 2], color='red', marker='o', label='setosa_train')
plt.scatter(X_versicolor_train[:, 0], X_versicolor_train[:, 2], color='blue', marker='^', label='versicolor_train')
plt.scatter(X_virginica_train[:, 0], X_virginica_train[:, 2], color='green', marker='s', label='virginica_train')
plt.scatter(X_setosa_test[:, 0], X_setosa_test[:, 2], color='y', marker='o', label='setosa_test')
plt.scatter(X_versicolor_test[:, 0], X_versicolor_test[:, 2], color='y', marker='^', label='versicolor_test')
plt.scatter(X_virginica_test[:, 0], X_virginica_test[:, 2], color='y', marker='s', label='virginica_test')
# 设置 x 轴和 y 轴的标签
plt.xlabel('sepal length')
plt.ylabel('petal length')
# 显示图例,并设置其位置
plt.legend(loc = 4)
# 显示图形
plt.show()
```
阅读全文