常用的损失函数
分类问题:交叉熵 (CE,Cross Entropy)
回归问题:均方根误差 (MSE,Mean Square Error)
以一个简单的例子实现自定义loss
假设某商品销售金额仅由变量x1和x2确定(y=x1+x2+噪声)
用到以下tf函数:
tf.where(条件,a,b) # 条件为真返回a,条件为假返回b
tf.greater(a,b) # 比大小,a>b 返回真,a<=b 返回假
代码:
import tensorflow as tf
import numpy as np
seed = 6
cost = 1
profit = 99
rdm = np.random.RandomState(seed)
x = rdm.rand(32, 2)
y_ = [[x1 + x2 + (rdm.rand() / 10.0 - 0.05)] for (x1, x2) in x] # 生成噪声
x = tf.cast(x, dtype=tf.float32)
w = tf.Variable(tf.random.normal([2, 1], stddev=1, seed=1))
epoch = 10000
lr = 0.002
for epoch in range(epoch):
with tf.GradientTape() as tape:
y = tf.matmul(x, w)
# loss = tf.reduce_mean(tf.square(y_ - y)) 均方根误差损失函数
loss = tf.reduce_sum(tf.where(tf.greater(y, y_), (y - y_) * cost, (y_ - y) * profit)) # 自定义损失函数,greater为比大小函数
grads = tape.gradient(loss, w)
w.assign_sub(lr * grads)
if epoch % 500 == 0:
print("After %d training steps,w is " % (epoch))
print(w.numpy(), "\n")
print("Final w is: ", w.numpy())
若不考虑 成本cost 和 利润profit,以均方根误差为损失函数,训练结果如下:
十分接近预先设置的 y=x1+x2
若考虑成本和利润,多生产亏钱,少生产少赚钱
假设商品成本为1,利润为99(暴利),按理说多生产一些更好,用自定义损失函数训练结果如下:
符合预先设想,x1和x2均大于1