基于鸢尾花数据集和波斯顿房价的cart分类回归算法Python代码
时间: 2024-01-23 16:04:08 浏览: 82
以下是基于鸢尾花数据集和波斯顿房价的 CART 分类回归算法的 Python 代码:
### 使用 sklearn 库加载数据集
```python
from sklearn.datasets import load_iris, load_boston
iris_data = load_iris()
boston_data = load_boston()
```
### 使用 CART 分类算法对鸢尾花数据集进行分类
```python
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(iris_data.data, iris_data.target, test_size=0.2, random_state=42)
clf = DecisionTreeClassifier(random_state=42)
clf.fit(X_train, y_train)
score = clf.score(X_test, y_test)
print("Accuracy: {:.2f}%".format(score*100))
```
### 使用 CART 回归算法对波士顿房价进行回归预测
```python
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
X_train, X_test, y_train, y_test = train_test_split(boston_data.data, boston_data.target, test_size=0.2, random_state=42)
reg = DecisionTreeRegressor(random_state=42)
reg.fit(X_train, y_train)
y_pred = reg.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("MSE: {:.2f}".format(mse))
```
阅读全文