[FIXED] Tensorflow JS – converting tensor to JSON and back to tensor

Issue

I a training a model in batches and am therefore saving its weights into JSON to store/send.

I need to now load those back into tensors – is there a proper way to do this?

tensor.data().then(d => JSON.stringify(d));

// returns
{"0":0.000016666666851961054,"1":-0.00019999999494757503,"2":-0.000183333337190561}

I can iterate over this an convert back to an array manually – but feel there maybe something in the API which would do this cleaner?

Solution

There is no need to stringify the result of data(). To save a tensor and restore it later, two things are needed, the data shape and the data flattened array.

s = tensor.shape 
// get the tensor from backend 

saved = {data: await s.data, shape: shape}
retrievedTensor = tf.tensor(saved.data, saved.shape)

The two pieces of information are given when using array or arraySync – the typedarray generated has the same structure as the tensor

saved = await tensor.array()
retrievedTensor = tf.tensor(saved)

Answered By – edkeveked

Answer Checked By – Katrina (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published