损失函数(loss):预测值(y)与已知答案(y_)的差距,优化目标loss最小
以下1与2两个案例的loss函数都是针对酸奶日销量案例
1、均方误差mse损失函数
import tensorflow as tf
import numpy as np
###拟合的是y = x1 + x2的函数
SEED = 2333
rdm = np.random.RandomState(seed=SEED) # 生成0至1不包含1之间的随机数
x = rdm.rand(32, 2)#生成32行 2列的特征
###生成噪声[0, 1) / 10 = [0, 0.1); 添加点噪声使结果更真实
y_ = [[x1 + x2 + (rdm.rand() / 10.0 - 0.05)] for (x1, x2) in x]
x = tf.cast(x, dtype=tf.float32)#转换数据类型
###这里随机初始化参数w1 2行 1列, 后面会迭代更新
w1 = tf.Variable(tf.random.normal([2, 1], stddev=1, seed=1))
epoch = 15000
lr = 0.002
for epoch in range(epoch):
with tf.GradientTape() as tape:
y = tf.matmul(x, w1)
###tf.reduce_mean(tf.square(y_ - y))求的是均方误差
loss_mse = tf.reduce_mean(tf.square(y_ - y))
grads = tape.gradient(loss_mse, w1)#对w1求偏导
###更新w1
w1.assign_sub(lr * grads)
##每500次打印一下
if epoch % 500 == 0: