当输入中存在nan时,即使损失计算是

2024-03-29 14:45:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些输入与南,我不能取代作为预处理。尽管如此,我还是想使用tensorflow 2.0的自差分来计算我的操作的梯度。 我构建了一个简单的回归案例,当输入中有NaN时,它返回NaN梯度。 有没有办法为这些操作设置梯度?你知道吗

致以最诚挚的问候

import tensorflow as tf
import numpy as np

x = np.float32(np.arange(100))
y = 2*x 
x[0] = np.nan
a = tf.Variable([1e-6])
with tf.GradientTape() as t:
    t.watch(a)
    y_pred = a*x
    tensor = tf.reshape((y_pred - y), [-1])**2
    tensor_mask = tf.math.is_nan(tensor)
    tensor_without_nans = tf.where(tensor_mask, tf.zeros_like(tensor), tensor)
    RMSE = tf.reduce_sum(tensor_without_nans, axis=-1)

grads = t.gradient(RMSE,a)
print(grads)

Tags: importtftensorflowasnpmasknanwithout