有没有办法将多个逻辑回归方程合为一体?

时间:2019-01-23 21:09:11

标签: python scikit-learn logistic-regression ensemble-learning

我正在研究二进制分类问题,其中答复率(不良)小于1%。预测变量包括一组名义上的分类变量和连续变量。

最初,我尝试了一种过采样技术(SMOTE)以平衡这两个类别。对过采样的数据集执行Logistic回归可得到良好的整体准确性,但假阳性率非常高。

我现在计划进行欠采样并运行多个逻辑回归模型。我正在处理的基本python代码如下。在将这些多个逻辑回归模型的结果整合为一个时需要指导。

import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
#Set i for the number of equations required
for i in range(10):
   #Create a sample of goods, good is pandas df containing goods
   sample_good=good.sample(n=300,replace=True)

   #Create a sample of bads, bad is pandas df containing bads. There are 
   #only 100 bads in the dataset
   sample_bad=bad.sample(n=100,replace=True)

   #Append the good and bad sample
   sample=sample_good.append(sample_bad)

   X = sample.loc[:, sample.columns != 'y']
   y = sample.loc[:, sample.columns == 'y']

   from sklearn.linear_model import LogisticRegression
   from sklearn import metrics
   X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, 
   random_state=0)
   logreg = LogisticRegression()
   logreg.fit(X_train, y_train)
   y_pred = logreg.predict(X_test)
   print('Accuracy of logistic regression classifier on test set: 
   {:.2f}'.format(logreg.score(X_test, y_test)))

上面的for循环运行10次并构建10个不同的模型。需要将这10个模型整合为一个模型的指导。我已经阅读了诸如装袋等可用技术的信息。在这种情况下,由于响应率非常低,因此我创建的示例每次都需要具有所有不利条件。

1 个答案:

答案 0 :(得分:2)

我认为您应该使用scikit-learn的BaggingClassifier。简而言之,它适用于您数据的随机子样本中的多个分类器,然后让它们投票执行分类。该元估计器会优雅地阻止您编写for循环。至于采样(我相信这是您编写循环的原始动机),您可以在model.fit()方法中调整权重。

import numpy as np
from sklearn.ensemble import BaggingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import balanced_accuracy_score

breast_cancer = datasets.load_breast_cancer()
X = breast_cancer.data
y = breast_cancer.target
X_train, X_test, y_train, y_test = train_test_split(X,y)

如您所见,数据集不平衡(毕竟是医疗数据):

len(y_train[y_train == 0]),len(y_train[y_train == 1]) # 163, 263

因此,让我们添加样本权重

y0 = len(y_train[y_train == 0])
y1 = len(y_train[y_train == 1])

w0 = y1/y0
w1 = 1

sample_weights = np.zeros(len(y_train))
sample_weights[y_train == 0] = w0
sample_weights[y_train == 1] = w1

现在使用BaggingClassifier:

model = BaggingClassifier(LogisticRegression(solver = 'liblinear'), 
                      n_estimators=10, 
                      bootstrap = True, random_state = 2019)
model.fit(X,y,sample_weights)
balanced_accuracy_score(y_test,model.predict(X_test)) # 94.2%

请注意,如果我不适合样本权重,则平衡精度仅为92.1%(平衡精度=平均召回率,对于不平衡问题非常有用)