【问题标题】:How to convert string list to tensor in pytorch?如何在pytorch中将字符串列表转换为张量?
【发布时间】:2021-01-04 07:31:55
【问题描述】:

我正在使用 phytorch 制作和预测几个模型。 因为内存问题,我把张量列表做成了数据框,保存为Excel。 之后,我尝试通过加载存储在 Excel 中的数据来预测模型,但是当我调用 Excel 时,张量列表变成了 str 列表。 如何将此 str 列表更改回张量列表? 我会参考部分代码,原始张量。


def BERT_reasoning(tokens_tensor, segments_tensors):
    model.eval()
    predictions=[]
    for i in range(len(tokens_tensor)):
        if torch.cuda.is_available():
            tokens_tensor[i] = tokens_tensor[i].to('cuda')
            segments_tensors[i] = segments_tensors[i].to('cuda')
            model.to('cuda')
            with torch.no_grad():
                outputs = model(tokens_tensor[i], token_type_ids=segments_tensors[i])
                predictions.append(outputs[0])
                torch.cuda.empty_cache()
    return(predictions)


predictions=[0 for i in range(len(target))]
for i in tqdm(range(len(target))):
    predictions[0]=BERT_reasoning(tokens_tensor[i],segments_tensors[i])
    globals()['df_pred_{}'.format(i)]=pd.DataFrame(predictions[0])
    del predictions[0]
    excel_name='prediction_{}.xlsx'.format(i)
    globals()['df_pred_{}'.format(i)].to_excel(excel_name)
    del globals()['df_pred_{}'.format(i)]
    torch.cuda.empty_cache()



Result :
orginal tensor -
tensor([[[ -7.2395,  -7.2337,  -7.2301,  ...,  -6.6463,  -6.5081,  -4.4686],
         [ -8.1057,  -8.1946,  -8.0791,  ...,  -8.4518,  -7.6345,  -5.3930],
         [-10.7883, -10.6919, -10.5438,  ...,  -9.9607, -10.0536,  -6.8828],
         ...,
         [ -9.0698,  -9.3295,  -8.9949,  ...,  -6.1696,  -7.4357,  -7.4828],
         [ -6.3161,  -6.4182,  -6.5455,  ...,  -5.5366,  -5.7362,  -2.2207],
         [-12.0209, -11.9511, -12.0039,  ..., -11.8723,  -9.6545,  -8.2306]]],
       device='cuda:0')

changed str
"tensor([[[ -7.2395,  -7.2337,  -7.2301,  ...,  -6.6463,  -6.5081,  -4.4686],\n         [ -8.1057,  -8.1946,  -8.0791,  ...,  -8.4518,  -7.6345,  -5.3930],\n         [-10.7883, -10.6919, -10.5438,  ...,  -9.9607, -10.0536,  -6.8828],\n         ...,\n         [ -9.0698,  -9.3295,  -8.9949,  ...,  -6.1696,  -7.4357,  -7.4828],\n         [ -6.3161,  -6.4182,  -6.5455,  ...,  -5.5366,  -5.7362,  -2.2207],\n         [-12.0209, -11.9511, -12.0039,  ..., -11.8723,  -9.6545,  -8.2306]]],\n       device='cuda:0')"

【问题讨论】:

标签: python pytorch


【解决方案1】:

您可以使用内置的eval 函数从字符串中获取张量。请注意,您的张量不应包含省略号(即“...”),因为张量不会被明确定义。所有值都应该出现在您希望恢复的字符串中(否则,无法确定它们应该是什么)。 示例:

t = eval("tensor([[1,2,3],[4,5,6]], device='cuda:0')")

【讨论】:

    猜你喜欢
    • 2017-11-20
    • 2019-07-29
    • 2023-01-23
    • 2018-08-04
    • 2020-08-05
    • 2020-04-07
    • 2019-05-23
    • 2022-01-10
    相关资源
    最近更新 更多