为什么 tf.reduce_mean() 返回 NaN 值?我正在尝试计算均方误差,但我不断得到 NaN 值 [英] Why does tf.reduce_mean() return NaN values? I'm trying to calculate the Mean Squared error, but I keep getting NaN values

查看:95
本文介绍了为什么 tf.reduce_mean() 返回 NaN 值?我正在尝试计算均方误差,但我不断得到 NaN 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的代码:

This is the code I'm using:

tf.reset_default_graph()
self.sess = tf.InteractiveSession() 
self.X = tf.placeholder(tf.float32, [None, self.state_space]) 
self.Y = tf.placeholder(tf.float32, [None, self.action_space]) 
layer1 = tf.layers.dense(self.X, 128, activation = tf.nn.leaky_relu) 
layer2 = tf.layers.dense(layer1, 64, activation = tf.nn.leaky_relu) 
layer3 = tf.layers.dense(layer2, 32, activation = tf.nn.leaky_relu)
self.outputs = tf.layers.dense(layer3, self.action_space, activation='softmax') 
self.loss = tf.reduce_mean(tf.square(self.Y - self.outputs))
#self.loss = tf.sqrt(tf.reduce_sum(tf.square(self.Y - self.outputs)) + 1.0e-12)
self.optimizer = tf.train.AdamOptimizer(1e-6).minimize(self.loss)   
self.sess.run(tf.global_variables_initializer()) 

我尝试了一些基本的更改,例如添加一个小常量、使用 tf.log() 等,但到目前为止没有任何效果.

I tried a few basic changes such as adding a small constant, using tf.log(), etc, but nothing has worked till now.

在此先感谢任何可以提供帮助的人!

Thank you, in advance, to anyone who can help!

推荐答案

最终通过更改 tensorflow 版本使损失函数起作用.

Finally got the loss function to work by changing the tensorflow version.

from tensorflow.python.framework import ops
%tensorflow_version 1.x

ops.reset_default_graph()

然后,在设置我的交易者(在我的代码中定义为一个类)时,我添加了以下代码段:

Then, while setting up my trader (which is defined as a class in my code), I added the following snippet:

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

我很高兴这现在有效,但我仍然不明白为什么使用我的原始代码无法解决这个问题:

I'm glad this works now, but I still don't understand why this couldn't be solved using my original code:

import tensorflow as tf 

在添加这些片段之前,我一直在使用 Tensorflow 2.4.1.如果有人知道答案,请在下面评论/回答.干杯!

Until I added these snippets, I had been working with Tensorflow 2.4.1. If anyone knows the answer, kindly comment/answer below. Cheers!

这篇关于为什么 tf.reduce_mean() 返回 NaN 值?我正在尝试计算均方误差,但我不断得到 NaN 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆