2016-10-03 70 views
0

所以,我不完全確定這裏發生了什麼,但是無論出於何種原因,Python都在向我拋出這個。作爲參考,它是我構建的一個小型神經網絡的一部分,但它使用了大量的np.array等,所以有很多矩陣被拋出,所以我認爲它創建了某種數據類型衝突。也許有人可以幫我弄清楚這一點,因爲我一直盯着這個錯誤太久,卻無法修復它。Python,元組索引必須是整數,而不是元組?

#cross-entropy error 
#y is a vector of size N and output is an Nx3 array 
def CalculateError(self, output, y): 

    #calculate total error against the vector y for the neurons where output = 1 (the rest are 0) 
    totalError = 0 
    for i in range(0,len(y)): 
     totalError += -np.log(output[i, int(y[i])]) #error is thrown here 

    #now account for regularizer 
    totalError+=(self.regLambda/self.inputDim) * (np.sum(np.square(self.W1))+np.sum(np.square(self.W2)))  

    error=totalError/len(y) #divide ny N 
    return error 

編輯:這裏的函數返回的輸出,所以你知道從哪裏來。 y是直接從文本文檔中獲取的長度爲150的矢量。 Y的每個索引在它包含一個索引或者1,2,或3:

#forward propogation algorithm takes a matrix "X" of size 150 x 3 
def ForProp(self, X):    
     #signal vector for hidden layer 
     #tanh activation function 
     S1 = X.dot(self.W1) + self.b1 
     Z1 = np.tanh(S1) 

     #vector for the final output layer 
     S2 = Z1.dot(self.W2)+ self.b2 
     #softmax for output layer activation 
     expScores = np.exp(S2) 
     output = expScores/(np.sum(expScores, axis=1, keepdims=True)) 
     return output,Z1 
+1

它看起來像'output'並不是真正的NX4陣列像你認爲它是。 – user2357112

+2

請包括完整的引用。 –

+1

如何保證y [i]在範圍[0,3]內?這似乎是你的問題。這可能是一個徹頭徹尾的錯誤,或者是需要在體系結構中固定的bandaid。 – Harrichael

回答

4

output變量不是N x 4矩陣,在Python類型感至少不是。它是一個元組,它只能被一個單一的數字索引,並且你試圖通過元組索引(兩個數字之間有昏迷),它只適用於numpy矩陣。打印你的輸出,找出問題是否只是一個類型(然後只是轉換爲np.array),或者如果你傳遞了完全不同的東西(然後修復生成的所有東西)。發生了什麼

例子:

import numpy as np 
output = ((1,2,3,5), (1,2,1,1)) 

print output[1, 2] # your error 
print output[(1, 2)] # your error as well - these are equivalent calls 

print output[1][2] # ok 
print np.array(output)[1, 2] # ok 
print np.array(output)[(1, 2)] # ok 
print np.array(output)[1][2] # ok 
相關問題