在损失函数中使用.numpy()时,为什么Tensorflow的自动区分会失败吗?

先知大卫

我注意到,当损失函数将输入转换为numpy数组以计算输出值时,Tensorflow的自动微分功能不会提供与有限差分相同的值。这是问题的最小工作示例:

import tensorflow as tf
import numpy as np

def lossFn(inputTensor):
    # Input is a rank-2 square tensor
    return tf.linalg.trace(inputTensor @ inputTensor)

def lossFnWithNumpy(inputTensor):
    # Same function, but converts input to a numpy array before performing the norm
    inputArray = inputTensor.numpy()

    return tf.linalg.trace(inputArray @ inputArray)

N = 2
tf.random.set_seed(0)
randomTensor = tf.random.uniform([N, N])

# Prove that the two functions give the same output; evaluates to exactly zero
print(lossFn(randomTensor) - lossFnWithNumpy(randomTensor)) 

theoretical, numerical = tf.test.compute_gradient(lossFn, [randomTensor])
# These two values match
print(theoretical[0])
print(numerical[0])

theoretical, numerical = tf.test.compute_gradient(lossFnWithNumpy, [randomTensor])
# The theoretical value is [0 0 0 0]
print(theoretical[0])
print(numerical[0])

该函数tf.test.compute_gradients使用自动微分计算“理论”梯度,并使用有限差分计算数值梯度。如代码所示,如​​果.numpy()在损失函数中使用自动微分功能,则不会计算梯度。

有人可以解释原因吗?

莱斯库雷尔

从指南:梯度和自动微分简介

如果计算退出TensorFlow,则磁带将无法记录渐变路径例如:

x = tf.Variable([[1.0, 2.0],
                 [3.0, 4.0]], dtype=tf.float32)

with tf.GradientTape() as tape:   
  x2 = x**2
  # This step is calculated with NumPy   
  y = np.mean(x2, axis=0)
  # Like most ops, reduce_mean will cast the NumPy array to a constant tensor 
  # using `tf.convert_to_tensor`. 
  y = tf.reduce_mean(y,axis=0)

print(tape.gradient(y, x)) 

输出 None

numpy值将在对的调用中作为常量张量而返回tf.linalg.trace,Tensorflow无法对其进行梯度计算。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

tensorflow 在损失函数中使用输入

在tensorflow中使用RGB图像的SSIM损失函数

在损失函数中使用自动分级时,PyTorch不更新权重

使用tensorflow在损失函数中使用输入dim 1索引超出范围

在Keras / Tensorflow自定义损失函数中使用其他**可**变量

拥抱脸的变形金刚库的 Trainer 中使用的损失函数是什么?

在Keras中使用自定义损失函数时的批次大小问题

在Keras中使用Tensorflow Huber损失

使用DNNRegressor的损失函数是什么?

在 C++ 中使用聚合的性能损失是什么?

在QML中使用Text.implicitWidth时的性能损失

如何使用TensorFlow后端掩盖Keras中的损失函数?

使用推土机的距离作为Tensorflow中的损失函数

为什么我们需要Tensorflow的损失函数中的MNIST标签使用`int64`?

TensorFlow:损失矩阵函数

使用自己的损失函数编译 Keras 模型时出错

如何在损失函数中使用常量?

使用CategoricalCrossentropy损失函数时,为什么会出现“ ValueError:形状不匹配”的问题?

ValueError:未知损失函数:使用我的自定义损失函数加载模型时已修复focal_loss_fixed

如果我在keras中使用y_pred作为自定义损失函数会怎样?这不应该总是有效吗,因为y_pred总是可以区分的吗?

为什么在 Keras 的 model.evaluate() 中使用损失来计算准确度?

为什么在决策树中使用交叉熵而不是0/1损失

我可以使用阶跃函数作为损失函数来训练神经网络吗?

AttributeError: 'Tensor' 对象在使用基于 Keras 的自定义损失函数时没有属性 'numpy'

在pytorch中使用交叉熵损失时,应该使用softmax作为输出吗?

为什么我的损失函数返回负值?

在Tensorflow函数中使用@登录

如何在tensorflow会话中使用mean_squared_error损失

Nan在Keras中使用Adam Optimizer与“ Learning Rate Step Decay”调度程序损失了Nan吗?