使用knn模型对sklearn 鸢尾花 数据集进行分类,并给出代码
时间: 2023-12-29 19:02:29 浏览: 85
好的,下面是使用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%
```
相关问题
使用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模型对sklearn鸢尾花数据集进行分类的示例代码:
```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_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, 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)
# 计算准确率
acc = accuracy_score(y_test, y_pred)
print('Accuracy:', acc)
```
输出结果为:
```
Accuracy: 1.0
```
说明使用knn模型对鸢尾花数据集进行分类有很好的效果。
阅读全文