【问题标题】:Scikit Learn Logistic Regression confusionScikit 学习逻辑回归混淆
【发布时间】:2015-08-05 15:43:24
【问题描述】:

我在理解 sckit-learn 的 LogisticRegression() 方法时遇到了一些麻烦。这是一个简单的例子

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression

# Create a sample dataframe
data = [['Age', 'ZepplinFan'], [13, 0], [25, 0], [40, 1], [51, 0], [55, 1], [58, 1]]
columns=data.pop(0)
df = pd.DataFrame(data=data, columns=columns)

   Age  ZepplinFan
0   13           0
1   25           0
2   40           1
3   51           0
4   55           1
5   58           1

# Fit Logistic Regression
lr = LogisticRegression()
lr.fit(X=df[['Age']], y = df['ZepplinFan'])

# View the coefficients
lr.intercept_ # returns -0.56333276
lr.coef_ # returns 0.02368826

# Predict for new values
xvals = np.arange(-10,70,1)
predictions = lr.predict_proba(X=xvals[:,np.newaxis])
probs = [y for [x, y] in predictions]

# Plot the fitted model
plt.plot(xvals, probs)
plt.scatter(df.Age.values, df.ZepplinFan.values)
plt.show()

显然这似乎不太合适。此外,当我在 R 中做这个练习时,我会得到不同的系数和更有意义的模型。

lapply(c("data.table","ggplot2"), require, character.only=T)
dt <- data.table(Age=c(13, 25, 40, 51, 55, 58), ZepplinFan=c(0, 0, 1, 0, 1, 1))
mylogit <- glm(ZepplinFan ~ Age, data = dt, family = "binomial")
newdata <- data.table(Age=seq(10,70,1))
newdata[, ZepplinFan:=predict(mylogit, newdata=newdata, type="response")]

mylogit$coeff
(Intercept)         Age 
    -4.8434      0.1148 

ggplot()+geom_point(data=dt, aes(x=Age, y=ZepplinFan))+geom_line(data=newdata, aes(x=Age, y=ZepplinFan))

我在这里错过了什么?

【问题讨论】:

  • 似乎如果我设置lr = LogisticRegression(intercept_scaling=9999),那么我会得到预期的结果。尽管如此,我仍然对拦截缩放的真正含义感到迷茫,并且还没有找到太多关于它的信息。
  • 请参阅关于intercept_scaling 与C 关系的编辑。

标签: python-3.x scikit-learn logistic-regression


【解决方案1】:

您面临的问题与 scikit learn 使用 regularized 逻辑回归这一事实有关。正则化项允许控制对数据的拟合和对未来未知数据的泛化之间的权衡。参数C 用于控制正则化,在您的情况下:

lr = LogisticRegression(C=100)

将生成您正在寻找的内容:

如您所见,更改intercept_scaling 参数的值也可以达到类似的效果。原因也是正则化,或者更确切地说它如何影响回归中偏差的估计。较大的intercept_scaling参数会有效降低正则化对bias的影响。

有关 scikit-learn 使用的 LR 和求解器的实现的更多信息,请查看:http://scikit-learn.org/stable/modules/linear_model.html#logistic-regression

【讨论】: