如何在 TensorFlow 中保存张量的值

How to save the value of a tensor in Tensorflow

我正在尝试使用装饰器 @tf.function 将必须计算的张量数组保存到函数中,这使得函数内的所有张量都成为张量图,因此成为不可迭代的对象。例如,在下面的最小代码中,我想知道是否可以使用函数 foo().

中的代码将张量保存到文件中
@tf.function
def foo(x):
    # code for saving x


a=tf.constant([1,2,3])
foo(a)

看看tf.io.write_file。它允许您将张量写入文件。

读取保存的tensor文件对应的函数是tf.io.read_file.

好吧,我想你 运行 在图形模式下运行函数,否则(急切模式执行)你可以使用 NumPy 或正常的 pythonic 文件处理方式在通过 .numpy()张量的函数。
在图表模式下,您可以使用tf.io.write_file() 操作。详细说明前面提到的解决方案,write_file fn 采用单个字符串。下面的例子可能会有更多帮助:

a = tf.constant([1,2,3,4,5] , dtype = tf.int32)
b = tf.constant([53.44569] , dtype= tf.float32)
c = tf.constant(0)
# if u wish to write all these tensors on each line ,
# then create a single string out of these.
one_string = tf.strings.format("{}\n{}\n{}\n", (a,b,c))
# {} is a placeholder for each element ina string and thus you would need n PH for n tensors.
# send this string to write_file fn
tf.io.write_file(filename, one_string)

write_file fn 只接受字符串,所以你需要先把所有的东西都转换成字符串。 此外,如果您在同一个 运行 中调用 write_file fn n 次,每次调用都会覆盖之前的输出,因此文件将包含最后一次调用的内容。