鸢尾花多分类python代码
时间: 2023-09-29 14:08:29 浏览: 96
以下是使用Scikit-learn库进行鸢尾花多分类的Python代码:
```
# 导入所需的库
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
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)
# 创建决策树分类器
clf = DecisionTreeClassifier()
# 在训练集上训练分类器
clf.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = clf.predict(X_test)
# 计算准确率
acc = accuracy_score(y_test, y_pred)
# 打印准确率
print("准确率:", acc)
```
这段代码将鸢尾花数据集分为训练集和测试集,使用决策树分类器进行训练,然后在测试集上进行预测并计算准确率。
相关问题
鸢尾花识别分类python代码
以下是使用Python实现的鸢尾花分类代码:
```python
# 导入必要的库
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
# 加载数据集
iris = load_iris()
# 将特征和标签分别存储在X和y中
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)
# 创建决策树分类器
clf = DecisionTreeClassifier()
# 使用训练数据拟合分类器
clf.fit(X_train, y_train)
# 使用测试数据对分类器进行评估
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
该代码使用决策树算法对鸢尾花数据集进行分类,将数据集分成训练集和测试集,并在测试集上评估分类器的准确性。
多层感知机鸢尾花分类python代码
好的,以下是多层感知机鸢尾花分类的 Python 代码:
```python
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.neural_network import MLPClassifier
# 加载数据集
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=0)
# 数据标准化
sc = StandardScaler()
sc.fit(X_train)
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)
# 多层感知机模型训练
mlp = MLPClassifier(hidden_layer_sizes=(10,), max_iter=1000)
mlp.fit(X_train_std, y_train)
# 模型评估
print('训练集准确率:', mlp.score(X_train_std, y_train))
print('测试集准确率:', mlp.score(X_test_std, y_test))
```
阅读全文