均方差损失函数求误差及梯度

均方差损失函数求误差及梯度

完整源码可戳:https://github.com/AKGWSB/Convolution-Neural-Network-Frame-only-based-on-Numpy-/blob/master/Loss.py

损失函数表达式

即 输出减去目标的平方再乘以二分之一

MSE = 1/2 * (output - target)^2

求梯度

均方差损失函数的求导相对简单,二分之一会和二约掉,
即 梯度 = 输出 - 目标

gradient = output - target

离散情况

如果目标,输出是向量:
output = (0.1, 0.2, 0,33)
target = (0.2, 0.1, 0.43)

  • 损失其实是向量各个位做均方差之后结果加和,可以利用python中numpy的直接加减实现

error = 1/2 * [ (0.2 - 0.1)^2 + (0.1 - 0.2)^2 + (0.43 - 0.33)^2 ]

python实现

import numpy as np

class Mean_squared_error:

    def __init__(self):
        pass

    def get_error(self, output, target):
        self.output = output
        self.target = target
        return 0.5 * np.sum((output - target) * (output - target))

    def get_gradient(self):
        return (self.output - self.target)
发布了18 篇原创文章 · 获赞 0 · 访问量 126

猜你喜欢

转载自blog.csdn.net/weixin_44176696/article/details/103992521