python - 简单示例中的错误逻辑回归 [scikit-learn]

标签 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...

我一定做错了什么,只是不明白是什么。非常感谢任何帮助!

最佳答案

这是由于正则化。直线的最佳值是截距值约为 -16,但由于正则化,它无法达到该水平。

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

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

进行以下更改

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

输出如下 enter image description here

阅读更多有关正则化的内容以更好地理解这一点

关于python - 简单示例中的错误逻辑回归 [scikit-learn],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52858950/

相关文章:

python - 在元组列表中查找元素

python - 在给定阈值内提取高度相关变量的最佳方法是什么

python - 检查 Python 中函数/方法中参数的类型

python - LightGBM 的特征重要性

python - 精度分数与指标公式不匹配

python - 在 Windows 上隐藏 python 进程和线程输出

python - 如何很好地格式化dict字符串输出

Python 机器学习标签和特征

python - Sklearn - 自动定义 get_params()

python - 从 sklearn GradientBoostedRegressor 访问计算出的偏差