我已经使用make_image_classifier命令行工具重新训练了mobilenet_v2模型,以重新训练模型,并使用tfjs-converter为浏览器准备了模型。
make_image_classifier \
--image_dir image_data \
--tfhub_module https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4 \
--saved_model_dir trained_models/1 \
--labels_output_file class_labels.txt \
--tflite_output_file trained_model.tflite
tensorflowjs_converter \
--input_format=tf_saved_model \
--output_format=tfjs_graph_model \
--signature_name=serving_default \
--saved_model_tags=serve \
./trained_models/1 \
./web_model
为了测试TF Lite模型,我使用了tflite example code。我遵循了工具的说明,因此使用了提供的代码。
如果现在尝试在浏览器中预测图像,则不会获得预期的输出。看起来只打印了概率而没有标签。
const MODEL_URL = 'model/model.json';
const model = await tf.loadGraphModel(MODEL_URL);
var canvas = document.getElementById("canvas").getContext("2d");;
const img = canvas.getImageData(0,0, 224,224)
const tfImg = tf.browser.fromPixels(img).expandDims(0);
const smalImg = tf.image.resizeBilinear(tfImg, [224, 224]);
let result = await model.predict(smalImg);
console.log(result.print())
输出:张量[[0.0022475、0.0040588、0.0220788、0.0032885、0.000126、0.0030831、0.8462179、0.1188994],]
使用python测试模型效果很好,我得到了带有标签和概率的预期输出。我做错了吗?
在python代码中,在前提之后有以下内容:
# output_data is the predition result
results = np.squeeze(output_data)
top_k = results.argsort()[-5:][::-1]
labels = load_labels(args.label_file)
for i in top_k:
if floating_model:
print('{:08.6f}: {}'.format(float(results[i]), labels[i]))
else:
print('{:08.6f}: {}'.format(float(results[i] / 255.0), labels[i]))
在js中进行预测后,需要执行相同的处理。 labels
的数组包含数据集的所有标签。它需要以js的形式加载,就像它是从labels.txt
文件的python代码中加载的一样。
const topkIndices = result.topk(5)
const topkIndices = await topk.indices.data();
const categories = (Array.from(topkIndices)).map((p: number) => labels[p]);
const topkValues = await topk.values.data()
const data = Array.from(topkValues).map(p => p * 100);
// categories will contain the top5 labels and
// data will contain their corresponding probabilities