2

Is it possible to extract directly the tensor included in this string tensor([-1.6975e+00, 1.7556e-02, -2.4441e+00, -2.3994e+00, -6.2069e-01])? I'm looking for some tensorflow or pytorch function that can do it, like the ast.literal_eval function does for dictionaries and lists.

If not, could you provide a pythonic method, please?

I'm thinking about something like this:

tensor_list = "tensor([-1.6975e+00,  1.7556e-02, -2.4441e+00, -2.3994e+00, -6.2069e-01])"
str_list = tensor_list.replace("tensor(", "").replace(")", "")
l = ast.literal_eval(str_list)
torch.from_numpy(np.array(l))

But I'm not sure this is the best way.

Belkacem Thiziri
  • 605
  • 2
  • 8
  • 31

1 Answers1

3

You can use eval:

import torch.tensor as tensor

eval(tensor_list)
>>> tensor([-1.6975,  0.0176, -2.4441, -2.3994, -0.6207])
iacob
  • 20,084
  • 6
  • 92
  • 119
Dishin H Goyani
  • 7,195
  • 3
  • 26
  • 37
  • Does the `eval` function recognize the tensor inside the string? this is awesome! – Belkacem Thiziri Jul 09 '20 at 12:36
  • 2
    [`eval`](https://stackoverflow.com/questions/9383740) will run string as python code. and we have added alias for `tensor` before (`import torch.tensor as tensor`) so it worked. – Dishin H Goyani Jul 09 '20 at 15:42