加入L2
时间: 2023-12-18 20:10:27 浏览: 57
V4L2-struct.rar_v4l2
好的,以下是加入L2正则化的程序示例:
```
import pandas as pd
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import PolynomialFeatures
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_regression
from sklearn.model_selection import train_test_split
# 读取 Excel 文件
data = pd.read_excel('D://数据1.xlsx', sheet_name='000')
# 把数据分成输入和输出
X = data.iloc[:, 0:4].values
y = data.iloc[:, 0:4].values
# 标准化处理
scaler = StandardScaler()
X = scaler.fit_transform(X)
# 添加多项式特征
poly = PolynomialFeatures(degree=2, include_bias=False)
X = poly.fit_transform(X)
# 将数据分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=0)
# 创建岭回归模型, 加入L2正则化
model = Ridge(alpha=0.88, solver='auto', normalize=False, max_iter=1000, tol=0.001, random_state=None,
penalty='l2', # 加入L2正则化
fit_intercept=True)
# 拟合模型
model.fit(X_train, y_train)
# 使用模型进行预测
y_pred = model.predict(X_test)
# 将预测结果四舍五入取整
y_pred = np.round(y_pred)
# 去除重复行
y_pred = np.unique(y_pred, axis=0)
# 打印预测结果
print(y_pred)
```
在创建Ridge模型时,设置penalty参数为'l2'即可加入L2正则化。其他参数的含义可以参考sklearn官方文档。
阅读全文