【问题标题】:Python, tuple indices must be integers, not tuple?Python,元组索引必须是整数,而不是元组?
【发布时间】:2017-02-11 20:04:41
【问题描述】:

所以,我不完全确定这里发生了什么,但无论出于何种原因,Python 都会向我抛出这个问题。作为参考,它是我为了好玩而构建的一个小型神经网络的一部分,但它使用了很多 np.array 等,所以有很多矩阵被抛出,所以我认为它正在创建某种数据类型冲突.也许有人可以帮我解决这个问题,因为我一直盯着这个错误太久而无法修复它。

#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

【问题讨论】:

  • 看起来 output 实际上并不像你想象的那样是一个 Nx4 数组。
  • 请附上完整的引用。
  • 如何保证 y[i] 在 [0,3] 范围内?这似乎是你的问题。这要么是彻头彻尾的错误,要么是需要在架构中修复的创可贴。
  • 你如何处理ForProp 的结果?它返回一个元组,可能你正在传递生成的内容,它是由output Z1组成的元组,我猜你有类似output = ForProp( .. )的东西应该是output, Z1 = ForProp( ... )

标签: python indexing types tuples


【解决方案1】:

您的output 变量不是N x 4 矩阵,至少在python 类型 意义上不是。它是一个元组,只能由单个数字索引,并且您尝试按元组(2 个数字,中间有逗号)进行索引,这仅适用于 numpy 矩阵。打印您的输出,确定问题是否只是一种类型(然后只需转换为 np.array),或者您传递的内容是否完全不同(然后修复产生 output 的任何内容)。

正在发生的事情的示例:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    相关资源
    最近更新 更多