Cannot Get TensorflowJS example to run from documentation

Viewed 19

I am a python developer who is flirting with tensorflowjs, and am trying to get the example to run from this page: [https://www.tensorflow.org/js/tutorials/conversion/import_keras][1]

I'm trying to generate a keras model and then export it to tensorflowjs and get it to run.

Here's the code I use to create the model:

import tensorflow as tf
import tensorflowjs as tfjs
from tensorflow import keras
from tensorflow.keras.datasets.imdb import load_data
from tensorflow.keras.preprocessing.sequence import pad_sequences

# import data
(x_train, y_train), (x_test, y_test) = load_data(num_words = 10000)
x_train                              = pad_sequences(x_train, maxlen = 20)

# build model
def train(x, y):
    mod = keras.models.Sequential([
          keras.layers.Embedding(10000, 128, input_length = 20),
          keras.layers.Flatten(),
          keras.layers.Dense(64, activation = 'relu'),
          keras.layers.Dense(1, activation = 'sigmoid')
    ])

    mod.compile(loss = 'binary_crossentropy')
    mod.fit(x, y, epochs = 1, batch_size = 128)
    tfjs.converters.save_keras_model(mod, 'models')

# run and fit
train(x_train, y_train)

I have a file called tf_js.js to load it into javascript that looks like this:

const model = await tf.loadLayersModel('C:\\Users\\Username\\tfjs\\models\\model.json');

const example    = tf.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
                            16, 17, 18, 19, 20]);  // for example
const prediction = model.predict(example);
console.log(prediction)

I then load this into an html file that reads like this

HTML FILE

<!DOCTYPE html>
<body>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
    <script type="module" src="tf_js.js"></script>
</body>

When I load the html file via LiveServer it returns the error message Not allowed to load local resource: file:///C:/Users/Username/tfjs/models/model.json

I presume this means I need to deploy my model on a local server, but to be honest there's nothing on that documentation page that actually states anything like that. Ditto for this page: https://www.tensorflow.org/js/guide/save_load

So it looks to me like you might have to access a tfjs model from an http endpoint, but it's not explicitly stated like that.

Any input on how to get this to work is much appreciated.

  [1]: https://www.tensorflow.org/js/tutorials/conversion/import_keras
0 Answers
Related