逻辑回归:从theta

时间:2017-03-09 20:19:35

标签: python numpy logistic-regression

我有以下代码:

x1 = np.random.randn(100)
y1 = np.random.randn(100) + 3
x2 = np.random.randn(100) + 3
y2 = np.random.randn(100)
plt.plot(x1, y1, "+", x2, y2, "x")
plt.axis('equal')
plt.show()

导致以下图像

enter image description here

我已经实现了自己的逻辑回归,这会返回一个theta,我想用这个θ来绘制决策边界,但我不知道该怎么做。

X = np.matrix(np.vstack((np.hstack((x1,x2)), np.hstack((y1,y2)))).T)
X = np.concatenate((np.ones((X.shape[0], 1)), X), axis=1)
Y = np.matrix(1.0 * np.hstack((np.zeros(100), np.ones(100)))).T

learning_rate = 0.0001
iterations    = 3000
theta         = np.matrix([[0.5], [0.5], [0.5]])
theta = logistic_regression(theta, X, Y, learning_rate, iterations)

这会给theta =

[[ 0.40377942]
 [ 0.53696461]
 [ 0.1398419 ]]
例如,

。我如何使用它来绘制决策边界?

1 个答案:

答案 0 :(得分:7)

您想绘制θ T X = 0,其中X是包含(1,x,y)的向量。也就是说,您想绘制由theta[0] + theta[1]*x + theta[2]*y = 0定义的线。解决y:

y = -(theta[0] + theta[1]*x)/theta[2]

所以,比如:

theta = theta[:,0]  # Make theta a 1-d array.
x = np.linspace(-6, 6, 50)
y = -(theta[0] + theta[1]*x)/theta[2]
plt.plot(x, y)

但是,有些东西看起来并不正确,因为您有theta[1] > 0theta[2] > 0,这会产生一条负斜率的线。

相关问题