【发布时间】:2021-10-05 01:12:42
【问题描述】:
我创建了一个模型,该模型将 Mobilenet V2 应用于 Google colab 中的卷积基础层。然后我使用以下命令对其进行了转换:
path_to_h5 = working_dir + '/Tensorflow_PY_Model/SavedModel.h5'
path_tfjs = working_dir + '/TensorflowJS'
!tensorflowjs_converter --input_format keras \
{path_to_h5} \
{path_tfjs}
我用一张图片来测试对两者进行分类。在 python 中,我使用下面的代码进行预测:
from google.colab import files
from io import BytesIO
from PIL import Image
import matplotlib.pyplot as plt
uploaded = files.upload()
last_uploaded = list(uploaded.keys())[-1]
im = Image.open(BytesIO(uploaded[last_uploaded]))
im = im.resize(size=(224,224))
img = np.array(im)
img = img / 255.0
prediction1 = model.predict(img[None,:,:])
print(prediction1)
上面的代码返回这个数组:
[6.1504150e-05 4.8508531e-11 5.1813848e-15 2.1887154e-12 9.9993849e-01
8.4171114e-13 1.4638757e-08 3.4268971e-14 7.5719299e-15 1.0649443e-16]]
之后,我尝试使用以下代码在 Javascript 中进行预测:
async function predict(image) {
var model = await tf.loadLayersModel('./TFJs/model.json');
let predictions = model.predict(preprocessImage(image)).dataSync();
console.log(predictions);
return results;
}
function preprocessImage(image) {
let tensor = tf.browser.fromPixels(image);
const resizedImage = tensor.resizeNearestNeighbor([224,224]);
const batchedImage = resizedImage.expandDims(0);
return batchedImage.toFloat().div(tf.scalar(255)).sub(tf.scalar(1));
}
document.querySelector('input[type="file"]').addEventListener("change", async function () {
if (this.files && this.files[0]) {
img = document.getElementById("uploaded-img");
img.onload = () => {
URL.revokeObjectURL(img.src); // no longer needed, free memory
};
img.src = URL.createObjectURL(this.files[0]);
predictionResult = await predict(model, img);
displayResult(predictionResult);
}
});
但是,使用与我在 Python 上进行预测时使用的图像相同的图像,它会返回此结果,并且无论我更改图像,它永远不会改变。
Float32Array(10) [0.9489052295684814, 0.0036257198080420494, 0.000009185552698909305,
0.000029705168344662525, 0.04141413792967796, 1.4301890782775217e-9, 0.006003820803016424,
2.8357267645162665e-9, 0.000011812648153863847, 4.0659190858605143e-7]
那么如何解决这个问题呢?我还应该做什么?提前感谢您的回答和建议!
【问题讨论】:
-
呸,这是个烦人的问题。对于相同的图像,您确定预处理是相同的吗?
-
我认为它已经相同了,我检查了预处理的形状结果,它与 JS 中的 ([1,224,224,3]) 完全相同,同时在 python 中它是 [None, 224, 224, 3].
-
是的,形状有效。但也许图像每次都是一样的,或者是一些奇怪的行为。图像张量本身是否相同?
-
谢谢。我发现我的网络应用收到的图片全是 0,所以这就是它行为错误的原因。
-
哈哈,知道了,我自己也做过同样的事情。没问题,祝你好运。
标签: tensorflow tensorflow.js transfer-learning tensorflowjs-converter