Tensorflow梯度返回nan或Inf

如何解决Tensorflow梯度返回nan或Inf

我正在尝试使用张量流和keras(用于credit card fraud data from kaggle)实现WGAN-GP模型。

我主要遵循keras website中提供的示例代码以及互联网上的其他几个示例代码(但是将它们从图像更改为我的数据),而且非常简单。

但是,当我要更新评论者时,经过几批操作后,损失的重量与评论者权重的梯度就变成了nan。这就导致评论家的权重变为nan,之后生成器的权重变为nan,...所以一切都变成了nan

enter image description here

我使用tf.debugging.enable_check_numerics并发现问题是由于经过一些迭代后渐变中出现了-Inf

这与损失中的梯度罚分项直接相关,因为当我删除时,问题就消失了。

请注意,gp本身不是nan,但是当我得到评论家权重的损失梯度(以下代码中的c_grads)时,它包含{ {1}},然后以某种方式变成全部-Inf

我检查了数学和网络体系结构是否存在可能的错误(例如,梯度消失的可能性等),并且在代码中检查了可能有几个小时的错误。但是我被卡住了。

如果有人能找到问题的根源,我将不胜感激

注意: 请记住,评论者的输出和损失函数与原始论文略有不同(因为我试图使其成为有条件的),但这与问题无关,因为正如我之前所说,当我这样做时,整个问题就消失了只需删除梯度惩罚项即可

这是我的批评家:

nan

这是我的梯度罚函数:

critic = keras.Sequential([
        keras.layers.Input(shape=(x_dim,),name='c-input'),keras.layers.Dense(64,kernel_initializer=keras.initializers.he_normal(),name='c-hidden-1'),keras.layers.LeakyReLU(alpha=0.25,name='c-activation-1'),keras.layers.Dense(32,name='c-hidden-2'),name='c-activation-2'),keras.layers.Dense(2,activation='tanh',name='c-output')
    ],name='critic')

这是评论家的更新代码

def gradient_penalty(self,batch_size,x_real,x_fake):
    # get the random linear interpolation of real and fake data (x hat)
    alpha = tf.random.uniform([batch_size,1],0.0,1.0)
    x_interpolated = x_real + alpha * (x_fake - x_real)
    with tf.GradientTape() as gp_tape:
        gp_tape.watch(x_interpolated)
        # Get the critic score for this interpolated data
        scores = 0.5 * (self.critic(x_interpolated,training=True) + 1.0)
    # Calculate the gradients w.r.t to this interpolated data
    grads = gp_tape.gradient(scores,x_interpolated)
    # Calculate the norm of the gradients
    # Gradient penalty enforces the gradient to stay close to 1.0 (1-Lipschitz constraint)
    gp = tf.reduce_mean(tf.square(tf.norm(grads,axis=-1) - 1.0))
    return gp

也请注意:如您所见,我不会使用任何交叉熵或其他自写函数,否则会被零除。

解决方法

因此,在深入研究互联网之后,事实证明这是由于tf.norm的数值不稳定(以及其他一些功能)所致。

对于norm函数,问题在于,当计算其梯度时,其值出现在分母中。因此,d(norm(x))/dx处的x = 0会变成0 / 0(这是我一直在寻找的神秘division-by-zero!)

问题是计算图有时会以a / a之类的结尾,其中a = 0的数值未定义,但存在极限。而且由于tensorflow的工作方式(使用链规则计算梯度),它会导致nan s或+/-Inf s。

最好的方法可能是让张量流检测这些模式并将其替换为分析简化的等效模式。但是直到他们这样做之前,我们还有另一种方法,那就是使用称为tf.custom_gradient的东西通过我们的自定义渐变(related issue on their github)来定义我们的自定义函数

尽管就我而言,实际上还有一个更简单的解决方案(尽管当我不知道tf.norm是罪魁祸首时,这并不简单):

所以代替:

tf.norm(x)

您可以使用:

tf.sqrt(tf.reduce_sum(tf.square(x)) + 1.0e-12)

注意:请注意尺寸(如果x是矩阵或张量,则需要计算行或列范数)!这只是一个示范概念的示例代码

希望它对某人有帮助

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-