carlorop
carlorop

Reputation: 332

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)

Upvotes: 7

Views: 16231

Answers (2)

yogeesh agarwal
yogeesh agarwal

Reputation: 128

Well, I suppose that you are running the function under graph mode, otherwise (eager mode execution) you can just use NumPy or normal pythonic file handling ways to save the values after accessing them via .numpy() function of a tensor.
In graph mode, you can use tf.io.write_file() operation. Elaborating more on the 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 everything to string first. Also if you call write_file fn n number of times in the same run, each call will override previous's output, thus file will contain last call content.

Upvotes: 6

Susmit Agrawal
Susmit Agrawal

Reputation: 3764

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.

Upvotes: 3

Related Questions