![](/img/trans.png)
[英]How to create as scatter plot with regression line based on statsmodel OLS?
[英]How to plot a line on a scatter graph based on theta from regression in Python?
我正在像這樣計算我的AI的theta:
theta = opt.fmin_cg(cost, initial_theta, gradient, (newX, y))
哪個很棒,並給我以下輸出:
Optimization terminated successfully.
Current function value: 0.684355
Iterations: 6
Function evaluations: 15
Gradient evaluations: 15
當我打印theta時,我得到了:
[ 0. -0.28132729 0.158859 ]
現在,我想在散點圖上將其繪制為一條線,我的預期輸出如下所示:
但是當我嘗試使用算法在圖形上執行此操作時:
weights * features = weight0 + weight1 * feature1 + weight2 * feature2
像這樣:
x_axis = np.array([min(newX[:, 1]), max(newX[:, 1])])
y_axis = x_axis * theta[1:]
ax.plot(x_axis, y_axis, linewidth=2)
plt.show()
輸出看起來像這樣:
y_axis = x_axis * theta[1:]
應該與算法匹配什么?
更新:
newX
源自我的訓練數據框架,其創建方式如下:
newX = np.zeros(shape=(x.shape[0], x.shape[1] + 1))
newX[:, 1:] = x.values
現在看起來像這樣,概念是0是自由重量:
[[0. 8. 2.]
[0. 0. 0.]
[0. 0. 0.]
...
[0. 0. 0.]
[0. 0. 0.]
[0. 1. 1.]]
IIUC,您正在嘗試為Logistic回歸繪制決策邊界。 這不僅是ay = mx + b問題,還好,但是您首先需要確定決策邊界在哪里,通常為0.5。 我假設您要使用的模型看起來像h(x) = g(theta_0*x_0 + theta_1*x_1 + theta_2*x_2)
,其中g(x) = 1 / (1 + e^-x)
和x_1
以及x_2
是您要繪制的要素,即y和x軸(我不知道哪個是y,哪個是x,因為我不知道您的數據)。 因此,對於概率0.5,您要求解h(x) = 0.5
,即theta_0*x_0 + theta_1*x_1 + theta_2*x_2 = 0
因此,您要繪制的是直線0 = theta_0*x_0 + theta_1*x_1 + theta_2*x_2
。 假設您在x軸上有x_1
,在y軸上有x_2
。 ( x_0
只是1
,對應於您的攔截theta_0
。)
因此,您需要選擇(任意選擇) x_1
值,這些值將為您很好地說明邊界線。 數據集的最小/最大工作量已經完成。 然后根據上述公式求解x_2
。 您可以在此處定義函數: lambda x_1: (theta[0] + theta[1] * x_1) / theta[2]
。 我假設您的theta
變量對應於[intercept, coeff for x_1, coeff for x_2]
。 因此,您將得到類似以下內容的結果:
theta = [0., -0.28132729, 0.158859]
x = np.array([0, 10])
f = lambda x_1: (theta[0] + theta[1] * x_1) / theta[2]
y = f(x)
plt.plot(x, y)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.