0

I have a json string representing a model stored in a js variable. I created it using a gui that generates this json. I would like to load it to tensorflow using tf.loadModel, but the API only accepts url or localstorage. Is there any way to do it directly from string?

2 Answers 2

2

Unfortunately Tensorflow.js doesn't provide any way to do this currently.

However, if you need to do it with a string, a possible workaround is to save the string directly to localStorage and retrieve it from there with the URI.

Something like this (untested):

var modelJson = { ... }
localStorage.setItem('model', JSON.stringify(modelJson))
const model = await tf.loadModel('localstorage://model');
Sign up to request clarification or add additional context in comments.

Comments

0

In cases where using localstorage is problematic (e.g. userscripts) you can load a model directly from variables by creating a custom IoHandler

    function base64ToArray(base64) {
        const binary_string = window.atob(base64);
        const len = binary_string.length;
        const bytes = new Uint8Array(len);
        for (let i = 0; i < len; i++) {
            bytes[i] = binary_string.charCodeAt(i);
        }
        return bytes.buffer;
    }

    const modelJson = { YOUR OBJECT HERE }
    const weights64 = "B64_HERE";

    const ioHandler = {
        load: function() {
            return new Promise((resolve, reject) => {
                resolve({
                    modelTopology: modelJson.modelTopology,
                    weightSpecs: modelJson.weightsManifest[0]["weights"],
                    weightData: base64ToArray(weights64),
                    //format: modelJson.format,
                    //generatedBy: modelJson.generatedBy,
                    //convertedBy: modelJson.convertedBy
                });
            });
        }
    }
    model = await tf.loadLayersModel(ioHandler);

Comments

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.