python - 打印张量值tensorflow 2.4

标签 python tensorflow

我在训练我的 Transformer 时打印了一个值。

@tf.function
def train_step(inp, tar):
    tar_inp = tar[:, :-1]
    tar_real = tar[:, 1:]
    global i
    if i == 1:
      print('__________________')
      tf.print('Inp: ', inp, output_stream=sys.stdout)
      tf.print('Tar: ', tar, output_stream=sys.stdout)
      tf.print('Tar_inp: ', tar_inp, output_stream=sys.stdout)
      tf.print('Tar_real: ', tar_real, output_stream=sys.stdout)
      i += 1
    .......

但是 tf.print 不打印任何东西。但是我的第一个 print('_') 有效 我做错了什么?请帮我打印我的张量。

更新: 你也可以向我解释 tar_inptar_real 的结构,而不是修复 tf.打印

最佳答案

尝试使用 tensor.numpy() 将其更改为 print() -

@tf.function
def train_step(inp, tar):
    tar_inp = tar[:, :-1]
    tar_real = tar[:, 1:]
    global i
    if i == 1:
      print('__________________')
      print('Inp: ', inp.numpy())
      print('Tar: ', tar.numpy())
      print('Tar_inp: ', tar_inp.numpy())
      print('Tar_real: ', tar_real.numpy())
      i += 1


W.r.t tar_inptar_real,索引在张量上的工作方式与在 numpy 数组上的工作方式相同,但它返回一个张量对象。因此您可以建立索引,然后将提取的值转换为 numpy 数组。

print(tf.convert_to_tensor([1,2,3]).numpy()) #get numpy
print(tf.convert_to_tensor([1,2,3])[1:].numpy()) #get numpy after indexing
print(tf.convert_to_tensor([1,2,3]).numpy()[1:]) #index after getting numpy
[1 2 3]
[2 3]
[2 3]

关于python - 打印张量值tensorflow 2.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66114393/

相关文章:

python - Dash 在回调之间共享 Fig 对象

python - 子进程系统找不到指定的文件错误

python - 制作额外的树模型时出现 ValueError : Unknown label type: array([0. 11],...)

python - Tensorflow:计算梯度子张量

python - Wide_deep分类器模型,需要预测概率值,不仅是 "best guess"

python - 准确率提高但损失也增加

machine-learning - 简单来说什么是损失函数?

python - Numpy 一维数组在广播时被视为列向量

tensorflow - 同样的模型在 keras 中收敛,但在 tensorflow 中不收敛,这怎么可能?

python - 如何使用 sphinx-apidoc 记录 Python 函数参数?