2017-02-26 155 views
1

我現在正在做線性迴歸分析。輸入變量是Size。輸出變量是Price。我將這組數據存儲在二維數組中。我知道使用NumPy很容易進行分析,但我的教授告訴我只用循環來執行迭代。 Formula of interation is shown as the picture in the hyperlink。因此,我決定下面的代碼來執行計算:簡單線性迴歸使用for循環只能用於Python

#Structure of array (Stored in float), with structure like this [Room, Price] 
array = [[4.0, 399.9], [5.0, 329.9], [6.0, 369.0]] 

#Set initial value 
theta_price = 0 
theta_room = 0 
stepsize = 0.01 
item = 3 

#Perform iterations 
for looping in range(0, 50): #Loop 50 times 
    for j in array[0]: #Call the value stored in array[0] 
     for k in array[1]: #Call the value stored in array[1] 
      theta_price_1 = theta_price - stepsize * (1/item) * (sum((theta_price + theta_room * int(j) - int(k)))#Perform iterations of theta 0 
      theta_room_1 = theta_room - stepsize * (1/item) * (sum((theta_price + t + theta_room * int(j) - int(k))*int(j)))#Perform iterations of theta 1 
      #Bring the new theta value to the next loop 
      theta_price = theta_price_1 
      theta_room = theta_room_1 
      print(theta_price,theta_room)#Print the result for every loop 

上面的代碼,錯誤消息在線路10沒有起作用的是:

'int' object is not iterable 

但是如果刪除的總和函數,它的工作原理計算結果不正確。因此,我知道它的sum函數和數組有一些問題,但我不知道如何解決它?

+0

在每次迭代中,'sum'應該應用於所有'x'和'y','array [0]'和'arrary [1]',但不是其中的一個。 – zsrkmyn

回答

0

正如我在評論中提到的,sum應該適用於每次迭代中的所有元素,這就是批處理梯度下降的作用。因此,代碼應該是:

theta_price = 0 
theta_room = 0 
stepsize = 0.1 
item = 5 
#Perform iterations 
array = [ 
      [0,1,2,3,4], 
      [5,6,7,8,9], 
     ] 

for looping in range(0, 500): #Loop 50 times 
     theta_price = theta_price - stepsize * (1/item) * (sum([theta_price + theta_room * int(j) - int(k) for j, k in zip(array[0], array[1])]))#Perform iterations of theta 0 
     theta_room = theta_room - stepsize * (1/item) * (sum([(theta_price + theta_room * int(j) - int(k)) * int(j) for j, k in zip(array[0], array[1])]))#Perform iterations of theta 1 
     print(theta_price,theta_room)#Print the result for every loop 

經過500次迭代的5個測試數據,我可以得到結果:

4.999999614653767 1.0000001313279816 

這也在意料之中。

+0

謝謝您的回答,但是,如果數組是二維數組,則答案不正確。我剛剛添加了數組的格式以供參考。我試圖通過以下方式改進答案: 對於j [0],k [0]在數組 進行此更改的原因是,使用此格式查找「for a in array」時的意思似乎很有用。然而,錯誤信息與預期的縮進塊一起出現。如何更改答案以適應我的情況。 –

+0

然後你可以使用'numpy.array'來方便。 – zsrkmyn

+0

正如我所提到的,我不想盡可能多地使用NumPy,我想修改for循環來申請我的數組。 –