从字符串中提取张量 [英] Extract tensor from string

查看:55
本文介绍了从字符串中提取张量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以直接提取这个字符串中包含的张量tensor([-1.6975e+00, 1.7556e-02, -2.4441e+00, -2.3994e+00, -6.2069e-01])?我正在寻找一些可以做到这一点的 tensorflowpytorch 函数,就像用于字典和列表的 ast.literal_eval 函数一样.>

如果没有,请提供一个pythonic方法好吗?

我正在考虑这样的事情:

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))

但我不确定这是最好的方法.

解决方案

您可以使用 eval:

import torch.tensor 作为张量评估(张量列表)>>>张量([-1.6975, 0.0176, -2.4441, -2.3994, -0.6207])

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.

解决方案

You can use eval:

import torch.tensor as tensor

eval(tensor_list)
>>> tensor([-1.6975,  0.0176, -2.4441, -2.3994, -0.6207])

这篇关于从字符串中提取张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆