-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3.损失函数与目的.py
49 lines (43 loc) · 1.34 KB
/
3.损失函数与目的.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import numpy as np
class Loss(object):
def mean_absolute_loss(self,y_hat,y,n):
"""
平均绝对误差损失
:param y_hat: 预测结果
:param y: 真实结果
:param n: 样本数量
:return: 损失函数计算结果
"""
########## Begin ##########
loss = abs(y_hat - y)
loss = np.sum(loss) / n
########## End ##########
return loss
def mean_squared_loss(self,y_hat,y,n):
"""
均方差损失
:param y_hat: 预测结果
:param y: 真实结果
:param n: 样本数量
:return: 损失函数计算结果
"""
########## Begin ##########
loss = (y_hat - y) ** 2
loss = np.sum(loss) / n
########## End ##########
return loss
def cross_entropy_loss(self,y_hat,y,n):
"""
交叉熵损失
:param y_hat: 预测结果
:param y: 真实结果
:param n: 样本个数
:return: 损失函数计算结果
"""
########## Begin ##########
# loss = -np.sum(y*np.log(y_hat)) + (1-y)*np.log(1-y_hat)
loss = y_hat * np.log2(y) + (1 - y) * np.log2(1 - y)
loss = np.sum(loss)
loss = loss / (-n)
########## End ##########
return loss