import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier # 加载鸢尾花数据集 iris = load_iris() X = iris.data[:, :2] # 只使用前两个特征 y = iris.target # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3, random_state=42) # 训练KNN模型 knn = KNeighborsClassifier(n_neighbors=5) knn.fit(X_train, y_train) # 可视化训练集和测试集 plt.figure(figsize=(10, 6)) plt.scatter(X_train[:, ], X_train[:, 1], c=y_train, cmap='viridis', label='Train') plt.scatter(X_test[:, ], X_test[:, 1], c=y_test, cmap='viridis', marker='x', label='Test') plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.legend() plt.show() # 可视化KNN分类结果 plt.figure(figsize=(10, 6)) h = .02 # 网格步长 x_min, x_max = X[:, ].min() - .5, X[:, ].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.contourf(xx, yy, Z, cmap='viridis', alpha=.5) plt.scatter(X_train[:, ], X_train[:, 1], c=y_train, cmap='viridis', label='Train') plt.scatter(X_test[:, ], X_test[:, 1], c=y_test, cmap='viridis', marker='x', label='Test') plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.legend() plt.show()帮我检查改正这段代码