【bug解决】类中函数方法的相互调取

Rachel MuZy · 收录于 2023-11-21 05:03:18 · source URL

目录

项目场景:

问题描述

解决方案:


项目场景:

Python的类中函数方法如何实现相互调用


问题描述

import numpy as np


class SoftmaxWithLoss:
    def __init__(self):
        self.loss = None #损失
        self.y = None #softmax的输出
        self.t = None #监督数据
        
    
    def softmax(a):
        exp_a = np.exp(a)
        sum_a = np.sum(exp_a)
        soft = exp_a / sum_a
        
        return soft
    
    
    def cross_entropy_error(y, t):
        delta = 1e-7
        E = -np.sum(t * np.log(y + delta), axis = 1)
        
        return E
    

    def forward(self, x, t):
        self.t = t
        self.y = softmax(x)  
        self.loss = cross_entropy_error(self.y, self.t) 
        
        return self.loss
    
    
    def backward(self, dout=1):
        batch_size = self.t.shape[0]
        dx = (self.y - self.t) / batch_size
        
        return dx

会出现两行报错:

 如何解决该问题呢?

 


解决方案:

import numpy as np


class SoftmaxWithLoss:
    def __init__(self):
        self.loss = None #损失
        self.y = None #softmax的输出
        self.t = None #监督数据
        
    
    def softmax(a):
        exp_a = np.exp(a)
        sum_a = np.sum(exp_a)
        soft = exp_a / sum_a
        
        return soft
    
    
    def cross_entropy_error(y, t):
        delta = 1e-7
        E = -np.sum(t * np.log(y + delta), axis = 1)
        
        return E
    

    def forward(self, x, t):
        self.t = t
        self.y = SoftmaxWithLoss.softmax(x)  
        self.loss = SoftmaxWithLoss.cross_entropy_error(self.y, self.t) 
        
        return self.loss
    
    
    def backward(self, dout=1):
        batch_size = self.t.shape[0]
        dx = (self.y - self.t) / batch_size
        
        return dx

问题解决。