yyPurpose_forever 2018-10-20 12:15 采纳率: 0%
浏览 2249

如何解决python中softmax损失函数计算时的溢出问题?

     def loss(self,X,y,reg):
        loss = 0.0
        dW = np.zeros_like(self.W)

        num_train = X.shape[0]
        num_class = self.W.shape[1]

        one_hot = np.zeros(shape = (num_train,num_class))
        y = y.astype('int64')
        one_hot[np.arange(0,num_train), y] = 1  

        Z = X.dot(self.W)
        Z_max = np.max(Z,axis = 1,keepdims = True) #Z_max = Z.max(1).reshape(num_train,1)
        Z = Z - Z_max  #max(1) get the maxmum of each row
        score_E = np.exp(Z)
        Sum = np.sum(score_E,axis = 1,keepdims = True)#score_E.sum(axis = 1).reshape(num_train,1)  # sum of each row
        A = score_E/Sum   #score of every class of each training_example
        A1 = np.where(A > 0.0000000001, A, 0.0000000001)
        loss += -np.sum(one_hot*np.log(A1))/num_train + 0.5 * reg * np.sum(self.W * self.W)
        dW += -np.dot(X.T, one_hot - A) / num_train + reg * self.W
        return loss,dW   

以上是我用python写的softmax的损失函数部分,但是在运行过程中发现输出里有时仍有这样的情况
图片说明

我只对图片做了零均值化,没有归一化,但是Z = Z - Z_max 溢出就说不通啊,这是怎么回事,有没有大神解释??

  • 写回答

2条回答

  • threenewbee 2018-10-20 16:34
    关注

    softmax你算的不对,公式你看下:https://www.cnblogs.com/liuyu124/p/7332476.html
    它必然是0~1之间的,不可能溢出

    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题