【问题标题】:SoftMax derivative calculation: Error: 'numpy.float64' object does not support item assignmentSoftMax 导数计算:错误:“numpy.float64”对象不支持项目分配
【发布时间】:2021-02-14 12:07:33
【问题描述】:

我正在尝试计算 SoftMax 函数的导数,但我无法调用它来消除下面提到的错误。

def softmax_grad(self,s):
    print('s.shape:',s.shape)
    jacobian_m = np.diag(s)
    print('jacobian_m:',jacobian_m.ndim)
    for i in range(len(jacobian_m)):
        print('i:',i)
        for j in range(len(jacobian_m)):
            print('j:',j)
            if i == j:
                jacobian_m[i][j] = s[i] * (1-s[i])
            else:
                jacobian_m[i][j] = -s[i]*s[j]
    return jacobian_m

def train(self, inputs, targets, eta, niterations):
    ndata = np.shape(inputs)[0] # number of data samples 
    # adding the bias
    inputs = np.concatenate((inputs,-np.ones((ndata,1))),axis=1)
    
    # numpy array to store the update weights 
    updatew1 = np.zeros((np.shape(self.weights1))) 
    updatew2 = np.zeros((np.shape(self.weights2)))
    updatew3 = np.zeros((np.shape(self.weights3)))
    
   
    for n in range(niterations):   
        # forward phase 
        self.outputs = self.forwardPass(inputs)
  
    
        # Error using the sum-of-squares error function
        error = 0.5*np.sum((self.outputs-targets)**2)
   
        if (np.mod(n,100)==0):
            print("Iteration: ",n, " Error: ",error)
    
            deltao = self.sigmoid_derivative(self.outputs)
            print('delto :',deltao)

运行以下代码后,我遇到了一个错误
TypeError: 'numpy.float64' object does not support item assignment

【问题讨论】:

  • 错误出现在哪里?我们不喜欢猜测!
  • 在softmax_grad函数的下面一行:jacobian_m[i][j] = s[i] * (1-s[i])
  • S的形状是什么?
  • jacobian_m 没有足够的维度来索引 2 层
  • @M.Soyturk s.shape: (9000, 10)

标签: python numpy neural-network artificial-intelligence linear-algebra


【解决方案1】:

np.diag 如果参数是二维数组(在您的情况下为“s”),则返回由给定参数的对角元素组成的一维数组。这就是为什么当您尝试获取 ndim 时会收到 1。因此,您的 jacobian_m 变量是一维数组,而您正试图像使用二维数组一样使用它,这会导致错误。

【讨论】:

  • 我重塑了jacobian_m ,现在是 (2,4500)。但它抛出了一个错误 “assignment destination is read-only” 所以我尝试了这个 jacobian_m .setflags(write=1) 现在它显示 ValueError: setting an array element with a sequence.跨度>
  • 如错误所示,您正在尝试将序列(列表)写入数组元素。这是不允许的。
猜你喜欢
  • 2019-01-03
  • 1970-01-01
  • 2023-02-26
  • 2019-11-14
  • 2012-01-22
  • 2017-11-18
  • 1970-01-01
  • 2018-09-02
  • 1970-01-01
相关资源
最近更新 更多