简体   繁体   English

如何在 Tensorflow 中保存张量的值

[英]How to save the value of a tensor in Tensorflow

I am trying to save a tensor array that is necessarily computed into a function with the decorator @tf.function , this makes all the tensors inside the function into tensor graphs, and hence, non-iterable objects.我试图保存一个张量数组,该数组必须使用装饰器@tf.function计算成一个函数,这使得函数内的所有张量都变成张量图,因此是不可迭代的对象。 For instance, in the following minimal code, I would like to know if it is possible to save the tensor into a file using code inside the function foo() .例如,在下面的最小代码中,我想知道是否可以使用函数foo()代码将张量保存到文件中。

@tf.function
def foo(x):
    # code for saving x


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

Take a look at tf.io.write_file .看看tf.io.write_file It allows you to write a tensor to a file.它允许您将张量写入文件。

The corresponding function to read a saved tensor file is tf.io.read_file .读取已保存张量文件的相应函数是tf.io.read_file

well i suppose that ur running the function under graph mode , otherwise (eager mode execution) u can just use numpy or normal pythonic file handling ways to save the values after accessing them via .numpy() fucntion of a tensor.好吧,我想你是在图形模式下运行函数,否则(热切模式执行)你可以只使用 numpy 或普通的 pythonic 文件处理方式来保存值,然后通过张量的 .numpy() 函数访问它们。
in graph mode, you can use tf.io.write_file() operation.Elborating more on previously mentioned solution , write_file fn takes a single string.在图形模式下,您可以使用 tf.io.write_file() 操作。对前面提到的解决方案进行更多讨论,write_file fn 需要一个字符串。 below example might help more:下面的例子可能有更多帮助:

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 only accepts strings, so you need to convert everythin to string first. write_file fn 只接受字符串,因此您需要先将所有内容转换为字符串。 Also if u call write_file fn n number of times in same run , each call will override previous's output , thus file will contain last call content.此外,如果您在同一次运行中多次调用 write_file fn,则每次调用都将覆盖先前的输出,因此文件将包含上次调用的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM