TF 2.0打印张量值

2024-04-20 15:38:31 发布

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

我正在学习Tensorflow(2.0)的最新版本,并尝试运行一个简单的代码来分割矩阵。 使用装饰器@tf.功能我上了以下课程:

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)

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

^{pr2}$

输出:

Tensor("sub:0", shape=(20, 1), dtype=float64)

我需要一个numpy格式的张量,但是tf2.0没有这个类tf.会议使用run()或eval()方法。在

谢谢你能给我的任何帮助!在


Tags: to代码self版本numpynewinputtime
2条回答

问题是你不能直接在图中得到张量的值。因此,您要么按照@edkeveked建议使用tf.print进行操作,要么按如下方式更改代码:

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)

        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.numpy())

在decorator @tf.function指示的图中,可以使用tf.print打印张量的值。在

tf.print(new_x)

下面是如何重写代码

^{pr2}$

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

相关问题 更多 >