user13074756
user13074756

Reputation: 413

TypeError: Object of type Tensor is not JSON serializable - dict to json error in Pytorch

In my pytorch code, I have the below output of dictionary with losses:

errors = {0: tensor(64.4072, device='cuda:0'), 1: tensor(58.2704, device='cuda:0')}

I am converting this dict to a json and writing the json to a file with the below code:

json_object = json.dumps(errors, indent = 4)
    with open("train_loss_dic.json", "w") as outfile:
        outfile.write(json_object)

However, I am getting the below error:

TypeError: Object of type Tensor is not JSON serializable

How to convert Tensor so it is json serializable in Pytorch? My versions are torch==1.9.0 and torchvision==0.10.0

Any help is appreciated!

Upvotes: 0

Views: 15420

Answers (1)

Pippet39
Pippet39

Reputation: 137

Since you have 1-element tensors, you can simply call item() on the tensors to recover a Python float from them. These are serializable.

You can use:

json_errors = {k: v.item() for k, v in errors.items()}

To get a new dict that is serializable.

Hope this helps :)

Upvotes: 2

Related Questions