2012-06-26 130 views
1

我想繪製散點圖上的線性迴歸線。我研究它(例如Linear regression with matplotlib/numpy),但我的執行力度不工作與matplotlib線性迴歸線給出ValueError

x = [-6.0, -5.0, -10.0, -5.0, -8.0, -3.0, -6.0, -8.0, -8.0, 7.5, 8.0, 9.0, 10.0, 7.0, 5.0, 5.0, -8.0, 8.0, 7.0] 
    y = [-7.094043198985176, -6.1018562538660044, -15.511155265492038, -2.7131460277126984, -8.6127363078417609, -3.1575686002528163, -10.246242711042497, -6.4333658386991992, -16.167988119268013, 2.4709555610646134, 4.5492058088492948, 5.5896790992867942, 3.3824425476540005, -1.8140272426684692, -1.5975329456235758, 5.1403915611396904, -4.4469105070935955, 0.51211850576547091, 5.7059436876065952] 
    m,b = numpy.polyfit(x,y,1) 
    plt.plot(x, y, x, m*x+b) 
    plt.show() 

返回:

Traceback (most recent call last): 
    File "test.py", line 464, in <module> 
    correlate(trainingSet,trainingSet.trainingTexts) 
    File "test.py", line 434, in correlate 
    plt.plot(x, y, x, m*x+b) 
    File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 2458, in plot 
    ret = ax.plot(*args, **kwargs) 
    File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 3848, in plot 
    for line in self._get_lines(*args, **kwargs): 
    File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 323, in _grab_ne 
xt_args 
    for seg in self._plot_args(remaining, kwargs): 
    File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 300, in _plot_ar 
gs 
    x, y = self._xy_from_xy(x, y) 
    File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 240, in _xy_from 
_xy 
    raise ValueError("x and y must have same first dimension") 
ValueError: x and y must have same first dimension 

我已檢查這兩個xy長度相同,他們是(19 )。任何想法我做錯了什麼?

回答

6

的問題是,x是一個Python list,而不是一個numpyarray,所以*作品不是您所期望的方式:

>>> m * x 
[] 

這是工作示例

plt.plot(x, y, x, numpy.array(x) * m +b) 
+0

你說得對。接得好。 – mgilson

+0

我還是新來的'numpy',我不知道_why_'m * x == []':D – unkulunkulu

+1

這很有趣。 m的類型是'numpy.float64'。顯然這個類型覆蓋'__mul__'(和'__rmul__'),使得'm * sequence'返回'int(m)* sequence'。如果m是一個常規的python float,由於序列不能乘以浮點數,所以會產生異常。 – mgilson