L1, L2, smooth_L1 Loss函数python实现

L1, L2, smooth_L1函数python实现

L1 loss

def L1(y_gt, y_pre):
    loss = np.sum(np.abs(y_gt - y_pre))
    print(loss)

    # 画图
    x = np.arange(-10,11,0.1)
    y = abs(x)
    dy = np.where(x>0, 1, -1)
    plt.plot(x, y, label="l1")
    plt.plot(x, dy, label="l1'")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.show()


if __name__ == "__main__":
    y_gt = np.arange(1, 11)
    y_pre  = np.array([1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,13.13])
    L1(y_gt, y_pre)
    L2(y_gt, y_pre)
    smooth_l1(y_gt, y_pre)

L2 loss

def L2(y_gt, y_pre):
    loss = np.sum(np.square(y_gt - y_pre))
    print(loss)
    
    # 画图
    x = np.arange(-10,11,0.1)
    y = (1/2) * (x)**2
    dy = x
    plt.plot(x, y, label="l2")
    plt.plot(x, dy, label="l2'")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.show()


if __name__ == "__main__":
    y_gt = np.arange(1, 11)
    y_pre  = np.array([1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,13.13])
    L1(y_gt, y_pre)
    L2(y_gt, y_pre)
    smooth_l1(y_gt, y_pre)

smooth_l1 loss

论文地址:Fast R-CNN

def smooth_l1(y_gt, y_pre):
    select = y_gt - y_pre
    loss = np.where(abs(select) < 1, 0.5*select**2, abs(select)-0.5)
    loss = np.sum(loss)

    # 画图
    x = np.arange(-10,11,0.1)
    y = []
    for xx in x:
        if xx > -1 and xx < 1:
            y.append(0.5*xx**2)
        else:
            y.append(abs(xx)-0.5)E
    dy = []
    for xx in x:
        if xx > -1 and xx < 1:
            dy.append(xx)
        elif xx <= -1:
            dy.append(-1)
        else:
            dy.append(1)
    plt.plot(x, y, label="smooth l1")
    plt.plot(x, dy, label="smooth l1'")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.show()
   

if __name__ == "__main__":
    y_gt = np.arange(1, 11)
    y_pre  = np.array([1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,13.13])
    L1(y_gt, y_pre)
    L2(y_gt, y_pre)
    smooth_l1(y_gt, y_pre)

你可能感兴趣的:(python,开发语言)