How To Use Saved Model In Tensorflow.js
I have found that I could use python-trained tensorflow model in tensorflow.js. I converted the model with tensorflowjs_wizard and followed their instructions. As a result, I got j
Solution 1:
In order to complete @Nikita's answer:
- Since your training data was all int, the model expects int numbers. It's better to convert them to float while training. For example like this:
train = np.array(train).astype('float32')
train_labels = np.array(train_labels).astype('float32')
model.fit(train ,train_labels , epochs=20)
- One other thing may be important is that, since you have not defined activation function for your last layer, you get prediction in any range, even negative numbers. It's better to remove
from_logits=True
from loss function and addactivation=softmax
to last layer:
model = tf.keras.Sequential([
tf.keras.layers.Dense(1,activation="relu"),
tf.keras.layers.Dense(100, activation="relu"),
tf.keras.layers.Dense(4,activation="softmax")
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=['accuracy'])
- You will get 4 numbers as output, and if you want to get category index, you may use
argmax
after prediction. So, modification code maybe something like this:
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"> </script>
<script>
async function run(){
const MODEL_URL = 'http://127.0.0.1:8887/model.json';
const model = await tf.loadLayersModel(MODEL_URL);
console.log(model.summary());
const input = tf.tensor2d([1, 3, 0, 3, 3, 1, 2, 3, 2], [1,9]);
const result = await model.predict(input);
const res = await result.argMax(axis=1);
alert(res)
}
run();
</script>
</head>
<body></body>
</html>
.json
file stores your model architecture, and.bin
file(s) stores trained weights of your model. You can not delete it.tf.loadLayersModel()
loads a model composed of layer objects, including its topology and optionally weights. It's limitations is ,this is not applicable to TensorFlowSavedModel
s or their converted forms. For those models, you should usetf.loadGraphModel()
.
Solution 2:
After hours of networking, I found that these two are the reasons.
const a = tf.tensor2d([1, 3, 0, 3, 3, 1, 2, 3, 2],[1,9],'int32');
and
const tensor = await getData();
The former reshapes the input data. The latter is important, to wait for data to be read.
Post a Comment for "How To Use Saved Model In Tensorflow.js"