1. import numpy as np
    2. # MSE Loss
    3. def mse(y, t):
    4. return 0.5*np.sum((y-t)**2)
    5. t=[0,1,1,0,0]
    6. y=[0,0.4,0.73,0.04,0.25]
    7. print(mse(y,t))
    8. # Cross Entropy Loss
    9. def CELoss(y, t):
    10. # 防止传入 log 的输入为0
    11. delta = 1e - 7
    12. return -np.sum(t*np.log(y+delta))
    13. # mini batch版本
    14. def CELoss(y, t):
    15. if y.dim == 1:
    16. # 转为二维
    17. t = t.reshape(1, t.size)
    18. y = y.reshape(1, y.size)
    19. batch_size = y.shape[0]
    20. return -np.sum(t*np.log(y+1e-7))/batch_size