使用Adaboost实现Iris分类的代码 使用梯度提升树GBDT实现Boston房价预测的代码
时间: 2024-02-13 17:06:07 浏览: 31
好的,以下是使用 AdaBoost 实现 Iris 分类和使用 GBDT 实现 Boston 房价预测的代码:
使用 AdaBoost 实现 Iris 分类:
```python
from sklearn.datasets import load_iris
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载数据集
iris = load_iris()
X, y = iris.data, iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 构建 AdaBoost 模型
tree = DecisionTreeClassifier(max_depth=1)
adaboost = AdaBoostClassifier(base_estimator=tree, n_estimators=100, learning_rate=0.1)
adaboost.fit(X_train, y_train)
# 预测测试集并计算准确率
y_pred = adaboost.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
使用 GBDT 实现 Boston 房价预测:
```python
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error
# 加载数据集
boston = load_boston()
X, y = boston.data, boston.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 构建 GBDT 模型
gbdt = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42)
gbdt.fit(X_train, y_train)
# 预测测试集并计算均方误差
y_pred = gbdt.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("MSE:", mse)
```
希望这些代码能够对您有所帮助。