2016-10-03 157 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 
相关问题