簡體   English   中英

如何在 tensorflow.js 中使用自定義模型對圖像進行分類?

[英]How to classify image using custom model in tensorflow.js?

構建和訓練模型的腳本如下所示:

const model = tf.sequential();

model.add(tf.layers.conv2d({
  inputShape: [160, 200, 3],
  filters: 32,
  kernelSize: 3,
  activation: 'relu',
}));

model.add(tf.layers.flatten());

model.add(tf.layers.dense({units: labels.length, activation: 'softmax'}));  

model.compile({
  optimizer: 'sgd',
  loss: 'categoricalCrossentropy',
  metrics: ['accuracy']
});    

const info = await model.fitDataset(ds, {epochs: 5});
console.log('Accuracy:', info.history.acc);

console.log('Saving...');
await model.save('file://' + MODEL_PATH);
console.log('Saved model');

ds由圖像和標簽組成。 對於 100 張圖像,我得到以下結果:

4478ms 135692us/step - acc=0.109 loss=14.37

它產生了一個 20 MB 的 weights.bin 文件......

坦率地說,我不知道這是否好,因為我不知道如何使用它對新圖像進行分類。

我知道如何加載模型:

const model = await tf.loadLayersModel('file://' + MODEL_PATH + '/model.json');

但就是這樣。

mobilenet 有一個.classify方法,我可以只傳遞一個圖像並輸出預測的標簽。 但這在模型對象上不可用.. 那么我該如何進行呢?

訓練模型后,要對新圖像進行分類,將使用predict方法。 它將返回給定輸入圖像的每個標簽的概率。

output = model.predict(image) // It can be a tensor of one image or a batch of many 
// output is a tensor that contain the probability for each label
images.argMax([-1]) // contain the label of high probability for each input

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM