以下是为您生成的代码示例: ```python from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB from sklearn.decomposition import PCA import matplotlib.pyplot as plt # 加载鸢尾花数据集 iris = datasets.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 = KNeighborsClassifier(n_neighbors=5) knn.fit(X_train, y_train) # 朴素贝叶斯分类器 gnb = GaussianNB() gnb.fit(X_train, y_train) # PCA 降维 pca = PCA(n_components=2) X_train_pca = pca.fit_transform(X_train) X_test_pca = pca.transform(X_test) # 绘制分类界面 def plot_classification_boundary(clf, X, y, title): h = 0.02 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.subplot(121) plt.contourf(xx, yy, Z, alpha=0.4) plt.scatter(X[:, 0], X[:, 1], c=y, alpha=0.8) plt.title(title) plt.figure(figsize=(10, 5)) plot_classification_boundary(knn, X_train_pca, y_train, 'KNN Classification Boundary') plot_classification_boundary(gnb, X_train_pca, y_train, 'Naive Bayes Classification Boundary') plt.show() ``` 额外需要注意的逻辑点: 1. 对于 K 值的选择,需要根据实际数据和效果进行调整。 2. 数据预处理步骤可能需要根据数据特点进行优化,比如标准化或归一化。 3. 绘图时的颜色和标记可以根据个人需求和美观进行修改。 [2024-12-08 09:14:25 | AI写代码神器 | 571点数解答]