岭回归与lasoo回归python实现的全代码
时间: 2023-11-15 11:05:59 浏览: 150
当然可以!下面是岭回归(Ridge Regression)和Lasso回归(Lasso Regression)的Python实现代码:
岭回归:
```python
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import numpy as np
# 生成示例数据
np.random.seed(0)
X = np.random.rand(100, 10)
y = np.random.rand(100)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 创建岭回归模型
ridge = Ridge(alpha=1.0)
# 拟合模型
ridge.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = ridge.predict(X_test)
# 计算均方误差
mse = mean_squared_error(y_test, y_pred)
print("均方误差:", mse)
```
Lasso回归:
```python
from sklearn.linear_model import Lasso
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import numpy as np
# 生成示例数据
np.random.seed(0)
X = np.random.rand(100, 10)
y = np.random.rand(100)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 创建Lasso回归模型
lasso = Lasso(alpha=1.0)
# 拟合模型
lasso.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = lasso.predict(X_test)
# 计算均方误差
mse = mean_squared_error(y_test, y_pred)
print("均方误差:", mse)
```
以上是岭回归和Lasso回归的Python实现代码。你可以根据实际情况,修改数据和超参数,运行代码进行训练和预测。希望对你有帮助!
阅读全文