tf.io.browserFiles
2025年02月11日
一、认识
tf.io.browserFiles(files)
创建一个 IOHandler
,用于从用户选择的文件加载模型文件。该方法适用于从浏览器中用户选择的文件加载模型,例如 model.json
和 weights.bin
文件。
二、语法
const uploadJSONInput = document.getElementById('upload-json');
const uploadWeightsInput = document.getElementById('upload-weights');
const model = await tf.loadLayersModel(tf.io.browserFiles(
[uploadJSONInput.files[0], uploadWeightsInput.files[0]]));
三、用法
3.1 加载离线缓存模型
(async () => {
const baseUrl = self.location.href.replace(/\/[^\/]*$/, "");
const modelUrl = `${baseUrl}/model.json`;
try {
const response = await caches.match(modelUrl);
if (response) {
const modelJson = await response.json();
const modelWeights = await caches.match(
`${baseUrl}/group1-shard1of1.bin`
);
const modelWeightsArrayBuffer = await modelWeights.arrayBuffer();
model = await tf.loadGraphModel(
tf.io.browserFiles([
new File([JSON.stringify(modelJson)], "model.json", {
type: "application/json",
}),
new File([modelWeightsArrayBuffer], "group1-shard1of1.bin", {
type: "application/octet-stream",
}),
])
);
} else {
model = await tf.loadGraphModel(modelUrl);
}
postMessage({ message: "load_model_success" });
console.log("Current Backend: ", tf.getBackend());
} catch (e) {
postMessage({ message: "load_model_failed" });
}
})();