使用sklearn自带的岭回归和Lasso回归对波士顿房价数据集进行回归预测
时间: 2023-11-24 22:05:29 浏览: 299
机器学习实战案例-基于回归算法(Lasso、Ridge)对波士顿房屋租赁价格进行预测
好的,我可以为您提供一个简单的代码示例。
首先,我们需要导入波士顿房价数据集和所需的库:
```python
from sklearn.datasets import load_boston
from sklearn.linear_model import Ridge, Lasso
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
```
接着,我们可以加载波士顿房价数据集:
```python
boston = load_boston()
X = boston.data
y = boston.target
```
然后,我们将数据集拆分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
现在我们可以使用岭回归和Lasso回归来训练模型并进行预测:
```python
# 岭回归
ridge = Ridge(alpha=0.1)
ridge.fit(X_train, y_train)
ridge_pred = ridge.predict(X_test)
# Lasso回归
lasso = Lasso(alpha=0.1)
lasso.fit(X_train, y_train)
lasso_pred = lasso.predict(X_test)
```
最后,我们可以计算均方根误差(RMSE)来评估模型的性能:
```python
print("Ridge regression RMSE: ", mean_squared_error(y_test, ridge_pred, squared=False))
print("Lasso regression RMSE: ", mean_squared_error(y_test, lasso_pred, squared=False))
```
完整代码如下:
```python
from sklearn.datasets import load_boston
from sklearn.linear_model import Ridge, Lasso
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
boston = load_boston()
X = boston.data
y = boston.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
ridge = Ridge(alpha=0.1)
ridge.fit(X_train, y_train)
ridge_pred = ridge.predict(X_test)
lasso = Lasso(alpha=0.1)
lasso.fit(X_train, y_train)
lasso_pred = lasso.predict(X_test)
print("Ridge regression RMSE: ", mean_squared_error(y_test, ridge_pred, squared=False))
print("Lasso regression RMSE: ", mean_squared_error(y_test, lasso_pred, squared=False))
```
希望这可以帮助您开始使用岭回归和Lasso回归预测波士顿房价数据集。
阅读全文