来自 pandas 向量列的 pytorch 张量

扎眼的阳光 pytorch 441

原文标题pytorch tensor from pandas columns of vectors

我想将熊猫的列转换为 PyTorch 张量。该列的每个单元格都有一个 300 暗淡的 NumPy 向量(一个嵌入)。

我试过这个:

torch.from_numpy(g_list[1]['sentence_vector'].to_numpy())

但它抛出了这个错误:

TypeError: can’t convert np.ndarray of type numpy.object_。唯一支持的类型有:float64、float32、float16、complex64、complex128、int64、int32、int16、int8、uint8和bool。

原文链接:https://stackoverflow.com//questions/71664538/pytorch-tensor-from-pandas-columns-of-vectors

回复

我来回复
  • Phoenix的头像
    Phoenix 评论

    如果您有此数据框,其中每列是 2 个数字的向量:

    import torch
    import pandas as pd
    
    df = pd.DataFrame({'a':    [[ 3,  29],[ 3,  29]],
                       'b': [[94, 170],[ 3,  29]],
                       'c': [[31, 115],[ 3,  29]]})
    

    enter image description here

    要将此数据帧转换为 pytorch 张量,只需将数据帧的值转换为列表,然后转换为张量:

    t = torch.Tensor(list(df.values))
    
    #output
    
    tensor([[[  3.,  29.],
             [ 94., 170.],
             [ 31., 115.]],
    
            [[  3.,  29.],
             [  3.,  29.],
             [  3.,  29.]]])
    

    t的形状是[2,3,2],每个列表里面有2行3列2个元素。

    2年前 0条评论