a) 利用LinearRegression 实现数据拟合与预测; b) 利用Ridge实现数据拟合与预测; c) 利用Lasso实现数据拟合与预测 并提供以上三项的完整python代码
时间: 2023-06-04 22:07:03 浏览: 170
a) 利用LinearRegression 实现数据拟合与预测的python代码:
```
import numpy as np
from sklearn.linear_model import LinearRegression
# 生成数据
X_train = np.random.rand(100, 1)
y_train = 2 * X_train + 1 + 0.2 * np.random.randn(100, 1)
# 构建模型
model = LinearRegression()
# 拟合数据
model.fit(X_train, y_train)
# 预测数据
X_test = np.array([[0.5]])
y_pred = model.predict(X_test)
print("预测结果为:", y_pred)
```
b) 利用Ridge实现数据拟合与预测的python代码:
```
import numpy as np
from sklearn.linear_model import Ridge
# 生成数据
X_train = np.random.rand(100, 1)
y_train = 2 * X_train + 1 + 0.2 * np.random.randn(100, 1)
# 构建模型
model = Ridge(alpha=0.1)
# 拟合数据
model.fit(X_train, y_train)
# 预测数据
X_test = np.array([[0.5]])
y_pred = model.predict(X_test)
print("预测结果为:", y_pred)
```
c) 利用Lasso实现数据拟合与预测的python代码:
```
import numpy as np
from sklearn.linear_model import Lasso
# 生成数据
X_train = np.random.rand(100, 1)
y_train = 2 * X_train + 1 + 0.2 * np.random.randn(100, 1)
# 构建模型
model = Lasso(alpha=0.1)
# 拟合数据
model.fit(X_train, y_train)
# 预测数据
X_test = np.array([[0.5]])
y_pred = model.predict(X_test)
print("预测结果为:", y_pred)
```
阅读全文