在PyTorch中提取张量

时间:2019-10-01 15:05:39

标签: pytorch torch

因为这个张量是PyTorch,

tensor([[ 0.7646,  0.5573,  0.4000,  0.2188,  0.7646,  0.5052,  0.2042,  0.0896,
          0.7667,  0.5938,  0.3167,  0.0917],
        [ 0.4271,  0.1354,  0.5000,  0.1292,  0.4260,  0.1354,  0.4646,  0.0917,
         -1.0000, -1.0000, -1.0000, -1.0000],
        [ 0.7208,  0.5656,  0.3000,  0.1688,  0.7177,  0.5271,  0.1521,  0.0667,
          0.7198,  0.5948,  0.2438,  0.0729],
        [ 0.6292,  0.8250,  0.4000,  0.2292,  0.6271,  0.7698,  0.2083,  0.0812,
          0.6281,  0.8604,  0.3604,  0.0917]], device='cuda:0')

如何将这些值提取到新的Tensor中

0.7646,  0.5573,  0.4000,  0.2188
0.4271,  0.1354,  0.5000,  0.1292

如何将两行中的前四行转换为新的张量?

1 个答案:

答案 0 :(得分:2)

实际上,@ zihaozhihao在评论中回答了该问题,但是如果您想知道从何而来,如果您这样构造Tensor会有所帮助:

import pyodbc
import pandas as pd
link='driver=xxx; AUTHENTICATION=xxx;DBCNAME=xx;UID=xxx;PWD=xx'
connection=pyodbc.connect(link,autocommit=True)
query='select col1,col2 from table where acct in (12345,67890,etc);'
df=pd.read_sql(query,connection)

因此,现在更清楚地知道您有一个形状(4,12),可以像excel文件一样考虑它,您有4行12列。现在,您想要从前两行中提取前四列,这就是您的解决方案的原因:

x = torch.Tensor([
        [ 0.7646,  0.5573,  0.4000,  0.2188,  0.7646,  0.5052,  0.2042,  0.0896, 0.7667,  0.5938,  0.3167,  0.0917],
        [ 0.4271,  0.1354,  0.5000,  0.1292,  0.4260,  0.1354,  0.4646,  0.0917, -1.0000, -1.0000, -1.0000, -1.0000],
        [ 0.7208,  0.5656,  0.3000,  0.1688,  0.7177,  0.5271,  0.1521,  0.0667, 0.7198,  0.5948,  0.2438,  0.0729],
        [ 0.6292,  0.8250,  0.4000,  0.2292,  0.6271,  0.7698,  0.2083,  0.0812, 0.6281,  0.8604,  0.3604,  0.0917]

                ])