常用的損失函數
分類問題:交叉熵 (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