如何输出张量列表的值

如题,使用tf.gradients求解函数导数时,不显示数值结果

import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()

X = tf.constant([[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0], [1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0]])
Y = X * 2
grad = tf.gradients(Y, X)
print(grad)

结果是:
Tensor("gradients/mul_grad/Mul:0", shape=(16, 1), dtype=float32)

请问该怎么操作才能让他显示数值

你得到的Tensor("gradients/mul_grad/Mul:0", shape=(16, 1), dtype=float32)表示的是一个对象,对象里面包含列表或数组。需要先转化为列表或数组才可以显示里面的数据

可以试试这两种

  1. torch.Tensor 转 list
    先转numpy,后转list
    list = tensor.numpy().tolist()
  2. torch.Tensor 转 numpy
    ndarray = tensor.numpy() #注:gpu上的tensor不能直接转为numpy
    ndarray = tensor.cpu().numpy()