Search code examples
pythonjsontorch

Convert torch tensor into list of dicionaries


I have some data like this:

tensor([[ 0.2054+0.7081j,  0.6586+0.1506j],
        [ 0.4596+0.7250j, -0.1743+0.4825j]])

and I would like to convert it to something like this:

[[{"real":0.2054,"img":0.7081},{"real":0.6586,"img":0.1506}],
 [{"real":0.4596,"img":0.7250},{"real":-0.1743,"img":0.4825}]]

where each value is replaced by a dictionary representing its real and imaginary part, so that I can save it into a JSON file. How should I convert it and "unconvert" it later?

I guess some one-like code might do the work but I not familiar with the syntax of Python and torch.


Solution

  • Since the final object a python list, you can convert it from pytorch with

    x = torch.tensor([[ 0.2054+0.7081j,  0.6586+0.1506j], [ 0.4596+0.7250j, -0.1743+0.4825j]])
    y = x.tolist()
    

    After this you can use 2d list comprehension to convert it to the format you want.

    [[{"real": j.real, "img":j.imag} for j in i]  for i in y]
    

    To go in reverse and you can do the above in reverse

    a = [[complex(j["real"], j["img"]) for j in i]  for i in z]
    torch.tensor(a,dtype=torch.cfloat)
    

    This is only valid for 2D tensors though