7.逻辑回归实践

1.逻辑回归是怎么防止过拟合的?为什么正则化可以防止过拟合?(大家用自己的话介绍下)

逻辑回归是怎么防止过拟合的?

(1)增加样本量,这是万能的方法,适用任何模型。

(2) 如果数据稀疏,使用L1正则,其他情况,用L2要好,可自己尝试。

(3) 通过特征选择,剔除一些不重要的特征,从而降低模型复杂度。

(4) 如果还过拟合,那就看看是否使用了过度复杂的特征构造工程,比如,某两个特征相乘/除/加等方式构造的特征,不要这样做了,保持原特征

(5) 检查业务逻辑,判断特征有效性,是否在用结果预测结果等。

(6)最总要的,逻辑回归特有的防止过拟合方法:进行离散化处理,所有特征都离散化。

为什么正则化可以防止过拟合?
正则化就是在损失函数的后面加上模型复杂度的惩罚项,这样在最小化损失函数的时候需要平衡模型误差和模型的复杂度,以此来减小模型的复杂度,从而防止过拟合。

2.用logiftic回归来进行实践操作,数据不限。

from sklearn.linear_model import LogisticRegression     
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
from sklearn.metrics import classification_report

import numpy as np
import pandas as pd

def logistic():

column = ['数据编号','属性1','属性2','属性3','属性4','属性5','属性6','属性7','属性8','属性9','属性10','类别']
#读取数据
data = pd.read_csv('C:/Users/lenovo/Desktop/breast-cancer-wisconsin.csv',names = column)
#缺失值处理
data = data.replace(to_replace='?',value = np.nan)
data = data.dropna()
#数据分割
x_train, x_test, y_train, y_test = train_test_split(data[column[1:10]], data[column[10]], test_size=0.3)
#进行标准化处理
std = StandardScaler()

x_train = std.fit_transform(x_train)
x_test = std.transform(x_test)

#逻辑回归预测
lg = LogisticRegression()
lg.fit(x_train,y_train)
print(lg.coef_)
lg_predict = lg.predict(x_test)
print('准确率:',lg.score(x_test,y_test))
print('召回率:',classification_report(y_test,lg_predict,labels=[2,4],target_names=['良性','恶性']))
if __name__ =='main':
logistic()

原文地址:https://www.cnblogs.com/huangyixuan/p/12804939.html