Scikit学习Logistic回归混淆

时间:2015-05-23 19:19:59

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

我在理解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()

enter image description here

显然,这似乎并不合适。此外,当我在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))

enter image description here

我在这里缺少什么?

1 个答案:

答案 0 :(得分:4)

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

lr = LogisticRegression(C=100)

将生成您要找的内容: enter image description here

正如您所发现的,更改intercept_scaling参数的值也会产生类似的效果。原因还在于正规化或者更确切地说它如何影响回归中的偏差估计。较大的intercept_scaling参数将有效降低正则化对偏差的影响。

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