2012-08-25 89 views
2

我發現線性迴歸的一個例子:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html#numpy.linalg.lstsq怎麼做線性迴歸的蟒蛇,與缺少的元素

x = np.array([0, 1, 2, 3]) 
y = np.array([-1, 0.2, 0.9, 2.1]) 
A = np.vstack([x, np.ones(len(x))]).T 
m, c = np.linalg.lstsq(A, y)[0] 
print m, c 

我的情況是:Y的一些元素缺失,所以x和y是不一樣長度。 它需要一些英特爾來判斷哪個位置丟失,所以rm它。 有沒有辦法,或者我應該自己做?

例如爲:

x=range(10) 
y=[i*3+5 for i in x] 
y.pop(3) #make a missing 

我不知道缺少哪個位置。但考慮平均坡度變化,y的位置4可能丟失。
這也許在特殊領域

+2

你怎麼能確定缺少哪個位置?這個構成的問題是有限的。 – mgilson

回答

0

一個問題,我下面有一個粗略的解決方案:

def slope(X,Y,i): 
    res = (Y[i]-Y[0])*1.0/(X[i]-X[0]) 
    return res 

len_thold=0.2 

def notgood(lst1,lst2): 
    if len(lst1)<2 or len(lst2)<2: 
     return True 
    return False 

def adjust_miss(X,Y): 
    slope_thold=1.1 
    if len(X)==len(Y): 
     return 
    newlen=min(len(X),len(Y)) 
    if len(Y)-len(X)<0: 
     aim=X 
    else: 
     aim=Y 
    difflen=abs(len(Y)-len(X)) 
    roughk=slope(X,Y,newlen-1) 
    for i in xrange(1,newlen): 
     if difflen==0: 
      break 
     k=slope(X,Y,i) 
     if (len(Y)<len(X) and k>slope_thold*roughk) or (len(Y)>len(X) and k<1.0/(slope_thold*roughk)): 
      aim.pop(i) 
      difflen-=1 
    if difflen>0: 
     for i in xrange(difflen): 
      aim.pop(-1) 
    assert len(X) == len(Y) 

def test_adjust(): 
    X=range(10) 
    Y=range(10) 
    Y.pop(3) 
    adjust_miss(X,Y) 
    print X,Y 
1

我假設你知道其中的x的與Y的缺少的元素有關。

在這種情況下,由於您想估計x的已知位置的y值,因此您有一個轉換式學習問題。

在概率線性迴歸公式中,學習一個分佈p(y | x),結果表明轉導性解與通過在沒有關聯y的情況下移除x之後運行迴歸得到的答案沒有差異。

所以答案是 - 只是刪除沒有關聯y的x,並對減少的問題運行線性迴歸。

2

我怕你會在你的製作缺失值的方法煩惱:

y=[i*3+5 for i in x] 
y.pop(3) #make a missing 

你特別希望使3元丟失,但現在發生了什麼?你應該如何告訴你的劇本,其實最初的第三個元素是不存在的?

我建議將您的缺失值標記爲np.nan(當然,前提是它們都是浮動的)。然後,找出哪些值丟失很簡單:

missing = np.isnan(y) 

現在,你可以刪除其中y缺少的xA項,其中ynp.nan

Anew = A[~missing] 
ynew = y[~missing] 

m, c = np.linalg.lstsq(Anew, ynew)[0] 
print m, c 

(中~運營商將您的True轉換爲False,反之亦然:您正在選擇y而非np.nan

如果您的y實際上是整數,那將不起作用,因爲np.nan僅適用於浮點數。然後您可以使用np.ma模塊。

my = np.ma.masked_array(y) 
my[3] = np.ma.masked 

Anew = A[~my.mask] 
ynew = my.compressed() 

m, c = np.linalg.lstsq(Anew, ynew)[0] 
print m, c 
+0

問題,任何位置可能會丟失。我不知道它是3. 3'rd似乎可能會丟失。或者在遍歷所有可能性之後,缺少3將導致完全匹配。 – whi