简体   繁体   中英

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

@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 . It allows you to write a tensor to a file.

The corresponding function to read a saved tensor file is 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.
in graph mode, you can use tf.io.write_file() operation.Elborating more on previously mentioned solution , write_file fn takes a single string. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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