You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将含Tensor类型嵌入的字典保存为JSON时遇序列化错误,求解决

如何将包含PyTorch Tensor的字典保存为JSON文件?

你遇到的问题是JSON无法直接序列化PyTorch Tensor对象——JSON仅支持字符串、数字、列表、字典等基本数据类型,而Tensor属于自定义类实例,不在默认序列化范围内。以下是两种可行的解决方法:

方法1:自定义JSON编码器

通过继承json.JSONEncoder并重写default方法,实现对Tensor类型的自动转换:

import json
import torch

class TensorEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, torch.Tensor):
            # 将Tensor转换为可序列化的列表
            return obj.tolist()
        # 其他类型交给父类处理
        return super().default(obj)

# 示例字典
embedding_dict = {'file_name_1': torch.tensor([0.1, 0.2]), 'file_name_2': torch.tensor([0.3, 0.4])}

# 使用自定义编码器保存JSON
with open("savedata.json", "w") as write_file:
    json.dump(embedding_dict, write_file, indent=4, cls=TensorEncoder)

方法2:提前转换Tensor为列表

直接遍历字典,将所有Tensor转换为列表后再保存,适合简单场景:

import json
import torch

embedding_dict = {'file_name_1': torch.tensor([0.1, 0.2]), 'file_name_2': torch.tensor([0.3, 0.4])}

# 转换字典中所有Tensor为列表
serializable_dict = {key: tensor.tolist() for key, tensor in embedding_dict.items()}

# 保存为JSON
with open("savedata.json", "w") as write_file:
    json.dump(serializable_dict, write_file, indent=4)

读取并还原Tensor

如果需要从JSON文件恢复原Tensor结构,只需将读取到的列表重新转换为Tensor即可:

with open("savedata.json", "r") as read_file:
    loaded_data = json.load(read_file)

# 还原为PyTorch Tensor
restored_dict = {key: torch.tensor(value) for key, value in loaded_data.items()}

内容的提问来源于stack exchange,提问作者Atharva_S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:52:50