python划分鸢尾花数据集搭建决策树
时间: 2023-10-15 15:04:33 浏览: 97
好的,以下是Python代码实现:
首先,我们需要导入所需的库:
```python
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
```
接着,我们可以加载鸢尾花数据集:
```python
iris = load_iris()
```
然后,我们将数据集转换成pandas的DataFrame格式,以便更好地进行数据处理:
```python
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df['target'] = iris.target
```
接着,我们可以使用train_test_split()函数将数据集分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(df[iris.feature_names], df['target'], random_state=0)
```
现在,我们可以使用sklearn中的DecisionTreeClassifier类来训练决策树模型,并使用训练集进行拟合:
```python
dtc = DecisionTreeClassifier(random_state=0)
dtc.fit(X_train, y_train)
```
最后,我们可以使用测试集来评估模型的性能:
```python
y_pred = dtc.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
```
完整代码如下:
```python
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df['target'] = iris.target
X_train, X_test, y_train, y_test = train_test_split(df[iris.feature_names], df['target'], random_state=0)
dtc = DecisionTreeClassifier(random_state=0)
dtc.fit(X_train, y_train)
y_pred = dtc.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
```
希望这可以帮助到你!
阅读全文