I created an image classifier in a browser with TensorFlow.js, the code is running well, but when the page is reloaded, the code needs to train the data again (it takes time), so instead of training data again, I want to save the model and load them. I am trying to save the model with this code
await model.save('anime/saved-model');
but it doesn't work, btw, this is my code
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jotaro atau Giorno</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/knn-classifier"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
</head>
<body>
<h1>Test Image Giorno and Jotaro</h1>
<input type='file' onchange="readURL(this);" />
<img id="image_baru" src="#" alt="your image" />
<button id="tombolPrediksi">Prediksi</button>
<h3>output in the console</h3>
</body>
</html>
Javascript
let mobileneModule;
let ClassifierKNN;
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image_baru')
.attr('src', e.target.result)
.width(300)
.height(300);};
reader.readAsDataURL(input.files[0]);}
}
const initScript = async function(){
ClassifierKNN = knnClassifier.create();
mobileneModule = await mobilenet.load();
const jotaroExample = ()=>{
for(let i=1; i<=3;i++){
const im = new Image(300,300);
im.src = 'anime/jotaro/'+i+'.jpg';
im.onload = ()=>{
let trainingImageJotaro = tf.browser.fromPixels(im);
let predJotaro = mobileneModule.infer(trainingImageJotaro,'conv_preds');
ClassifierKNN.addExample(predJotaro,"Jotaro Kujo");
console.log("Giorno ok")
}
im.onload();
}}
const giornoExample = ()=>{
for(let i=1; i<=3;i++){
const im2 = new Image(300,300);
im2.src = 'anime/giorno/'+i+'.jpg';
im2.onload = ()=>{
let trainingImageGiorno = tf.browser.fromPixels(im2);
let predGiorno = mobileneModule.infer(trainingImageGiorno,'conv_preds');
ClassifierKNN.addExample(predGiorno,"Giorno Giovanna");
console.log("Giorno Oke")
}
im2.onload();
}}
await jotaroExample();
await giornoExample();
//save model
await model.save('anime/saved-model');
}
initScript();
const prediksiGambar = async function(){
let imgX = document.getElementById('image_baru');
const tensorX = tf.browser.fromPixels(imgX);
const logitsX = mobileneModule.infer(tensorX,'conv_preds');
let result = await ClassifierKNN.predictClass(logitsX);
console.log('hasil prediksi:');
console.log(result);
}
document.getElementById("tombolPrediksi").addEventListener("click",prediksiGambar);
I hope someone can help me :)
More info from the documentation