gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
人工智能算法代码例子
- User
人工智能算法代码例子
- Assistant
这是一个简单的Python代码示例,实现了K-最近邻(K-Nearest Neighbors,KNN)算法,它是一种使用于分类和回归的机器学习算法。按Python代码编写规范,使用
sklearn库完成对鸢尾花数据集(Iris dataset)的分类。首先,请确保已经安装了
scikit-learn,numpy,和matplotlib库。你可以使用以下命令进行安装:pip install scikit-learn numpy matplotlib这是KNN算法实现的一个简单示例代码:
import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap # 加载iris数据集 iris = load_iris() # 提取数据集中的特征和类别 X, y = iris.data[:, :2], iris.target # 划分数据集(80%训练集,20%测试集) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 数据预处理:特征缩放 scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) # KNN分类器 k = 5 classifier = KNeighborsClassifier(n_neighbors=k) classifier.fit(X_train, y_train) # 对测试集做预测 y_pred = classifier.predict(X_test) # 计算预测精度 accuracy = accuracy_score(y_test, y_pred) print("KNN accuracy: {:.2f}%".format(accuracy * 100)) # 可视化 # Set up color map cmap_light = ListedColormap(['orange', 'cyan', 'cornflowerblue']) cmap_bold = ['darkorange', 'c', 'darkblue'] h = .02 # step size in the mesh # Create color mesh x_min, x_max = X_test[:, 0].min() - 1, X_test[:, 0].max() + 1 y_min, y_max = X_test[:, 1].min() - 1, X_test[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = classifier.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.figure() plt.pcolormesh(xx, yy, Z, cmap=cmap_light) # Plot test data for i, color in zip(range(iris.target_names.shape[0]), cmap_bold): idx = np.where(y_test == i) plt.scatter(X_test[idx, 0], X_test[idx, 1], c=color, label=iris.target_names[i]) plt.legend() plt.show()在这个例子中,我们首先加载了鸢尾花(Iris)数据集,并针对数据集中的两个特征进行分类。我们将数据集划分为训练集和测试集。然后使用K-最近邻分类器进行分类,并计算预测精度。最后,绘制了分类边界和测试集数据。