把上述代码整合到一起
时间: 2024-10-16 08:19:20 浏览: 18
C#合并多个结果集实例源代码
当然可以,下面是将上述步骤整合到一起的完整代码示例,包括数据生成、划分、KNN模型构建、预测和评估,以及基本的可视化:
```python
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import numpy as np
# 生成二维随机数据
data = make_blobs(n_samples=200, centers=2, random_state=8)
x, y = data # x是样本数据,y是对应的标签
# 划分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
# 构建KNN分类器,这里假设n_neighbors=3
knn = KNeighborsClassifier(n_neighbors=3)
# 训练模型
knn.fit(x_train, y_train)
# 对测试集进行预测
predictions = knn.predict(x_test)
# 计算模型的准确率
accuracy = knn.score(x_test, y_test)
print(f"模型评估:{accuracy:.2f}")
# 将预测结果绘制在散点图上
plt.figure(figsize=(8, 6))
plt.scatter(x[:, 0], x[:, 1], c=y, cmap='viridis', label='Original Data')
plt.scatter(x_test[:, 0], x_test[:, 1], c=predictions, cmap='viridis', label='Predicted Class')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.legend()
plt.title("KNN Classification Results")
plt.show()
# 打印单个测试样本的预测结果
print(f"预测单个测试样本:{x_test[0]} -> {predictions[0]}")
#
阅读全文