TF 2.0 打印张量值

Cri*_*iva 15 python tensorflow tensorflow2.0

我正在学习 Tensorflow (2.0) 的最新版本,并尝试运行一个简单的代码来切片矩阵。使用装饰器 @tf.function 我做了以下类:

class Data:
def __init__(self):
    pass

def back_to_zero(self, input):
    time = tf.slice(input, [0,0], [-1,1])
    new_time = time - time[0][0]
    return new_time

@tf.function
def load_data(self, inputs):
    new_x = self.back_to_zero(inputs)
    print(new_x)
Run Code Online (Sandbox Code Playgroud)

因此,当使用 numpy 矩阵运行代码时,我无法检索数字。

time = np.linspace(0,10,20)
magntiudes = np.random.normal(0,1,size=20)
x = np.vstack([time, magntiudes]).T


d = Data()
d.load_data(x)
Run Code Online (Sandbox Code Playgroud)

输出:

Tensor("sub:0", shape=(20, 1), dtype=float64)
Run Code Online (Sandbox Code Playgroud)

我需要以 numpy 格式获取此张量,但 TF 2.0 没有使用 run() 或 eval() 方法的 tf.Session 类。

感谢您为我提供的任何帮助!

edk*_*ked 16

在装饰器指示的图形内@tf.function,您可以使用tf.print打印张量的值。

tf.print(new_x)
Run Code Online (Sandbox Code Playgroud)

以下是如何重写代码

class Data:
    def __init__(self):
        pass

    def back_to_zero(self, input):
        time = tf.slice(input, [0,0], [-1,1])
        new_time = time - time[0][0]
        return new_time

    @tf.function
    def load_data(self, inputs):
        new_x = self.back_to_zero(inputs)
        tf.print(new_x) # print inside the graph context
        return new_x

time = np.linspace(0,10,20)
magntiudes = np.random.normal(0,1,size=20)
x = np.vstack([time, magntiudes]).T

d = Data()
data = d.load_data(x)
print(data) # print outside the graph context
Run Code Online (Sandbox Code Playgroud)

tf.decorator上下文之外的张量类型是 type tensorflow.python.framework.ops.EagerTensor。要将其转换为 numpy 数组,您可以使用data.numpy()

  • tf.print 语句仅返回 `<tf.Operation 'PrintV2_3' type=PrintV2>` :-( 我做错了什么? (4认同)
  • 嗨edkeveked。我在 tf.function 中添加了 tf.print 语句,但它没有显示任何内容。 (2认同)