Tensorflow之损失函数与交叉熵

损失函数:预测值与已知答案之间的差距

NN优化目标:loss最小{mse, 自定义, ce)

均方误差tensorflow实现,loss_mse = tf.reduce_mean(tf.sqrue(y_-y)

预测酸奶日销量,y,x1, x2是影响日销量的因素

建模前,应预先采集每日x1,x2,和效率y

拟造数据集x,y:y_=x1 + x2 ,噪声 -0.05-+0.05

复制代码
import tensorflow as tf
import numpy as np

SEED = 2345

rdm = np.random.RandomState()
x = rdm.rand(32,2) # 生成32行两列之间的数字
y_ = [[x1 + x2 + (rdm.rand()/10.0 - 0.05)] for (x1, x2) in x] #0.1-0.05=0.005
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)
        loss_mse = tf.reduce_mean(tf.square(y_ - y))
    grads = tape.gradient(loss_mse, w1)
    w1.assign_sub(lr * grads) #更新参数

使用均方误差,预测多和预测少是一样的

预测多了,损失成本,预测少了,损失利润,利润不等于成本

自定义损失函数 loss(y_, y) =

复制代码
import tensorflow as tf
import numpy as np

SEED = 23455
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]  # 生成噪声[0,1)/10=[0,0.1); [0,0.1)-0.05=[-0.05,0.05)
x = tf.cast(x, dtype=tf.float32)

w1 = 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, w1)
        loss = tf.reduce_sum(tf.where(tf.greater(y, y_), (y - y_) * COST, (y_ - y) * PROFIT))

    grads = tape.gradient(loss, w1)
    w1.assign_sub(lr * grads)

    if epoch % 500 == 0:
        print("After %d training steps,w1 is " % (epoch))
        print(w1.numpy(), "\n")
print("Final w1 is: ", w1.numpy())

# 自定义损失函数
# 酸奶成本1元, 酸奶利润99元
# 成本很低,利润很高,人们希望多预测些,生成模型系数大于1,往多了预测

交叉熵

交叉熵可以表示两个概率分布之间的距离

例如 二分类,已知答案y_(1, 0) 预测 y1(0.6, 0.4), y2=(0.8, 0.2), 那个答案接近标准答案

代码实现, tf.losses.categorical_crossentropy(y_,y)

复制代码
import tensorflow as tf

loss_ce1 = tf.losses.categorical_crossentropy([1, 0], [0.6, 0.4])
loss_ce2 = tf.losses.categorical_crossentropy([1, 0], [0.8, 0.2])
print("loss_ce1:", loss_ce1)
print("loss_ce2:", loss_ce2)

sotfmax与交叉熵结合

tf.nn.sotfmax_cross_entropy_with_logits(y_, y)

例子:

复制代码
# softmax与交叉熵损失函数的结合
import tensorflow as tf
import numpy as np

y_ = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0]])
y = np.array([[12, 3, 2], [3, 10, 1], [1, 2, 5], [4, 6.5, 1.2], [3, 6, 1]])
y_pro = tf.nn.softmax(y)
loss_ce1 = tf.losses.categorical_crossentropy(y_,y_pro)
loss_ce2 = tf.nn.softmax_cross_entropy_with_logits(y_, y)

print('分步计算的结果:\n', loss_ce1)
print('结合计算的结果:\n', loss_ce2)


# 输出的结果相同
相关推荐
Shuai@几秒前
VILA-M3: Enhancing Vision-Language Models with Medical Expert Knowledge
人工智能·语言模型·自然语言处理
动亦定2 分钟前
AI与物联网(IoT)的融合
人工智能·物联网
夏末蝉未鸣0115 分钟前
python transformers笔记(TrainingArguments类)
python·自然语言处理·transformer
德育处主任Pro19 分钟前
「py数据分析」04如何将 Python 爬取的数据保存为 CSV 文件
数据库·python·数据分析
咸鱼鲸29 分钟前
【PyTorch】PyTorch中数据准备工作(AI生成)
人工智能·pytorch·python
停走的风35 分钟前
二刷(李宏毅深度学习,醍醐灌顶,长刷长爽)
人工智能·深度学习
qinyia41 分钟前
Wisdom SSH:探索AI助手在复杂运维任务中的卓越表现
运维·人工智能·ssh
TY-202543 分钟前
二、深度学习——损失函数
人工智能·深度学习
遇见你很高兴1 小时前
Pycharm中体验通义灵码来AI辅助编程
python
京东零售技术1 小时前
让大模型更懂你,京东零售的算法工程师做了这些事
人工智能·求职