Python Tensorflow:矩阵乘法和加法期间的nan
我正在使用一个函数(ndegree_poly),它得到一个张量和一个权重数组,并从中计算多项式的结果 代码似乎很简单,但当阶数增加,或者函数重复多次时,结果张量包含一组NaN和Inf。INF是合理的。但是,如果数字真的越来越小,它们不应该变成零,而不是nan吗Python Tensorflow:矩阵乘法和加法期间的nan,python,matrix,tensorflow,nan,Python,Matrix,Tensorflow,Nan,我正在使用一个函数(ndegree_poly),它得到一个张量和一个权重数组,并从中计算多项式的结果 代码似乎很简单,但当阶数增加,或者函数重复多次时,结果张量包含一组NaN和Inf。INF是合理的。但是,如果数字真的越来越小,它们不应该变成零,而不是nan吗 import tensorflow as tf function_degree = 10 def ndegree_poly(x, a, degree=6): op = tf.add_n([tf.multiply(tf.
import tensorflow as tf
function_degree = 10
def ndegree_poly(x, a, degree=6):
op = tf.add_n([tf.multiply(tf.pow(x, i), a[i]) for i in range(1, degree)])
return tf.add(op, a[0])
with tf.Session() as sess:
poly_weight = tf.Variable(tf.random_normal([function_freedom, 1, 5]))
mat = tf.Variable(tf.random_normal([2, 5]))
result0 = ndegree_poly(mat, poly_weight, function_degree)
result1 = ndegree_poly(result0, poly_weight, function_degree)
result2 = ndegree_poly(result1, poly_weight, function_degree)
result3 = ndegree_poly(result2, poly_weight, function_degree)
result4 = ndegree_poly(result3, poly_weight, function_degree)
sess.run(tf.global_variables_initializer())
print(sess.run(result4))
它打印:
[[-0.28569764 nan nan nan -inf]
[ nan nan 3.55561209 nan 0.53827095]]
nan
值不是来自非常小的系数,它只是尝试这样做的“自然”结果∞ - ∞, 因为系数来自正态分布,所以是正态和负态的
import math
import tensorflow as tf
tf_inf = tf.constant(inf)
res = tf_inf - tf_inf
with tf.Session() as sess:
print(sess.run(res))
>>> nan
谢谢,我忘了考虑