首页 > 解决方案 > 批量输入的 TensorFlow 梯度仅相对于考虑批量大小的某些变量。ValueError:无法从形状推断 num

问题描述

我的问题有两个部分,因为我已经混淆了导致我的错误的原因。我同时在我的 tf.unstack() 方法中处理批量大小以及使用这些未堆叠张量的 tf.GradientTape() 的导数时遇到问题。我正在用这个循环训练一个网络。

with tf.GradientTape() as tape2:
    with tf.GradientTape() as tape:
        tape.watch(x)
        preds = self(x)
        # grab jacobian for PINN 
    jacobian = tape.jacobian(preds, x)
    loss_value = self.compiled_loss(y, preds)
    loss_value += self.physics_regularization(jacobian, y)

在我的用例中,X 有 4 个输入列,我只使用前两列的梯度信息。我试图将输入值分开,只采用某些推导来减少计算负担。

t, x0, z0, vel = tf.unstack(x)  # ValueError: Cannot infer num from shape
with tf.GradientTape() as tape2:
    with tf.GradientTape(persistent=True) as tape:
        tape.watch([x0, z0]) 
        x = tf.stack((t, x0, z0, vel))
        preds = self(x)
        _x, _z, _sxx, _sxz, _szz = tf.unstack(preds, axis=1)
    dx_dx0 = tape.gradient(_x, x0)
    dx_dz0 = tape.gradient(_x, z0)
    dz_dx0 = tape.gradient(_z, x0)
    dz_dz0 = tape.gradient(_z, z0)
    derivs = tf.reshape(tf.stack((dx_dx0, dx_dz0, dz_dx0, dz_dz0)), (1,4))
    loss_value = self.compiled_loss(y, preds)
    loss_value += self.reg_constant * self.regularization(derivs, y)

标签: tensorflow

解决方案


推荐阅读