Python 我的交叉熵函数的实现有什么问题?

Python 我的交叉熵函数的实现有什么问题?,python,machine-learning,neural-network,cross-entropy,Python,Machine Learning,Neural Network,Cross Entropy,我正在学习神经网络,我想用python编写一个函数cross\u entropy。定义为 其中,N是样本数,k是类数,log是自然对数,t\u i,j是1,如果样本i在类j中,否则0则是类数,p\u i,j是样本i在类j中的预测概率。 为了避免对数的数值问题,请将预测剪辑到[10]^{−12}, 1 − 10^{−12} ]范围 根据上面的描述,我通过将预测裁剪到[epsilon,1]来写下代码− ε]范围,然后根据上述公式计算交叉熵 def cross_entropy(predictions

我正在学习神经网络,我想用python编写一个函数
cross\u entropy
。定义为

其中,
N
是样本数,
k
是类数,
log
是自然对数,
t\u i,j
是1,如果样本
i
在类
j
中,否则
0
则是类数,
p\u i,j
是样本
i
在类
j
中的预测概率。 为了避免对数的数值问题,请将预测剪辑到
[10]^{−12}, 1 − 10^{−12} ]
范围

根据上面的描述,我通过将预测裁剪到
[epsilon,1]来写下代码− ε]
范围,然后根据上述公式计算交叉熵

def cross_entropy(predictions, targets, epsilon=1e-12):
    """
    Computes cross entropy between targets (encoded as one-hot vectors)
    and predictions. 
    Input: predictions (N, k) ndarray
           targets (N, k) ndarray        
    Returns: scalar
    """
    predictions = np.clip(predictions, epsilon, 1. - epsilon)
    ce = - np.mean(np.log(predictions) * targets) 
    return ce
以下代码将用于检查函数
cross\u entropy
是否正确

predictions = np.array([[0.25,0.25,0.25,0.25],
                        [0.01,0.01,0.01,0.96]])
targets = np.array([[0,0,0,1],
                  [0,0,0,1]])
ans = 0.71355817782  #Correct answer
x = cross_entropy(predictions, targets)
print(np.isclose(x,ans))

上述代码的输出是错误的,也就是说我定义函数
交叉熵的代码是不正确的。然后我打印交叉熵(预测、目标)的结果。它给出了
0.17838954455
,正确的结果应该是
ans=0.71355817782
。有人能帮我检查一下我的代码有什么问题吗?

你一点也不远,但请记住你取的是N个和的平均值,其中N=2(在本例中)。因此,您的代码可以读取:

def cross_entropy(predictions, targets, epsilon=1e-12):
    """
    Computes cross entropy between targets (encoded as one-hot vectors)
    and predictions. 
    Input: predictions (N, k) ndarray
           targets (N, k) ndarray        
    Returns: scalar
    """
    predictions = np.clip(predictions, epsilon, 1. - epsilon)
    N = predictions.shape[0]
    ce = -np.sum(targets*np.log(predictions+1e-9))/N
    return ce

predictions = np.array([[0.25,0.25,0.25,0.25],
                        [0.01,0.01,0.01,0.96]])
targets = np.array([[0,0,0,1],
                   [0,0,0,1]])
ans = 0.71355817782  #Correct answer
x = cross_entropy(predictions, targets)
print(np.isclose(x,ans))
在这里,我认为如果您坚持使用
np.sum()
,会更清楚一些。另外,我在
np.log()
中添加了1e-9,以避免在计算中出现日志(0)。希望这有帮助

注:根据@Peter的评论,
1e-9
的偏移量确实是多余的,如果ε值大于
0

def cross\u熵(x,y):
def cross_entropy(x, y):
    """ Computes cross entropy between two distributions.
    Input: x: iterabale of N non-negative values
           y: iterabale of N non-negative values
    Returns: scalar
    """

    if np.any(x < 0) or np.any(y < 0):
        raise ValueError('Negative values exist.')

    # Force to proper probability mass function.
    x = np.array(x, dtype=np.float)
    y = np.array(y, dtype=np.float)
    x /= np.sum(x)
    y /= np.sum(y)

    # Ignore zero 'y' elements.
    mask = y > 0
    x = x[mask]
    y = y[mask]    
    ce = -np.sum(x * np.log(y)) 
    return ce

def cross_entropy_via_scipy(x, y):
        ''' SEE: https://en.wikipedia.org/wiki/Cross_entropy'''
        return  entropy(x) + entropy(x, y)

from scipy.stats import entropy, truncnorm

x = truncnorm.rvs(0.1, 2, size=100)
y = truncnorm.rvs(0.1, 2, size=100)
print np.isclose(cross_entropy(x, y), cross_entropy_via_scipy(x, y))
“”“计算两个分布之间的交叉熵。 输入:x:N个非负值的可比性 y:N个非负值的可比性 返回:标量 """ 如果np.any(x<0)或np.any(y<0): raise VALUERROR('存在负值') #力到适当的概率质量函数。 x=np.array(x,dtype=np.float) y=np.array(y,dtype=np.float) x/=np.和(x) y/=np.和(y) #忽略零个“y”元素。 掩码=y>0 x=x[遮罩] y=y[遮罩] ce=-np.sum(x*np.log(y)) 返回ce def交叉熵通过scipy(x,y): ''见:https://en.wikipedia.org/wiki/Cross_entropy''' 返回熵(x)+熵(x,y) 从scipy.stats导入熵,truncnorm x=truncnorm.rvs(0.1,2,尺寸=100) y=truncnorm.rvs(0.1,2,尺寸=100) 打印np.isclose(交叉熵(x,y),交叉熵通过交叉熵(x,y))
是否有任何预先构建的交叉熵函数,将logits和预测作为输入并输出成本?嘿,@Kalpit。应在
sklearn
库中构建
日志损失
交叉熵损失
方法。这里有一个链接:。