美文网首页
[Machine Learning From Scratch]-

[Machine Learning From Scratch]-

作者: 六千宛 | 来源:发表于2021-06-27 21:09 被阅读0次

    损失函数定义

    from __future__ import division
    import numpy as np
    from mlfromscratch.utils import accuracy_score
    from mlfromscratch.deep_learning.activation_functions import Sigmoid
    
    class Loss(object):
        def loss(self, y_true, y_pred):
            return NotImplementedError()
    
        def gradient(self, y, y_pred):
            raise NotImplementedError()
    
        def acc(self, y, y_pred):
            return 0
    
    class SquareLoss(Loss):
        def __init__(self): pass
    
        def loss(self, y, y_pred):
            return 0.5 * np.power((y - y_pred), 2)
    
        def gradient(self, y, y_pred):
            return -(y - y_pred)
    
    class CrossEntropy(Loss):
        def __init__(self): pass
    
        def loss(self, y, p):
            # Avoid division by zero
            p = np.clip(p, 1e-15, 1 - 1e-15)
            return - y * np.log(p) - (1 - y) * np.log(1 - p)
    
        def acc(self, y, p):
            return accuracy_score(np.argmax(y, axis=1), np.argmax(p, axis=1))
    
        def gradient(self, y, p):
            # Avoid division by zero
            p = np.clip(p, 1e-15, 1 - 1e-15)
            return - (y / p) + (1 - y) / (1 - p)
    

    相关文章

      网友评论

          本文标题:[Machine Learning From Scratch]-

          本文链接:https://www.haomeiwen.com/subject/cttfultx.html