2

Having defined an API based on a transformer model which I send request to, I got as output an object of class string supposed to represent a torch tensor.

import requests
import json
import torch

response = requests.post("http://127.0.0.1:5000/predict", json="This is a test.")
data = response.json()
print(data)

tensor([[-5.5169e-01,  5.1988e-01, -1.4731e-01,  4.6096e-02, -5.5753e-02,
         -6.9530e-01,  7.3424e-01,  3.0014e-01,  4.0528e-01, -1.7587e-01,
          1.2586e-01,  5.6712e-01, -4.0757e-01,  1.5796e-01,  9.4700e-01,
          6.2967e-01,  3.1027e-01,  1.0169e-02,  3.1380e-02,  1.2585e-01,
          2.3633e-01,  6.0813e-01, -1.0548e+00, -1.8581e-01, -5.9870e-02,
          1.2952e-01, -3.8818e-01,  2.3425e-01]])

I checked in the requests module documentation, but couldn't find any way to convert this fully strings into a torch tensor?

iacob
  • 20,084
  • 6
  • 92
  • 119
  • The simplest way could be to import `tensor` from TensorFlow and then `eval(data, globals={'tensor': tensor})` – ForceBru Mar 23 '21 at 14:59
  • Does this answer your question? [Extract tensor from string](https://stackoverflow.com/questions/62814427/extract-tensor-from-string) – iacob Mar 23 '21 at 15:53

1 Answers1

2

You can use eval to evaluate the code contained in the string:

from torch import tensor

my_tensor = eval(data)
iacob
  • 20,084
  • 6
  • 92
  • 119