1、概述
逻辑回归本身是一种分类算法,它并不涉及下采样或过采样操作。然而,在处理不平衡数据集时,这些技术经常被用来改善模型的性能。下采样和过采样是两种常用的处理不平衡数据集的方法。
2、下采样
1、概念
下采样是通过减少数量较多的类别(多数类)的样本数量,使其与数量较少的类别(少数类)的样本数量相匹配或接近。这样可以使模型在训练时不会偏向于多数类。
2、原理
随机选择一些多数类的样本并从数据集中移除,只保留与少数类样本数量相等的样本。可以导致数据集的信息丢失,特别是当多数类样本被大量移除时。
3、案例
从0中找到和1的数目相同的数据
代码
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
data=pd.read_csv("creditcard.csv")
#StandardScaler用于数据标准化
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
# 对"Amount"列进行标准化处理
data["Amount"]=scaler.fit_transform(data[["Amount"]])
data=data.drop(["Time"],axis=1)
#从完整数据集中找到和n_eg数目相同的p_eg进行lianj
p_eg=data[data["Class"]==0]
n_eg=data[data["Class"]==1]
np.random.seed(seed=4)
p_eg=p_eg.sample(len(n_eg))
data_c=pd.concat([p_eg,n_eg])
from sklearn.model_selection import train_test_split
x=data.drop("Class",axis=1)
y=data["Class"]
# 随机分割训练集和测试集
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=0)
#小数据集的训练集特征与标签,测试集特征与标签
m=data_c.drop("Class",axis=1)
n=data_c["Class"]
m_train,m_test,n_train,n_test=train_test_split(m,n,test_size=0.2,random_state=0)
#交叉验证小数据集
from sklearn.model_selection import cross_val_score
scores=[]
c_param_range=[0.01,0.1,1,10,100]
for i in c_param_range:
lr=LogisticRegression(C=i,penalty='l2',solver='lbfgs',max_iter=1000)
score=cross_val_score(lr,m_train,n_train,cv=8,scoring='recall')
score_mean=sum(score)/len(score)
scores.append(score_mean)
#选择最合适的C重新训练
best_c=c_param_range[np.argmax(scores)]
lr=LogisticRegression(C=best_c,penalty='l2',max_iter=1000)
lr.fit(m_train,n_train)
from sklearn import metrics
#小数据集的训练集
train_predicted=lr.predict(m_train)
print(metrics.classification_report(n_train,train_predicted))
#小数据集的测试集
test_predicted=lr.predict(m_test)
print(metrics.classification_report(n_test,test_predicted))
#完整数据集的训练集
data_x_train_predicted=lr.predict(x_train)
print(metrics.classification_report(y_train,data_x_train_predicted))
#完整数据集的测试集
data_x_test_predicted=lr.predict(x_test)
print(metrics.classification_report(y_test,data_x_test_predicted))
thresh=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
recalls=[]
for i in thresh:
y_predict_proba=lr.predict_proba(x_test)
y_predict_proba=pd.DataFrame(y_predict_proba).drop([0],axis=1)
y_predict_proba[y_predict_proba[[1]]>i]=1
y_predict_proba[y_predict_proba[[1]]<=i]=0
recall=metrics.recall_score(y_test,y_predict_proba[1])
recalls.append(recall)
print(i,recall)
4、过采样
1、概念
过采样是通过增加数量较少的类别(少数类)的样本数量,使其与数量较多的类别(多数类)的样本数量相匹配或超过。这可以通过复制现有样本或生成新的合成样本来实现。
2、原理
复制:简单地复制少数类的样本,直到其数量与多数类相等。
合成样本:使用算法如SMOTE(Synthetic Minority Over-sampling Technique)生成新的合成样本,而不是简单地复制现有样本。SMOTE通过在特征空间中插值来创建新的少数类样本。
5、案例
将原数据分成训练集和测试集,训练集进行过采样获得两倍大小的新的训练集
代码
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
data=pd.read_csv("creditcard.csv")
#StandardScaler用于数据标准化
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
# 对"Amount"列进行标准化处理
data["Amount"]=scaler.fit_transform(data[["Amount"]])
data=data.drop(["Time"],axis=1)
#随机抽取
# 准备数据集,分割特征和标签
from sklearn.model_selection import train_test_split
x=data.drop("Class",axis=1)
y=data["Class"]
# 随机分割训练集和测试集
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=0)
#对训练集进行过采样
from imblearn.over_sampling import SMOTE
oversamples=SMOTE(random_state=0)
os_x_train,os_y_train=oversamples.fit_resample(x_train,y_train)
# 随机分割训练集和测试集
os_x_train_w,os_x_test_w,os_y_train_w,os_y_test_w=train_test_split(os_x_train,os_y_train,test_size=0.3,random_state=0)
#交叉验证
from sklearn.model_selection import cross_val_score
scores=[]
c_param_range=[0.01,0.1,1,10,100]
for i in c_param_range:
lr=LogisticRegression(C=i,penalty='l2',solver='lbfgs',max_iter=1000)
score=cross_val_score(lr,os_x_train_w,os_y_train_w,cv=8,scoring='recall')
score_mean=sum(score)/len(score)
scores.append(score_mean)
# 选择平均召回率最高的C值
best_c=c_param_range[np.argmax(scores)]
lr=LogisticRegression(C=best_c,penalty='l2',max_iter=1000)
lr.fit(os_x_train_w,os_y_train_w)
from sklearn import metrics
# 打印分类报告
os_train_predicted=lr.predict(os_x_train_w)
print(metrics.classification_report(os_y_train_w,os_train_predicted))
os_test_predicted=lr.predict(os_x_test_w)
print(metrics.classification_report(os_y_test_w,os_test_predicted))
train_predicted=lr.predict(x_train)
print(metrics.classification_report(y_train,train_predicted))
test_predicted=lr.predict(x_test)
print(metrics.classification_report(y_test,test_predicted))
thresh=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
recalls=[]
for i in thresh:
y_predict_proba=lr.predict_proba(x_test)
y_predict_proba=pd.DataFrame(y_predict_proba).drop([0],axis=1)
y_predict_proba[y_predict_proba[[1]]>i]=1
y_predict_proba[y_predict_proba[[1]]<=i]=0
recall=metrics.recall_score(y_test,y_predict_proba[1])
recalls.append(recall)
print(i,recall)