交叉熵函数(python)

时间:2017-11-19 13:08:53

标签: python machine-learning neural-network cross-entropy

我正在学习神经网络,我想在python中编写一个函数cross_entropy。在哪里定义为

cross entropy

其中N是样本数,k是类的数量, log 是自然对数,t_i,j是1如果样本i在课程j中,而0则为p_i,j,而i是样本j在课程[10^{−12}, 1 − 10^{−12}]中的预测概率。 要避免使用对数的数字问题,请将预测剪切为[epsilon, 1 − epsilon]范围。

根据上面的描述,我通过clippint将代码记录到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_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)) 是否正确。

cross_entropy

上述代码的输出为False,即我定义函数cross_entropy(predictions, targets)的代码不正确。然后我打印0.178389544455的结果。它提供了ans = 0.71355817782,正确的结果应为<?php $string = '<a title="Link 01" href="http://www.mywebsite.com.br/?id=121451781">Link 01</a>'; $l = new SimpleXMLElement($string); $old_href = $l['href']; $new_href = str_replace("1","*",$l['href']); $new_string = str_replace($old_href,$new_href,$string); print($new_string); 。有人可以帮我查一下我的代码有什么问题吗?

2 个答案:

答案 0 :(得分:13)

你根本没有那么远,但记住你正在取N个和的平均值,其中N = 2(在这种情况下)。所以你的代码可以读取:

np.sum()

在这里,如果你坚持使用np.log(),我认为它会更清楚一些。另外,我在1e-9中添加了1e-9,以避免计算中出现log(0)的可能性。希望这有帮助!

注意:根据@ Peter的评论,如果你的epsilon值大于0,{{1}}的偏移确实是多余的。

答案 1 :(得分:2)

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))