简单示例中的不良逻辑回归[scikit-learn]

时间:2018-10-17 15:52:25

标签: python scikit-learn

我正在尝试使用sklearn.linear_model.LogisticRegression

进行逻辑回归的简单示例

代码如下:

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

# some randomly generated data with two well differentiated groups 
x1 = np.random.normal(loc=15, scale=2, size=(30,1))
y1 = np.random.normal(loc=10, scale=2, size=(30,1))
x2 = np.random.normal(loc=25, scale=2, size=(30,1))
y2 = np.random.normal(loc=20, scale=2, size=(30,1))

data1 = np.concatenate([x1, y1, np.zeros(shape=(30,1))], axis=1)
data2 = np.concatenate([x2, y2, np.ones(shape=(30,1))], axis=1)

dfa = pd.DataFrame(data=data1, columns=["F1", "F2", "group"])
dfb = pd.DataFrame(data=data2, columns=["F1", "F2", "group"])

df = pd.concat([dfa, dfb], ignore_index=True)

# the actual fitting
features = [item for item in df.columns if item not in ("group")]
logreg = LogisticRegression(verbose=1)
logreg.fit(df[features], df.group)

# plotting and checking the result

theta = logreg.coef_[0,:] # parameters
y0 = logreg.intercept_    # intercept

print("Theta =", theta)
print("Intercept = ", y0)

xdb = np.arange(0, 30, 0.2)  # dummy x vector for decision boundary
ydb = -(y0+theta[0]*xdb) / theta[1] # decision boundary y values

fig = plt.figure()
ax = fig.add_subplot(111)
colors = {0 : "red", 1 : "blue"}
for i, group in df.groupby("group"):
    plt.plot(group["F1"], group["F2"],
             MarkerFaceColor = colors[i], Marker = "o", LineStyle="",
             MarkerEdgeColor=colors[i])
plt.plot(xdb, ydb, LineStyle="--", Color="b")

令人震惊的是,结果图看起来像这样:

enter image description here

,实际上,可以计算出准确性:

predictions = logreg.predict(df[features])
metrics.accuracy_score(predictions, df["group"])

产生0.966 ...

我一定做错了,只是想不通。任何帮助深表感谢!

1 个答案:

答案 0 :(得分:1)

这是由于正则化。 line的最佳值应为-16左右的截距,但是由于正则化,它无法达到该水平。

逻辑回归将误差和权重值组合的损失函数最小化。在这种情况下,当我们增加C模型的值时,它将更多地集中在减少错误(从而找到更好的决策边界)上,而不是权重上。得出正确的决策边界。

尽管正规化在大多数现实世界场景中非常重要。在某些情况下,重要的是不要使用一个。

进行以下更改

logreg = LogisticRegression(verbose=1, C=100)

以下是输出 enter image description here

阅读有关正则化的更多信息以更好地理解