生成利用KNN算法对数据集进行二分类的代码
时间: 2023-07-05 12:06:59 浏览: 175
利用KNN对数据进行分类
首先需要导入必要的库:
``` python
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
```
然后,我们可以准备数据集。这里我们使用 sklearn 自带的 iris 数据集。
``` python
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
```
接下来,我们将数据集分成训练集和测试集。我们将训练集占总数据集的 80%,测试集占 20%。
``` python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
接下来,我们需要创建一个 KNN 分类器,并对训练集进行拟合。
``` python
k = 3
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train, y_train)
```
现在,我们已经训练好了我们的分类器,可以使用测试集进行预测并计算准确率。
``` python
y_pred = knn.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
```
完整代码如下:
``` python
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.datasets import load_iris
iris = 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)
k = 3
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
```
阅读全文