逻辑回归可视化

Logistic regression visualization

我正在学习基本的机器学习模型并遇到了下一个问题:预测线与数据集的拟合不佳。我正在生成一个简单的 2 class 数据集并训练 SVM 和逻辑回归。虽然指标显示了良好的结果,但可视化效果很差:经过训练的线显然没有将两个 class 分开。我不太明白哪里出了问题,有人可以解释一下吗?

from sklearn import datasets
from sklearn.linear_model import LogisticRegression

X, y = datasets.make_blobs(n_samples=100, centers=2, n_features=2, center_box=(0, 12))

clf = LogisticRegression()
clf.fit(X_train, y_train)

plt.plot(X_train[:, 0], X_train[:, 0] * svc.coef_[:, 1] + svc.coef_[:, 0])
plt.plot(X_train[:, 0][y_train == 0], X_train[:, 1][y_train == 0], 'g^')
plt.plot(X_train[:, 0][y_train == 1], X_train[:, 1][y_train == 1], 'bs')

我想我看到了错误,但有点难以确定,因为您演示的代码不完整,而且您混淆了逻辑回归和 SVM。为了澄清,我将回答逻辑回归。考虑到这一点,您用来绘制决策边界的公式是错误的。

逻辑回归的公式为:

我们将决策边界定义为 x_1 和 x_2 的值,使得 h(x) 为 0。然后根据输入变量之一重写方程。

那么只需将其实现到代码中即可。

# Gather model parameters
theta_0, theta_1, theta_2 = clf.intercept_[0], clf.coef_[:, 0], clf.coef_[:, 1]

# Choose a pair of x values that fit nicely with your data
x_vals = [np.min(X_train[:, 0]) - 2, np.max(X_train[:, 0]) + 2]

# Apply the formula
y_vals = [- (theta_0 + theta_1 * x)/theta_2 for x in v_vals]

plt.plot(x_vals, y_vals, '--', c='r')