使用稀疏张量计算梯度时,tensorflow给出nans

2024-04-26

以下代码片段来自相当长的一段代码,但希望我可以提供所有必要的信息:

y2 = tf.matmul(y1,ymask)

dist = tf.norm(ystar-y2,轴=0)

y1 和 y2 为 128x30,ymask 为 30x30。 ystar 为 128x30。距离为 1x30。当 ymask 是单位矩阵时,一切正常。但是当我将其设置为全零时,除了沿对角线的单个 1 之外(以便将 y2 中除一列之外的所有列设置为零),我使用 tf.梯度(距离,[y2])。 dist 的具体值为 [0,0,7.9,0,...],第三列中所有 ystar-y2 值均在 (-1,1) 范围内,其他位置为零。

我很困惑为什么这里会出现数字问题,因为没有日志或分区,这是下溢吗?我在数学中遗漏了什么吗?

就上下文而言,我这样做是为了尝试使用整个网络一次训练 y 的各个维度。

要重现的更长版本:

import tensorflow as tf
import numpy as np
import pandas as pd

batchSize = 128
eta = 0.8
tasks = 30
imageSize = 32**2
groups = 3
tasksPerGroup = 10
trainDatapoints = 10000

w = np.zeros([imageSize, groups * tasksPerGroup])
toyIndex = 0
for toyLoop in range(groups):
    m = np.ones([imageSize]) * np.random.randn(imageSize)
    for taskLoop in range(tasksPerGroup):
        w[:, toyIndex] = m * 0.1 * np.random.randn(1)
        toyIndex += 1

xRand = np.random.normal(0, 0.5, (trainDatapoints, imageSize))
taskLabels = np.matmul(xRand, w) + np.random.normal(0,0.5,(trainDatapoints, groups * tasksPerGroup))
DF = np.concatenate((xRand, taskLabels), axis=1)
trainDF = pd.DataFrame(DF[:trainDatapoints, ])

# define graph variables
x = tf.placeholder(tf.float32, [None, imageSize])
W = tf.Variable(tf.zeros([imageSize, tasks]))
b = tf.Variable(tf.zeros([tasks]))
ystar = tf.placeholder(tf.float32, [None, tasks])
ymask = tf.placeholder(tf.float32, [tasks, tasks])
dataLength = tf.cast(tf.shape(ystar)[0],dtype=tf.float32)

y1 = tf.matmul(x, W) + b
y2 = tf.matmul(y1,ymask)
dist = tf.norm(ystar-y2,axis=0)
mse = tf.reciprocal(dataLength) * tf.reduce_mean(tf.square(dist))
grads = tf.gradients(dist, [y2])

trainStep = tf.train.GradientDescentOptimizer(eta).minimize(mse)

# build graph
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

randTask = np.random.randint(0, 9)
ymaskIn = np.zeros([tasks, tasks])
ymaskIn[randTask, randTask] = 1
batch = trainDF.sample(batchSize)
batch_xs = batch.iloc[:, :imageSize]
batch_ys = np.zeros([batchSize, tasks])
batch_ys[:, randTask] = batch.iloc[:, imageSize + randTask]

gradOut = sess.run(grads, feed_dict={x: batch_xs, ystar: batch_ys, ymask: ymaskIn})

sess.run(trainStep, feed_dict={x: batch_xs, ystar: batch_ys, ymask:ymaskIn})

这是一个非常简单的复制:

import tensorflow as tf

with tf.Graph().as_default():
  y = tf.zeros(shape=[1], dtype=tf.float32)
  dist = tf.norm(y,axis=0)
  (grad,) = tf.gradients(dist, [y])
  with tf.Session():
    print(grad.eval())

Prints:

[ nan]

问题是tf.norm计算sum(x**2)**0.5。梯度为x / sum(x**2) ** 0.5(参见例如https://math.stackexchange.com/a/84333 https://math.stackexchange.com/a/84333),所以当sum(x**2)是零,我们要除以零。

对于特殊情况,没有什么可做的:梯度为x接近全零取决于它从哪个方向接近。例如如果x是单元素向量,极限为x接近 0 可能是 1 或 -1,具体取决于它从零的哪一侧接近。

所以就解决方案而言,你可以添加一个小的epsilon:

import tensorflow as tf

def safe_norm(x, epsilon=1e-12, axis=None):
  return tf.sqrt(tf.reduce_sum(x ** 2, axis=axis) + epsilon)

with tf.Graph().as_default():
  y = tf.constant([0.])
  dist = safe_norm(y,axis=0)
  (grad,) = tf.gradients(dist, [y])
  with tf.Session():
    print(grad.eval())

Prints:

[ 0.]

请注意,这实际上不是欧几里得范数。只要输入远大于epsilon.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用稀疏张量计算梯度时,tensorflow给出nans 的相关文章

随机推荐