使用knn模型对sklearn 鸢尾花 数据集进行分类。
时间: 2023-12-29 22:03:19 浏览: 60
好的,下面是对sklearn鸢尾花数据集使用KNN模型进行分类的代码:
```python
# 导入需要的库
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
# 加载数据集
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.3, random_state=42)
# 创建KNN模型并训练
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
# 预测测试集并计算准确率
y_pred = knn.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
结果输出:
```
Accuracy: 1.0
```
说明使用KNN模型对该数据集进行分类时,可以达到100%的准确率。
相关问题
使用knn模型对sklearn 鸢尾花 数据集进行分类
好的,下面是使用knn模型对sklearn鸢尾花数据集进行分类的Python代码:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
# 加载数据集
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)
# 创建knn模型,k=3
knn = KNeighborsClassifier(n_neighbors=3)
# 训练模型
knn.fit(X_train, y_train)
# 预测测试集
y_pred = knn.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
输出结果:
```
Accuracy: 1.0
```
可以看到,使用knn模型对sklearn鸢尾花数据集进行分类,准确率达到了100%。
使用knn模型对sklearn 鸢尾花 数据集进行分类,并给出代码
好的,下面是使用KNN模型对鸢尾花数据集进行分类的代码:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
# 加载鸢尾花数据集
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.3, random_state=42)
# 创建KNN模型,设置k值为3
knn = KNeighborsClassifier(n_neighbors=3)
# 在训练集上拟合KNN模型
knn.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = knn.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
```
输出结果为:
```
Accuracy: 97.78%
```
阅读全文