【发布时间】:2020-12-07 20:23:48
【问题描述】:
我对 pytorch 中的 cat 有疑问。我想在 dim=0 上连接张量,例如,我想要这样的东西
>>> x = torch.randn(2, 3)
>>> x
tensor([[ 0.6580, -1.0969, -0.4614],
[-0.1034, -0.5790, 0.1497]])
>>> torch.cat((x, x, x), 0)
tensor([[ 0.6580, -1.0969, -0.4614],
[-0.1034, -0.5790, 0.1497],
[ 0.6580, -1.0969, -0.4614],
[-0.1034, -0.5790, 0.1497],
[ 0.6580, -1.0969, -0.4614],
[-0.1034, -0.5790, 0.1497]])
但是,当我尝试在我的程序中这样做时,我有
def create_batches_to_device(train_df, test_df, device,batch_size=2):
train_tensor = torch.tensor([])
for i in range (batch_size):
rand_2_strs = train_df.sample(2)
tmp_tensor = torch.tensor([rand_2_strs.get('Sigma').iloc[0],rand_2_strs.get('Sigma').iloc[1],
rand_2_strs.get('mu').iloc[0],rand_2_strs.get('mu').iloc[1],
rand_2_strs.get('th').iloc[0],rand_2_strs.get('th').iloc[1],
np.log(weighted_mse(np.array(rand_2_strs.get('Decay').iloc[0]),np.array(rand_2_strs.get('Decay').iloc[1]),t)[0])])
print("it is tmp tensor")
print(tmp_tensor)
train_tensor = torch.cat((train_tensor,tmp_tensor),dim=0)
print("this is after cat")
print(train_tensor)
create_batches_to_device(train_data, test_data, device)
我有结果
it is tmp tensor
tensor([ 0.3244, -0.6401, -0.7959, 0.9019, 0.1468, -1.7093, -6.4419],
dtype=torch.float64)
this is after cat
tensor([ 0.3244, -0.6401, -0.7959, 0.9019, 0.1468, -1.7093, -6.4419],
dtype=torch.float64)
it is tmp tensor
tensor([ 1.2923, -0.3088, -0.1275, 0.6417, -1.3383, 1.4020, 28.9065],
dtype=torch.float64)
this is after cat
tensor([ 0.3244, -0.6401, -0.7959, 0.9019, 0.1468, -1.7093, -6.4419, 1.2923,
-0.3088, -0.1275, 0.6417, -1.3383, 1.4020, 28.9065],
dtype=torch.float64)
无论是dim=0还是dim=-1,结果都是一样的 这是示例(看什么 dim=-1)
def create_batches_to_device(train_df, test_df, device,batch_size=2):
train_tensor = torch.tensor([])
for i in range (batch_size):
rand_2_strs = train_df.sample(2)
tmp_tensor = torch.tensor([rand_2_strs.get('Sigma').iloc[0],rand_2_strs.get('Sigma').iloc[1],
rand_2_strs.get('mu').iloc[0],rand_2_strs.get('mu').iloc[1],
rand_2_strs.get('th').iloc[0],rand_2_strs.get('th').iloc[1],
np.log(weighted_mse(np.array(rand_2_strs.get('Decay').iloc[0]),np.array(rand_2_strs.get('Decay').iloc[1]),t)[0])])
print("it is tmp tensor")
print(tmp_tensor)
train_tensor = torch.cat((train_tensor,tmp_tensor),dim=-1)
print("this is after cat")
print(train_tensor)
create_batches_to_device(train_data, test_data, device)
结果是一样的
it is tmp tensor
tensor([ 1.0183, 0.2162, 0.4987, -0.0165, 0.2094, 0.9425, -14.4564],
dtype=torch.float64)
this is after cat
tensor([ 1.0183, 0.2162, 0.4987, -0.0165, 0.2094, 0.9425, -14.4564],
dtype=torch.float64)
it is tmp tensor
tensor([ 0.2389, -1.0108, -0.2350, 0.7105, -0.9200, 0.3282, 7.5456],
dtype=torch.float64)
this is after cat
tensor([ 1.0183, 0.2162, 0.4987, -0.0165, 0.2094, 0.9425, -14.4564,
0.2389, -1.0108, -0.2350, 0.7105, -0.9200, 0.3282, 7.5456],
dtype=torch.float64)
【问题讨论】: