基于Sklearn库中的load_linnerud 体能训练数据集线性回归算法和决策树回归算法的详细实现
时间: 2024-03-02 08:50:12 浏览: 97
好的,我来为您解答。
首先,我们需要导入所需的库和数据集:
```python
from sklearn.datasets import load_linnerud
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
X, y = load_linnerud(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
接下来,我们使用Sklearn库中的LinearRegression和DecisionTreeRegressor模型来进行训练和预测。
线性回归模型的代码如下:
```python
# 创建线性回归模型
lin_reg = LinearRegression()
# 训练模型
lin_reg.fit(X_train, y_train)
# 预测测试集数据
y_pred_lin = lin_reg.predict(X_test)
```
决策树回归模型的代码如下:
```python
# 创建决策树回归模型
tree_reg = DecisionTreeRegressor()
# 训练模型
tree_reg.fit(X_train, y_train)
# 预测测试集数据
y_pred_tree = tree_reg.predict(X_test)
```
最后,我们可以使用Sklearn库中的r2_score函数来评估模型的性能:
```python
from sklearn.metrics import r2_score
# 评估线性回归模型性能
lin_reg_score = r2_score(y_test, y_pred_lin)
print("Linear Regression R2 score:", lin_reg_score)
# 评估决策树回归模型性能
tree_reg_score = r2_score(y_test, y_pred_tree)
print("Decision Tree Regression R2 score:", tree_reg_score)
```
完整的代码如下:
```python
from sklearn.datasets import load_linnerud
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import r2_score
# 加载数据集
X, y = load_linnerud(return_X_y=True)
# 创建训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 创建线性回归模型
lin_reg = LinearRegression()
# 训练模型
lin_reg.fit(X_train, y_train)
# 预测测试集数据
y_pred_lin = lin_reg.predict(X_test)
# 创建决策树回归模型
tree_reg = DecisionTreeRegressor()
# 训练模型
tree_reg.fit(X_train, y_train)
# 预测测试集数据
y_pred_tree = tree_reg.predict(X_test)
# 评估线性回归模型性能
lin_reg_score = r2_score(y_test, y_pred_lin)
print("Linear Regression R2 score:", lin_reg_score)
# 评估决策树回归模型性能
tree_reg_score = r2_score(y_test, y_pred_tree)
print("Decision Tree Regression R2 score:", tree_reg_score)
```
希望能够帮助到您。
阅读全文