使用Python进行多项式Lo​​gistic回归 您所在的位置:网站首页 惩罚逻辑回归SPSS 使用Python进行多项式Lo​​gistic回归

使用Python进行多项式Lo​​gistic回归

2024-07-15 16:41| 来源: 网络整理| 查看: 265

      【翻译自:  Multinomial Logistic Regression With Python】

      【说明:Jason Brownlee PhD大神的文章个人很喜欢,所以闲暇时间里会做一点翻译和学习实践的工作,这里是相应工作的实践记录,希望能帮到有需要的人!】

       多项逻辑回归是逻辑回归的扩展,增加了对多类分类问题的本地支持。默认情况下,逻辑回归仅限于两类分类问题。尽管有些扩展要求先将分类问题转换为多个二元分类问题,但某些扩展(例如“一对剩余”)可以允许将逻辑回归用于多分类问题。相反,多项式逻辑回归算法是对逻辑回归模型的扩展,该模型涉及将损失函数更改为交叉熵损失,并将概率分布预测为多项式概率分布以本地支持多类分类问题。

     在本教程中,您将发现如何在Python中开发多项逻辑回归模型。完成本教程后,您将知道:

多项式逻辑回归是对多元分类进行逻辑回归的扩展。 如何开发和评估多项式Lo​​gistic回归并开发最终模型以对新数据进行预测。 如何为多项逻辑回归模型调整惩罚超参数。 教程概述

    本教程分为三个部分:他们是:

多项式Lo​​gistic回归 评估多项式Lo​​gistic回归模型 多项逻辑回归的音调惩罚 多项式Lo​​gistic回归

      Logistic回归是一种分类算法。它适用于具有数字输入变量和具有两个值或类的分类目标变量的数据集。这种类型的问题称为二进制分类问题。逻辑回归是针对两类问题设计的,使用二项式概率分布函数对目标进行建模。对于阳性分类或结果,分类标签映射为1;对于阴性分类或结果,分类标签映射为0。拟合模型预测示例属于类别1的概率。默认情况下,逻辑回归不能用于具有两个以上类别标签的分类任务,即所谓的多类别分类。相反,它需要进行修改以支持多类分类问题。使Logistic回归适应多类分类问题的一种流行方法是将多类分类问题分解为多个二元分类问题,并在每个子问题上拟合标准Logistic回归模型。这种类型的技术包括一对一包装和一对一包装模型。

      一种替代方法涉及更改逻辑回归模型以直接支持多个类别标签的预测。具体来说,为了预测输入示例属于每个已知类标签的概率。定义多类概率的概率分布称为多项式概率分布。适用于学习和预测多项式概率分布的逻辑回归模型称为“多项逻辑回归”。同样,我们可以将默认逻辑回归或标准逻辑回归称为二项式逻辑回归。

二项式Logistic回归:标准Logistic回归可预测每个输入示例的二项式概率(即针对两个类别)。 多项式Lo​​gistic回归:Logistic回归的改进版本,可预测每个输入示例的多项式概率(即两个以上类别)。

      如果您不熟悉二项式和多项式概率分布,则可能需要阅读本教程:

                                                                                                                        机器学习的离散概率分布        将Logistic回归从二项式概率转换为多项式概率,需要更改用于训练模型的损失函数(例如,对数损失变为交叉熵损失),并且将每个类别标签的输出从单个概率值更改为一个概率。既然我们熟悉了多项逻辑回归,现在让我们看一下如何在Python中开发和评估多项逻辑回归模型。

评估多项式Logistic回归模型

        在本节中,我们将使用scikit-learn Python机器学习库开发和评估多项逻辑回归模型。首先,我们将定义一个综合的多类分类数据集,以用作调查的基础。 这是一个通用数据集,您以后可以轻松地用自己的已加载数据集替换。

make_classification()函数可用于生成具有给定数量的行,列和类的数据集。 在这种情况下,我们将生成一个包含1,000行,10个输入变量或列以及3个类的数据集。下面的示例生成数据集,并总结数组的形状以及示例在三个类中的分布。

# test classification dataset from collections import Counter from sklearn.datasets import make_classification # define dataset X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, n_classes=3, random_state=1) # summarize the dataset print(X.shape, y.shape) print(Counter(y))

       运行示例将确认数据集具有1,000行和10列(如我们预期的那样),并且行在三个类中的分布大致均匀,每个类中约有334个示例。

(1000, 10) (1000,) Counter({1: 334, 2: 334, 0: 332})

     通过LogisticRegression类在scikit-learn库中支持Logistic回归。通过将“ multi_class”参数设置为“ multinomial”,将“ solver”参数设置为支持多项逻辑回归的求解器(例如“ lbfgs”),可以为LogisticRegression类配置多项逻辑回归。

# define the multinomial logistic regression model model = LogisticRegression(multi_class='multinomial', solver='lbfgs')

       多项逻辑回归模型将使用交叉熵损失进行拟合,并将预测每个整数编码的类标签的整数值。既然我们熟悉了多项逻辑回归API,我们可以看看如何在合成的多类分类数据集上评估多项逻辑回归模型。优良作法是使用重复的分层k折交叉验证来评估分类模型。 分层可确保每个交叉验证对折在每个班级中的示例分布与整个训练数据集大致相同。我们将使用10折的三个重复,这是一个很好的默认值,并假设类是平衡的,并使用分类精度评估模型性能。

     下面列出了评估用于多类分类的多项式逻辑回归的完整示例。

# evaluate multinomial logistic regression model from numpy import mean from numpy import std from sklearn.datasets import make_classification from sklearn.model_selection import cross_val_score from sklearn.model_selection import RepeatedStratifiedKFold from sklearn.linear_model import LogisticRegression # define dataset X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, n_classes=3, random_state=1) # define the multinomial logistic regression model model = LogisticRegression(multi_class='multinomial', solver='lbfgs') # define the model evaluation procedure cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1) # evaluate the model and collect the scores n_scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1) # report the model performance print('Mean Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))

       运行示例将报告评估过程所有折叠和重复的平均分类准确性。

      注意:由于算法或评估程序的随机性,或者数值精度不同,您的结果可能会有所不同。 考虑运行该示例几次并比较平均结果。

      在这种情况下,我们可以看到带有默认罚分的多项式逻辑回归模型在我们的综合分类数据集上实现了约68.1%的平均分类精度。

Mean Accuracy: 0.681 (0.042)

      我们可能决定使用多项逻辑回归模型作为最终模型,并对新数据进行预测。这可以通过首先在所有可用数据上拟合模型,然后调用predict()函数对新数据进行预测来实现。下面的示例演示了如何使用多项式Logistic回归模型对新数据进行预测。

# make a prediction with a multinomial logistic regression model from sklearn.datasets import make_classification from sklearn.linear_model import LogisticRegression # define dataset X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, n_classes=3, random_state=1) # define the multinomial logistic regression model model = LogisticRegression(multi_class='multinomial', solver='lbfgs') # fit the model on the whole dataset model.fit(X, y) # define a single row of input data row = [1.89149379, -0.39847585, 1.63856893, 0.01647165, 1.51892395, -3.52651223, 1.80998823, 0.58810926, -0.02542177, -0.52835426] # predict the class label yhat = model.predict([row]) # summarize the predicted class print('Predicted Class: %d' % yhat[0])

      运行示例首先使模型适合所有可用数据,然后定义一行数据,将数据提供给模型以进行预测。在这种情况下,我们可以看到模型为单行数据预测了类“ 1”。

Predicted Class: 1

      多项式逻辑回归的好处是它可以预测数据集中所有已知类标签的校准概率。这可以通过在模型上调用predict_proba()函数来实现。以下示例演示了如何使用多项逻辑回归模型预测新示例的多项概率分布。

# predict probabilities with a multinomial logistic regression model from sklearn.datasets import make_classification from sklearn.linear_model import LogisticRegression # define dataset X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, n_classes=3, random_state=1) # define the multinomial logistic regression model model = LogisticRegression(multi_class='multinomial', solver='lbfgs') # fit the model on the whole dataset model.fit(X, y) # define a single row of input data row = [1.89149379, -0.39847585, 1.63856893, 0.01647165, 1.51892395, -3.52651223, 1.80998823, 0.58810926, -0.02542177, -0.52835426] # predict a multinomial probability distribution yhat = model.predict_proba([row]) # summarize the predicted probabilities print('Predicted Probabilities: %s' % yhat[0])

     运行示例首先使模型适合所有可用数据,然后定义一行数据,将其提供给模型以预测类概率。

     注意:由于算法或评估程序的随机性,或者数值精度不同,您的结果可能会有所不同。 考虑运行该示例几次并比较平均结果。

      在这种情况下,我们可以看到类别1(例如,将数组索引映射到类别整数值)具有约0.50的最大预测概率。

Predicted Probabilities: [0.16470456 0.50297138 0.33232406]

      现在,我们已经熟悉了评估和使用多项式逻辑回归模型,现在让我们探讨如何调整模型的超参数。

多项逻辑回归的音调惩罚

     调整多项式逻辑回归的重要超参数是惩罚项。该术语对模型施加压力以寻求较小的模型权重。这是通过将模型系数的加权总和添加到损失函数中来实现的,鼓励模型在拟合模型的同时减小权重的大小以及误差。一种流行的惩罚类型是L2惩罚,它将平方系数的(加权)和加到损失函数中。可以使用系数的加权,以将惩罚的强度从完全惩罚降低到非常小的惩罚。默认情况下,LogisticRegression类使用L2惩罚,系数的权重设置为1.0。惩罚的类型可以通过“惩罚”参数设置为值“ l1”,“ l2”,“ elasticnet”(例如,两者),尽管并非所有求解器都支持所有惩罚类型。可以通过“ C”自变量设置惩罚中系数的权重。

# define the multinomial logistic regression model with a default penalty LogisticRegression(multi_class='multinomial', solver='lbfgs', penalty='l2', C=1.0)

惩罚的加权实际上是逆加权,也许惩罚= 1 –C。

从文档中:

C:浮点型,默认= 1.0 正则强度的倒数; 必须为正浮点数。 与支持向量机一样,较小的值指定更强的正则化。 这意味着接近1.0的值表示很少的惩罚,接近零的值表示很强的惩罚。 C值为1.0可能表示完全没有损失。 C接近1.0:轻微。 C接近0.0:严厉。 可以通过将“ penalty”参数设置为字符串“ none”来禁用惩罚。 # define the multinomial logistic regression model without a penalty LogisticRegression(multi_class='multinomial', solver='lbfgs', penalty='none')

       现在我们已经熟悉了惩罚,让我们看一下如何探索不同惩罚值对多项式Logistic回归模型的性能的影响。通常,以对数刻度测试惩罚值,以便快速发现对模型有效的惩罚等级。 一旦发现,进一步调整该规模可能会有所帮助。除了无惩罚或0.0之外,我们还将探索L2惩罚,其权重值的对数范围为0.0001至1.0。下面列出了评估L2惩罚值以进行多项逻辑回归的完整示例。

# tune regularization for multinomial logistic regression from numpy import mean from numpy import std from sklearn.datasets import make_classification from sklearn.model_selection import cross_val_score from sklearn.model_selection import RepeatedStratifiedKFold from sklearn.linear_model import LogisticRegression from matplotlib import pyplot # get the dataset def get_dataset(): X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=1, n_classes=3) return X, y # get a list of models to evaluate def get_models(): models = dict() for p in [0.0, 0.0001, 0.001, 0.01, 0.1, 1.0]: # create name for model key = '%.4f' % p # turn off penalty in some cases if p == 0.0: # no penalty in this case models[key] = LogisticRegression(multi_class='multinomial', solver='lbfgs', penalty='none') else: models[key] = LogisticRegression(multi_class='multinomial', solver='lbfgs', penalty='l2', C=p) return models # evaluate a give model using cross-validation def evaluate_model(model, X, y): # define the evaluation procedure cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1) # evaluate the model scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1) return scores # define dataset X, y = get_dataset() # get the models to evaluate models = get_models() # evaluate the models and store results results, names = list(), list() for name, model in models.items(): # evaluate the model and collect the scores scores = evaluate_model(model, X, y) # store the results results.append(scores) names.append(name) # summarize progress along the way print('>%s %.3f (%.3f)' % (name, mean(scores), std(scores))) # plot model performance for comparison pyplot.boxplot(results, labels=names, showmeans=True) pyplot.show()

       运行示例将报告沿途每种配置的平均分类精度。

       注意:由于算法或评估程序的随机性,或者数值精度的差异,您的结果可能会有所不同。 考虑运行该示例几次并比较平均结果。

      在这种情况下,我们可以看到C值为1.0时,最佳分数约为77.7%,这与不使用获得相同分数的惩罚相同。

>0.0000 0.777 (0.037) >0.0001 0.683 (0.049) >0.0010 0.762 (0.044) >0.0100 0.775 (0.040) >0.1000 0.774 (0.038) >1.0000 0.777 (0.037)

     为每种配置的精度得分创建了箱须图,并且所有图以相同比例并排显示在图形上,以便直接比较。

      在这种情况下,我们可以看到我们在此数据集上使用的惩罚越大(即C值越小),模型的性能越差。

 

 

 

 

 

 

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有