我使用的是ml5.js,一个张力流am的包装器。我想在浏览器中训练一个神经网络,下载权重,在pyTorch中将它们作为张量处理,然后将它们加载到浏览器的tensorflowjs模型中。如何在这些格式( tfjs <-> pytorch )之间进行转换
浏览器模型有一个save()函数,它生成三个文件。特定于ml5.js (json)的元数据文件、描述模型体系结构(json)的拓扑文件和二进制权重文件(bin)。
// Browser
model.save()// HTTP/Download
model_meta.json (needed by ml5.js)
model.json (needed by tfjs)
model.weights.bin (needed by tfjs)# python backend
import json
with open('model.weights.bin', 'rb') as weights_file:
with open('model.json', 'rb') as model_file:
weights = weights_file.read()
model = json.loads(model_file.read())
####
pytorch_tensor = convert2tensor(weights, model) # whats in this function?
####
# Do some processing in pytorch
####
new_weights_bin = convert2bin(pytorch_tensor, model) # and in this?
####这里是示例javascript代码来生成和加载浏览器中的3个文件。若要加载,请在对话框中同时选择所有3个文件。如果它们是正确的,弹出窗口将显示一个示例预测。
发布于 2020-12-19 05:54:28
我找到了一种将tfjs model.weights.bin转换为numpy的ndarrays的方法。将numpy数组转换为py呼救state_dict是很简单的,它是张量及其名称的字典。
理论
首先,应该理解模型的tfjs表示。model.json描述了模型。在python中,它可以作为字典来阅读。它有以下键:
modelTopology下的另一个json/字典。weightsManifest下有一个json/字典,它描述了包装在相应的model.weights.bin文件中的每个权重的类型/形状/位置。另外,权重清单允许多个.bin文件存储权重。Tensorflow.js有一个附带的python包tensorflowjs,它附带了用于在tf.js二进制和numpy数组格式之间设置朗读和写权重的实用函数。
每个权重文件都被读取为“组”。组是包含键name和data的字典列表,它们引用权重名称和包含权重的numpy数组。还有可选的其他键。
group = [{'name': weight_name, 'data': np.ndarray}, ...] # 1 *.bin file应用程序
安装张力流。不幸的是,它还将安装tensorflow。
pip install tensorflowjs使用这些功能。请注意,为了方便起见,我更改了签名。
from typing import Dict, ByteString
import torch
from tensorflowjs.read_weights import decode_weights
from tensorflowjs.write_weights import write_weights
def convert2tensor(weights: ByteString, model: Dict) -> Dict[str, torch.Tensor]:
manifest = model['weightsManifest']
# If flatten=False, returns a list of groups equal to the number of .bin files.
# Use flatten=True to convert to a single group
group = decode_weights(manifest, weights, flatten=True)
# Convert dicts in tfjs group format into pytorch's state_dict format:
# {name: str, data: ndarray} -> {name: tensor}
state_dict = {d['name']: torch.from_numpy(d['data']) for d in group}
return state_dict
def convert2bin(state_dict: Dict[str: np.ndarray], model: Dict, directory='./'):
# convert state_dict to groups (list of 1 group)
groups = [[{'name': key, 'data': value} for key, value in state_dict.items()]]
# this library function will write to .bin file[s], but you can read it back
# or change the function internals my copying them from source
write_weights(groups, directory, write_manifest=False)https://stackoverflow.com/questions/65350949
复制相似问题