Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to save tensor value to file as binary format?

I'm trying to save tensor value to file as binary format. Especially I'm trying to save float32 tensor value as binary format(IEEE-754 format). Could you please help me ??

import tensorflow as tf

x = tf.constant([[1.0, 2.0, 3.0], [5.5, 4.3, 2.5]])

# how to save tensor x as binary format ?? 
like image 967
김종현 Avatar asked Jan 08 '18 05:01

김종현


People also ask

How save a tensor in a text file in Python?

If you really want to write the data to a text file, format the string. Something like '{:. 25f}'. format(tensor) might work (assuming you don't have values really close to zero).

How do I save a tensor object in Python?

One way would be to do a. numpy(). save('file. npy') then converting back to a tensor after loading.

How do I save a tensor to a csv file?

You can first convert the tensor to a Lua table using torch. totable. Then use the csvigo library to save the table as a csv file.


1 Answers

The recommended approach is to checkpoint your model. As documented in the Saving and Restoring programmer's guide, you create a tf.train.Saver object, optionally specifying which variables/saveable objects are to be saved. Then, whenever you want to save the values of the tensors, you invoke the save() method of the tf.train.Saver object:

saver = tf.train.Saver(...)

#...

saver.save(session, 'my-checkpoints', global_step = step)

.. where the second argument ('my-checkpoints' in the above example) is the path to a directory in which the checkpoint binary files are stored.

Another approach is to evaluate individual tensors (which will be NumPy ndarrays) and then save individual ndarrays to NPY files (via numpy.save()) or multiple ndarrays to a single NPZ archive (via numpy.savez() or numpy.savez_compressed()):

np.save('x.npy', session.run(x), allow_pickle = False)
like image 184
Daniel Trebbien Avatar answered Sep 23 '22 04:09

Daniel Trebbien