2016-10-12 80 views
0

即時通訊新的python。python scikit線性迴歸怪異結果

正在使用matplotlib繪製linea迴歸的結果。

我試過一些基本的數據,它的工作原理,但是當我嘗試使用實際數據時,迴歸線是完全錯誤的。我認爲我在fit()或predict()函數中做錯了什麼。

這是代碼:

import matplotlib.pyplot as plt 
from sklearn import linear_model 
import scipy 
import numpy as np 
regr=linear_model.LinearRegression() 
A=[[69977, 4412], [118672, 4093], [127393, 12324], [226158, 15453], [247883, 8924], [228057, 6568], [350119, 4040], [197808, 6793], [205989, 8471], [10666, 632], [38746, 1853], [12779, 611], [38570, 1091], [38570, 1091], [95686, 8752], [118025, 17620], [79164, 13335], [83051, 1846], [4177, 93], [29515, 1973], [75671, 5070], [10077, 184], [78975, 4374], [187730, 17133], [61558, 2521], [34705, 1725], [206514, 10548], [13563, 1734], [134931, 7117], [72527, 6551], [16014, 310], [20619, 403], [21977, 437], [20204, 258], [20406, 224], [20551, 375], [38251, 723], [20416, 374], [21125, 429], [20405, 235], [20042, 431], [20016, 366], [19702, 200], [20335, 420], [21200, 494], [22667, 487], [20393, 405], [20732, 414], [20602, 393], [111705, 7623], [112159, 5982], [6750, 497], [59624, 418], [111468, 10209], [40057, 1484], [435, 0], [498848, 17053], [26585, 1390], [75170, 3883], [139146, 3540], [84931, 7214], [19144, 3125], [31144, 2861], [66573, 818], [114253, 4155], [15421, 2094], [307497, 5110], [484904, 10273], [373476, 36365], [128152, 10920], [517285, 106315], [453483, 10054], [270763, 17542], [9068, 362], [61992, 1608], [35791, 1747], [131215, 6227], [4314, 191], [16316, 2650], [72791, 2077], [47008, 4656], [10853, 1346], [66708, 4855], [214736, 11334], [46493, 4236], [23042, 737], [335941, 11177], [65167, 2433], [94913, 7523], [454738, 12335]] 
#my data are selected from a Mysql DB and stored in np array like this one above. 



regr.fit(A,A[:,1]) 
plt.scatter(A[:,0],A[:,1], color='black') 
plt.plot(A[:,1],regr.predict(A), color='blue',linewidth=3) 
plt.show() 

什麼求購是使用來自A的第一列和第二列中的數據的迴歸線。這是結果:

enter image description here

我知道,離羣的存在可以havily對輸出的影響,但我想與其他收費的迴歸和迴歸線更接近很多景區裏點是,所以我很確定我錯過了什麼。

謝謝。

編輯1:建議我再次只改變劇情()參數。代替的A [:,1] i的使用的[:,0],這是結果:

enter image description here

在scikit-learn.org/stable/modules/linear_model.html,看上去簡單的例子像我的。我不需要預測,所以我沒有在訓練和測試集中切分我的數據......也許我誤解了「X,y」的含義,但再次看到鏈接中的示例,它看起來像我的。

編輯2:最後它的工作。

X=A[:,0] 
X=X[:,np.newaxis] 
regr=linear_model.LinearRegression() 
regr.fit(X,A[:,1]) 
plt.plot(X,regr.predict(X)) 

X參數只需要是2個暗淡的數組。在EDIT 1的例子還真的誤導我:(。

回答

0

你似乎包括目標值在訓練數據A[:, 1]。擬合命令的格式regr.fit(X, y)的。

你似乎也有一個問題這條線:

plt.plot(A[:,1],regr.predict(A), color='blue',linewidth=3)

我認爲你應該應該A[:, 0]取代A[:, 1],如果你想給PL對預測值的預測。

您可能會發現在開始時將數據拆分爲Xy更容易 - 它可能會使事情更加清晰。