2

I have a piece of code to read some binary files which are written in a specific format. I want to write a tensorflow version of my read_file() function. Is there any way to do so? I don't want to wrap my function using tf.py_function().

def read_file(filename):
    f = open(filename, 'rb')
    w = int(np.fromfile(f, np.int32, count=1))
    h = int(np.fromfile(f, np.int32, count=1))
    data = np.fromfile(f, np.float32, count=2 * w * h)
    data = np.resize(data, (h, w, 2))
    f.close()
    return data

2 Answers 2

1

You could potentially use tf.data.FixedLengthRecordDataset to read samples encoded with a fixed length of bytes from a binary file.

Sign up to request clarification or add additional context in comments.

Comments

0

Unfortunately, every python code that you want to use beside the tf* functions must be wrapped inside the tf.py_function().

There is no other way to integrate custom Python code with the TensorFlow specialised functions.

You can find even more details about this at this question: Is there an alternative to tf.py_function() for custom Python code?

6 Comments

The key function here is np.fromfile(), I couldn't find any Tensorflow alternative for that, are you aware of any? With that, it is easy to convert the whole function.
What if use use tf.constant(np.fromfile()) to convert it to Tensor?
Curious about the result, never tried it, tell me :D
Thanks, but that doesn't work here. I'm using a wrapped version of read_file() to make my tf.data.dataset, and trying to speed up the process wanted to avoid using tf.py_function() by converting the entire code to tensorflow functions. I guess I need to write my own custom tf op.
Yes, I know. That's why I put that link to my question, because there was an answer stating there that you cannot do that.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.