2014-01-28 31 views
0

我試圖實現感知器算法,但得到不一致的結果;我注意到權重的初始化產生了很大的影響。有什麼我公然做錯了嗎?謝謝!Perceptron算法的結果不一致

import numpy as np 

def train(x,y): 

    lenWeights = len(x[1,:]); 
    weights = np.random.uniform(-1,1,size=lenWeights) 
    bias = np.random.uniform(-1,1); 
    learningRate = 0.01; 
    t = 1; 
    converged = False; 

# Perceptron Algorithm 

while not converged and t < 100000: 
    targets = []; 
    for i in range(len(x)): 

      # Calculate output of the network 
      output = (np.dot(x[i,:],weights)) + bias; 

      # Perceptron threshold decision 
      if (output > 0): 
       target = 1; 
      else: 
       target = 0; 

      # Calculate error and update weights 
      error = target - y[i]; 

      weights = weights + (x[i,:] * (learningRate * error)); 

      bias = bias + (learningRate * error); 

      targets.append(target); 

      t = t + 1; 

    if (list(y) == list(targets)) == True: 
     converged = True; 


return weights,bias 

def test(weights, bias, x): 

    predictions = []; 

    for i in range(len(x)): 

     # Calculate w'x + b 
     output = (np.dot(x[i,:],weights)) + bias; 

     # Get decision from hardlim function 
     if (output > 0): 
      target = 1; 
     else: 
      target = 0; 

     predictions.append(target); 

    return predictions 

if __name__ == '__main__': 

    # Simple Test 

    x = np.array([ [0,1], [1,1] ]); 
    y = np.array([ 0, 1 ]); 

    weights,bias = train(x,y); 
    predictions = test(weights,bias,x); 

    print predictions 
    print y 
+0

結果不一致的方式是什麼?你發現對重量的依賴是什麼?我猜在'while'也有一個縮進錯誤。 – Nabla

+0

有時它會輸出正確的標籤,有時卻不會,隨機排序 – rahulm

回答

0

感知是全局優化,使培訓效果不會是一致的(他們可以在每次運行你的算法時間變化),以及它的權重初始化取決於(其中包括)。這是非凸函數梯度優化的特徵(對感知器進行微調是一個例子),而不是實現問題。

+0

@lejlot所討論的代碼是一個簡單的二元單層感知器。如果訓練集是線性可分的,我認爲它應該總是在全球範圍內收斂,如果不是,那麼它就不會收斂。有關的代碼實際上幾乎不會收斂。提問者用't <100000'測試掩蓋了這一點。我也認爲訓練集是線性可分的。我錯了嗎? – Nabla

+0

你說得對,我的確假設了更復雜的模型(MLP)。我會刪除答案,但第一作者必須「解答」它。 – lejlot

+0

是的,這是一個簡單的錯誤,我在這行代碼上的體重更新: 'error = target - y [i]'; 它應該是: 'error ='y [i] - target'; 這解決了我的問題;它現在總是返回正確的結果,因爲Nabla提到,因爲訓練集是線性可分的。 – rahulm