十二、逻辑回归

作者:Chris Albon

译者:飞龙

协议:CC BY-NC-SA 4.0

C 超参数快速调优

有时,学习算法的特征使我们能够比蛮力或随机模型搜索方法更快地搜索最佳超参数。

scikit-learn 的LogisticRegressionCV方法包含一个参数C。 如果提供了一个列表,C是可供选择的候选超参数值。 如果提供了一个整数,C的这么多个候选值,将从 0.0001 和 10000 之间的对数标度(C的合理值范围)中提取。

  1. # 加载库
  2. from sklearn import linear_model, datasets
  3. # 加载数据
  4. iris = datasets.load_iris()
  5. X = iris.data
  6. y = iris.target
  7. # 创建逻辑回归的交叉验证
  8. clf = linear_model.LogisticRegressionCV(Cs=100)
  9. # 训练模型
  10. clf.fit(X, y)
  11. '''
  12. LogisticRegressionCV(Cs=100, class_weight=None, cv=None, dual=False,
  13. fit_intercept=True, intercept_scaling=1.0, max_iter=100,
  14. multi_class='ovr', n_jobs=1, penalty='l2', random_state=None,
  15. refit=True, scoring=None, solver='lbfgs', tol=0.0001, verbose=0)
  16. '''

在逻辑回归中处理不平衡类别

像 scikit-learn 中的许多其他学习算法一样,LogisticRegression带有处理不平衡类的内置方法。 如果我们有高度不平衡的类,并且在预处理期间没有解决它,我们可以选择使用class_weight参数来对类加权,确保我们拥有每个类的平衡组合。 具体来说,balanced参数会自动对类加权,与其频率成反比:

十二、逻辑回归 - 图1

其中 十二、逻辑回归 - 图2 是类 十二、逻辑回归 - 图3 的权重,十二、逻辑回归 - 图4 是观察数,十二、逻辑回归 - 图5 是类 十二、逻辑回归 - 图6 中的观察数,十二、逻辑回归 - 图7 是类的总数。

  1. # 加载库
  2. from sklearn.linear_model import LogisticRegression
  3. from sklearn import datasets
  4. from sklearn.preprocessing import StandardScaler
  5. import numpy as np
  6. # 加载数据
  7. iris = datasets.load_iris()
  8. X = iris.data
  9. y = iris.target
  10. # 通过移除前 40 个观测,使类高度不均衡
  11. X = X[40:,:]
  12. y = y[40:]
  13. # 创建目标向量,如果表示类别是否为 0
  14. y = np.where((y == 0), 0, 1)
  15. # 标准化特征
  16. scaler = StandardScaler()
  17. X_std = scaler.fit_transform(X)
  18. # 创建决策树分类器对象
  19. clf = LogisticRegression(random_state=0, class_weight='balanced')
  20. # 训练模型
  21. model = clf.fit(X_std, y)

逻辑回归

尽管其名称中存在“回归”,但逻辑回归实际上是广泛使用的二分类器(即,目标向量只有两个值)。 在逻辑回归中,线性模型(例如 十二、逻辑回归 - 图8)包含在 logit(也称为 sigmoid)函数中,十二、逻辑回归 - 图9,满足:

十二、逻辑回归 - 图10

其中 十二、逻辑回归 - 图11 是第 十二、逻辑回归 - 图12 个观测的目标值 十二、逻辑回归 - 图13 为 1 的概率,十二、逻辑回归 - 图14 是训练数据,十二、逻辑回归 - 图15十二、逻辑回归 - 图16 是要学习的参数,十二、逻辑回归 - 图17 是自然常数。

  1. # 加载库
  2. from sklearn.linear_model import LogisticRegression
  3. from sklearn import datasets
  4. from sklearn.preprocessing import StandardScaler
  5. # 加载只有两个类别的数据
  6. iris = datasets.load_iris()
  7. X = iris.data[:100,:]
  8. y = iris.target[:100]
  9. # 标准化特征
  10. scaler = StandardScaler()
  11. X_std = scaler.fit_transform(X)
  12. # 创建逻辑回归对象
  13. clf = LogisticRegression(random_state=0)
  14. # 训练模型
  15. model = clf.fit(X_std, y)
  16. # 创建新的观测
  17. new_observation = [[.5, .5, .5, .5]]
  18. # 预测类别
  19. model.predict(new_observation)
  20. # array([1])
  21. # 查看预测的概率
  22. model.predict_proba(new_observation)
  23. # array([[ 0.18823041, 0.81176959]])

大量数据上的逻辑回归

scikit-learn 的LogisticRegression提供了许多用于训练逻辑回归的技术,称为求解器。 大多数情况下,scikit-learn 会自动为我们选择最佳求解器,或警告我们,你不能用求解器做一些事情。 但是,我们应该注意一个特殊情况。

虽然精确的解释超出了本书的范围,但随机平均梯度下降使得我们在数据非常大时,比其他求解器更快训练模型。 但是,对特征尺度也非常敏感,标准化我们的特征尤为重要。 我们可以通过设置solver ='sag'来设置我们的学习算法来使用这个求解器。

  1. # 加载库
  2. from sklearn.linear_model import LogisticRegression
  3. from sklearn import datasets
  4. from sklearn.preprocessing import StandardScaler
  5. # 加载数据
  6. iris = datasets.load_iris()
  7. X = iris.data
  8. y = iris.target
  9. # 标准化特征
  10. scaler = StandardScaler()
  11. X_std = scaler.fit_transform(X)
  12. # 创建使用 SAG 求解器的逻辑回归
  13. clf = LogisticRegression(random_state=0, solver='sag')
  14. # 训练模型
  15. model = clf.fit(X_std, y)

带有 L1 正则化的逻辑回归

L1 正则化(也称为最小绝对误差)是数据科学中的强大工具。 有许多教程解释 L1 正则化,我不会在这里尝试这样做。 相反,本教程将展示正则化参数C对系数和模型精度的影响。

  1. import numpy as np
  2. from sklearn.linear_model import LogisticRegression
  3. from sklearn import datasets
  4. from sklearn.model_selection import train_test_split
  5. from sklearn.preprocessing import StandardScaler

本教程中使用的数据集是着名的鸢尾花数据集。鸢尾花数据包含来自三种鸢尾花y,和四个特征变量X的 50 个样本。

数据集包含三个类别(三种鸢尾),但是为了简单起见,如果目标数据是二元的,则更容易。因此,我们将从数据中删除最后一种鸢尾。

  1. # 加载鸢尾花数据集
  2. iris = datasets.load_iris()
  3. # 从特征中创建 X
  4. X = iris.data
  5. # 从目标中创建 y
  6. y = iris.target
  7. # 重新生成变量,保留所有标签不是 2 的数据
  8. X = X[y != 2]
  9. y = y[y != 2]
  10. # 查看特征
  11. X[0:5]
  12. '''
  13. array([[ 5.1, 3.5, 1.4, 0.2],
  14. [ 4.9, 3\. , 1.4, 0.2],
  15. [ 4.7, 3.2, 1.3, 0.2],
  16. [ 4.6, 3.1, 1.5, 0.2],
  17. [ 5\. , 3.6, 1.4, 0.2]])
  18. '''
  19. # 查看目标数据
  20. y
  21. '''
  22. array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  24. 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  25. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  26. 1, 1, 1, 1, 1, 1, 1, 1])
  27. '''
  28. # 将数据拆分为测试和训练集
  29. # 将 30% 的样本放入测试集
  30. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

因为正则化惩罚由系数的绝对值之和组成,所以我们需要缩放数据,使系数都基于相同的比例。

  1. # 创建缩放器对象
  2. sc = StandardScaler()
  3. # 将缩放器拟合训练数据,并转换
  4. X_train_std = sc.fit_transform(X_train)
  5. # 将缩放器应用于测试数据
  6. X_test_std = sc.transform(X_test)

L1 的用处在于它可以将特征系数逼近 0,从而创建一种特征选择方法。 在下面的代码中,我们运行带有 L1 惩罚的逻辑回归四次,每次都减少了C的值。 我们应该期望随着C的减少,更多的系数变为 0。

  1. C = [10, 1, .1, .001]
  2. for c in C:
  3. clf = LogisticRegression(penalty='l1', C=c)
  4. clf.fit(X_train, y_train)
  5. print('C:', c)
  6. print('Coefficient of each feature:', clf.coef_)
  7. print('Training accuracy:', clf.score(X_train, y_train))
  8. print('Test accuracy:', clf.score(X_test, y_test))
  9. print('')
  10. '''
  11. C: 10
  12. Coefficient of each feature: [[-0.0855264 -3.75409972 4.40427765 0\. ]]
  13. Training accuracy: 1.0
  14. Test accuracy: 1.0
  15. C: 1
  16. Coefficient of each feature: [[ 0\. -2.28800472 2.5766469 0\. ]]
  17. Training accuracy: 1.0
  18. Test accuracy: 1.0
  19. C: 0.1
  20. Coefficient of each feature: [[ 0\. -0.82310456 0.97171847 0\. ]]
  21. Training accuracy: 1.0
  22. Test accuracy: 1.0
  23. C: 0.001
  24. Coefficient of each feature: [[ 0\. 0\. 0\. 0.]]
  25. Training accuracy: 0.5
  26. Test accuracy: 0.5
  27. '''

注意,当C减小时,模型系数变小(例如,从C = 10时的4.36276075变为C = 0.1时的0.0.97175097),直到C = 0.001,所有系数都是零。 这是变得更加突出的,正则化惩罚的效果。

OVR 逻辑回归

逻辑回归本身只是二分类器,这意味着它们无法处理具有两个类别以上的目标向量。 但是,逻辑回归有一些聪明的扩展来实现它。 在 One-VS-Rest(OVR)逻辑回归中,针对每个类别训练单独的模型,预测观测是否是该类(因此使其成为二分类问题)。 它假定每个分类问题(例如是不是类 0)是独立的。

  1. # 加载库
  2. from sklearn.linear_model import LogisticRegression
  3. from sklearn import datasets
  4. from sklearn.preprocessing import StandardScaler
  5. # 加载数据
  6. iris = datasets.load_iris()
  7. X = iris.data
  8. y = iris.target
  9. # 标准化特征
  10. scaler = StandardScaler()
  11. X_std = scaler.fit_transform(X)
  12. # 创建 OVR 逻辑回归对象
  13. clf = LogisticRegression(random_state=0, multi_class='ovr')
  14. # 训练模型
  15. model = clf.fit(X_std, y)
  16. # 创建新的观测
  17. new_observation = [[.5, .5, .5, .5]]
  18. # 预测类别
  19. model.predict(new_observation)
  20. # array([2])
  21. # 查看预测概率
  22. model.predict_proba(new_observation)
  23. # array([[ 0.0829087 , 0.29697265, 0.62011865]])