文章目录

  • 1.常用损失函数
  • 2.自定义损失函数
    • mse
    • Focal loss损失函数
  • 3.实战1:Focal Loss实现自定义损失函数(以minist数据集构建图像分类算法)

1.常用损失函数

tf.keras.losses

列举常用的,如下:

BinaryCrossentropy和binary_crossentropy有什么区别?
前者是类的实现形式,后者是函数的实现形式
这两者并没有本质的区别使用损失函数时,首先要确定到底是分类还是回归问题?一定要对应
每个损失函数是如何实现的一定要清楚

交叉熵损失函数-多分类

# tf版本
import tensorflow as tf# 调用类,输入损失函数
cce = tf.keras.losses.CategoricalCrossentropy()loss = cce([[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]],[[.9,.05,.05],[.05,.89,.06],[.05,.01,.94]])
print('Loss:',loss.numpy())     # Loss: 0.09458993# Numpy版本
import numpy as np a = np.array([[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]])
b = np.array([[.9,.05,.05],[.05,.89,.06],[.05,.01,.94]])np.average(-np.sum(a * np.log(b),axis=1))     # 0.09458991187728844

2.自定义损失函数

mse

Focal loss损失函数

多分类的Focal loss函数:
gamma 用来减小易分类样本的权重,使得模型训练时更加专注于难分类的样本
α 用来计算每个类别的概率-权重-二分类变成多分类时,α会失效
# 类的实现
class SparseFocalLoss(tf.keras.losses.Loss):def __init__(self,gamma=2.0,alpha=0.25,class_num=10):# 初始化参数self.gamma = gammaself.alpha = alphaself.class_num = class_numsuper(SparseFocalLoss,self).__init__()def call(self,y_true,y_pred):# 激活函数y_pred = tf.nn.softmax(y_pred,axis=-1)# 使预测值在某个区间不为0epsilon = tf.keras.backend.epsilon()y_pred = tf.clip_by_value(y_pred,epsilon,1.0)# 转换成one_hot格式y_true = tf.one_hot(y_true,depth=self.class_num)# 数据类型转化y_true = tf.cast(y_true,tf.float32)loss = -y_true * tf.math.pow(1 - y_pred,self.gamma) * tf.math.log(y_pred)loss = tf.math.reduce_sum(loss,axis=1)return loss
# 函数的实现
def focal_loss(gamma=2.0,alpha=0.25):def focal_loss_fixed(y_true,y_pred):y_pred = tf.nn.softmax(y_pred,axis=-1)epsilon = tf.keras.backend.epsilon()y_pred = tf.clip_by_value(y_pred,epsilon,1.0)# 数据类型转换y_true = tf.cast(y_true,tf.float32)loss = -y_true * tf.math.pow(1-y_pred,gamma) * tf.math.log(y_pred)loss = tf.reduce_sum(loss,axis=1)return lossreturn focal_loss_fixed

3.实战1:Focal Loss实现自定义损失函数(以minist数据集构建图像分类算法)


子类模型

from __future__ import absolute_import, division, print_function, unicode_literalsimport tensorflow as tffrom tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model
import numpy as npprint(tf.__version__)
print(np.__version__)# 数据集处理
mnist = np.load("mnist.npz")
x_train, y_train, x_test, y_test =
mnist['x_train'],mnist['y_train'],mnist['x_test'],mnist['y_test']
# 神经网络需要归一化
x_train, x_test = x_train / 255.0, x_test / 255.0# 画图展示
import matplotlib.pyplot as pltfig, ax = plt.subplots(nrows=2,ncols=5,sharex=True,sharey=True, )ax = ax.flatten()
for i in range(10):img = x_train[y_train == i][0].reshape(28, 28)ax[i].imshow(img, cmap='Greys', interpolation='nearest')ax[0].set_xticks([])
ax[0].set_yticks([])
plt.tight_layout()
plt.show()# 增加一个通道(28,28,1)
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]y_train = tf.one_hot(y_train,depth=10)
y_test = tf.one_hot(y_test,depth=10)train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)).shuffle(10000).batch(32)
test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)# 简单的神经网络
# 定义模型
class MyModel(Model):def __init__(self):super(MyModel,self).__init__()# 定义二维的卷积层self.conv1 = Conv2D(32,3,activation='relu')self.flatten = Flatten()# 定义全连接层self.d1 = Dense(128,activation='relu')# 输出层self.d2 = Dense(10,activation='softmax')def call(self,x):# 定义前向传播x = self.conv1(x)     # 卷积x = self.flatten(x)   # 压缩x = self.d1(x)        # 全连接层return self.d2(x)     # 输出# 类的实现
#多分类的focal loss 损失函数
class FocalLoss(tf.keras.losses.Loss):def __init__(self,gamma=2.0,alpha=0.25):self.gamma = gammaself.alpha = alphasuper(FocalLoss, self).__init__()def call(self,y_true,y_pred):y_pred = tf.nn.softmax(y_pred,axis=-1)epsilon = tf.keras.backend.epsilon()#1e-7y_pred = tf.clip_by_value(y_pred, epsilon, 1.0)y_true = tf.cast(y_true,tf.float32)loss = -  y_true * tf.math.pow(1 - y_pred, self.gamma) * tf.math.log(y_pred)loss = tf.math.reduce_sum(loss,axis=1)return loss# 类的实现与函数的实现选择一个
# 函数的实现
def FocalLoss(gamma=2.0,alpha=0.25):def focal_loss_fixed(y_true, y_pred):y_pred = tf.nn.softmax(y_pred,axis=-1)# 使预测值在某个区间不为0epsilon = tf.keras.backend.epsilon()y_pred = tf.clip_by_value(y_pred, epsilon, 1.0)# 转换数据格式y_true = tf.cast(y_true,tf.float32)loss = -  y_true * tf.math.pow(1 - y_pred, gamma) * tf.math.log(y_pred)loss = tf.math.reduce_sum(loss,axis=1)return  lossreturn focal_loss_fixedmodel = MyModel()#loss_object = tf.keras.losses.CategoricalCrossentropy()
loss_object = FocalLoss(gamma=2.0,alpha=0.25)optimizer = tf.keras.optimizers.Adam()train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.CategoricalAccuracy(name='train_accuracy')test_loss = tf.keras.metrics.Mean(name='test_loss')
test_accuracy = tf.keras.metrics.CategoricalAccuracy(name='test_accuracy')# 将动态图转化为静态图
@tf.function
def train_step(images, labels):with tf.GradientTape() as tape:predictions = model(images)loss = loss_object(labels, predictions)# 计算梯度gradients = tape.gradient(loss, model.trainable_variables)optimizer.apply_gradients(zip(gradients, model.trainable_variables))# 参数更新train_loss(loss)train_accuracy(labels, predictions)@tf.function
def test_step(images, labels):predictions = model(images)t_loss = loss_object(labels, predictions)test_loss(t_loss)test_accuracy(labels, predictions)EPOCHS = 5
for epoch in range(EPOCHS):# 在下一个epoch开始时,重置评估指标train_loss.reset_states()train_accuracy.reset_states()test_loss.reset_states()test_accuracy.reset_states()for images, labels in train_ds:train_step(images, labels)for test_images, test_labels in test_ds:test_step(test_images, test_labels)template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'print(template.format(epoch + 1,train_loss.result(),train_accuracy.result() * 100,test_loss.result(),test_accuracy.result() * 100))



函数模型

from __future__ import absolute_import, division, print_function, unicode_literalsimport tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model
import numpy as npprint(tf.__version__)
print(np.__version__)mnist = np.load("mnist.npz")
x_train, y_train, x_test, y_test = mnist['x_train'],mnist['y_train'],mnist['x_test'],mnist['y_test']x_train, x_test = x_train / 255.0, x_test / 255.0
y_train = np.int32(y_train)
y_test = np.int32(y_test)# 增加一个通道
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]
y_train = tf.one_hot(y_train,depth=10)
y_test = tf.one_hot(y_test,depth=10)train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)).shuffle(10000).batch(32)
test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).shuffle(100).batch(32)# 函数式定义模型
def MyModel():inputs = tf.keras.Input(shape=(28,28,1), name='digits')         # 输入层x = tf.keras.layers.Conv2D(32, 3, activation='relu')(inputs)    # 卷积层 32个通道  3表示卷积和x = tf.keras.layers.Flatten()(x)                                # 压缩x = tf.keras.layers.Dense(128, activation='relu')(x)            # 128个神经元的全连接层outputs = tf.keras.layers.Dense(10,activation='softmax', name='predictions')(x)# 输出层model = tf.keras.Model(inputs=inputs, outputs=outputs)          return model# 类的实现
#多分类的focal loss 损失函数
class FocalLoss(tf.keras.losses.Loss):def __init__(self,gamma=2.0,alpha=0.25):self.gamma = gammaself.alpha = alphasuper(FocalLoss, self).__init__()def call(self,y_true,y_pred):y_pred = tf.nn.softmax(y_pred,axis=-1)epsilon = tf.keras.backend.epsilon()y_pred = tf.clip_by_value(y_pred, epsilon, 1.0)y_true = tf.cast(y_true,tf.float32)loss = -  y_true * tf.math.pow(1 - y_pred, self.gamma) * tf.math.log(y_pred)loss = tf.math.reduce_sum(loss,axis=1)return loss# keras版本
model = MyModel()
model.compile(optimizer = tf.keras.optimizers.Adam(0.001), #优化器loss =  FocalLoss(gamma=2.0,alpha=0.25), #损失函数metrics = [tf.keras.metrics.CategoricalAccuracy()]) #评估函数model.fit(train_ds, epochs=5,validation_data=test_ds)

深度学习7-常用损失函数和自定义损失函数相关推荐

  1. 【AI初识境】深度学习中常用的损失函数有哪些?

    这是专栏<AI初识境>的第11篇文章.所谓初识,就是对相关技术有基本了解,掌握了基本的使用方法. 今天来说说深度学习中常见的损失函数(loss),覆盖分类,回归任务以及生成对抗网络,有了目 ...

  2. Keras深度学习实战(4)——深度学习中常用激活函数和损失函数详解

    Keras深度学习实战(4)--深度学习中常用激活函数和损失函数详解 常用激活函数 Sigmoid 激活函数 Tanh 激活函数 ReLU 激活函数 线性激活函数 Softmax 激活函数 损失函数 ...

  3. 【深度学习】医学图像分割多标签损失函数和极坐标变换

    [深度学习]医学图像分割多标签损失函数和极坐标变换 文章目录 1 基于分布的损失函数 2 基于区域的损失函数 3 基于边界的损失函数 4 多标签损失函数 5 极坐标变换 1 基于分布的损失函数 基于分 ...

  4. 深度学习最常用的学习算法:Adam优化算法

    上海站 | 高性能计算之GPU CUDA培训 4月13-15日 三天密集式学习  快速带你晋级 阅读全文 > 正文共6267个字,30张图,预计阅读时间16分钟. 听说你了解深度学习最常用的学习 ...

  5. 深度学习中常用的优化算法(SGD, Nesterov,Adagrad,RMSProp,Adam)总结

    深度学习中常用的优化算法(SGD, Nesterov,Adagrad,RMSProp,Adam)总结 1. 引言 在深度学习中我们定义了损失函数以后,会采取各种各样的方法来降低损失函数的数值,从而使模 ...

  6. Tensorflow 2.x(keras)源码详解之第十一章:keras损失函数及自定义损失函数

      大家好,我是爱编程的喵喵.双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中.从事机器学习以及相关的前后端开发工作.曾在阿里云.科大讯飞.CCF等比赛获得多次Top名次.现 ...

  7. DL之AF:机器学习/深度学习中常用的激活函数(sigmoid、softmax等)简介、应用、计算图实现、代码实现详细攻略

    DL之AF:机器学习/深度学习中常用的激活函数(sigmoid.softmax等)简介.应用.计算图实现.代码实现详细攻略 目录 激活函数(Activation functions)相关配图 各个激活 ...

  8. 深度学习中常用的误差方法

    深度学习中常用的误差方法有: 标准差(Standard Deviation): 标准差也叫均方差,是方差的算术平方根,反应数据的离散程度 ,标准差越小,数据偏离平均值越小,反之亦然 . 公式为: py ...

  9. 深度学习中常用的标注文件

    深度学习中常用的标注文件 mat mat文件是matlab专用的文件,第一次见是再COCOstuff-10k数据集中. 遇到的问题:如果用sublime打开的话,会显示16进制格式,可以猜想matla ...

  10. 【深度学习】常用的模型评估指标

    [深度学习]常用的模型评估指标 "没有测量,就没有科学."这是科学家门捷列夫的名言.在计算机科学中,特别是在机器学习的领域,对模型的测量和评估同样至关重要.只有选择与问题相匹配的评 ...

最新文章

  1. 企业根CA方法客户机证书的解决方案,ISA2006系列之三十
  2. (译)删除未使用的前端代码
  3. Lambda and Anonymous Classes
  4. MySQL根被拒绝_[转载]phpMyAdmin 尝试连接到 MySQL 服务器,但服务器拒绝连接。...
  5. Spring源码 --Idea module 相互引用
  6. linux 进程0 写时复制,linux 写时复制 COW 过程梳理
  7. 添加Silverlight应用到HTML
  8. sql server 按年月日分组
  9. Android lint工具 检查的常见问题
  10. Linux系统,Hadoop,R语言,RHadoop的安装
  11. 如何用 DBSCAN 聚类算法做数据分析?
  12. 从C++11到C++23(一) C++20圆周率、常数e和常见对数
  13. 掷骰子python代码_python模拟掷骰子
  14. 1.[Sprd]-(Sprd9820e安卓4.4平台user版开启长按power键开启sysdump分析)
  15. 几款支持国标GB28181的平台以及视频监控设备接入的配置方法(Web端无插件播放)
  16. 小米手机混淆升级崩溃记录与解决
  17. 【开源项目】小程序版 玩安卓
  18. 三星被指盗取FinFET芯片专利技术 将被起诉
  19. 大数据实训笔记10:hive的应用
  20. 欧洲的计算机博士申请,申请经典案例:欧洲计算机科学专业博士全奖

热门文章

  1. html5指南--1.html5全局属性(html5 global attributes)
  2. ASP.NET站点性能提升-缩短首页生成时间
  3. Altium Designer(四):敷铜设置
  4. jQuery实现回车绑定Tab事件
  5. macOS 安装和管理多个Python版本
  6. 20180513 实参 形参 数组
  7. 关于数组增减Array 和list的区别
  8. 《前端JavaScript面试技巧》
  9. Idea 里svn的导入使用
  10. JAVA 编码格式转换工具类