pytorch中的Tensor使用入門

2021-10-05 13:41:05 字數 2192 閱讀 3243

1.3 級聯操作cat

1.4 常用tensor

1.5 tensor在cnn中的形式

1.6 element-wise

#直接建立

t = torch.rand(3,

4)#把numpy轉為tensor

t = np.random.rand(3,

4)#torch.tensor是呼叫乙個類,會預設把data轉為float

t = torch.tensor(t)

#torch.tensor是使用工廠方法,不會轉化資料型別

t = torch.tensot(t)

#tensor維度轉換,實際上還是二維的

t = torch.reshape(t,(1

,12))

#dense拉扯為一維

t = t.reshape(1,

12).squeeze(

)#效果與reshape+squeeze一致

t = t.flatten(

)

t1 = torch.tensor([[

1,1,

1,1]

,[2,

2,2,

2],[

3,3,

3,3]

])#tensor([6., 6., 6., 6.])

print

(t1.

sum(dim=0)

)print

(t1[0]

+t1[1]

+t1[2]

)#tensor([ 4., 8., 12.])

print

(t1.

sum(dim =1)

)print

(t1[0]

.sum()

+ t1[1]

.sum()

+ t1[2]

.sum()

)

t1 = torch.rand(2,

2)t2 = torch.rand(2,

2)t3 = torch.cat(

(t1,t2)

,dim=0)

# t3 = torch.cat((t1,t2),dim=1)

#對角矩陣

torch.eye(2)

#零矩陣

torch.zeros(2,

2)#一矩陣

torch.ones(2,

2)

t1 = torch.tensor([[

1,1,

1,1]

,[1,

1,1,

1],[

1,1,

1,1]

,[1,

1,1,

1]])

t2 = torch.tensor([[

2,2,

2,2]

,[2,

2,2,

2],[

2,2,

2,2]

,[2,

2,2,

2]])

t3 = torch.tensor([[

3,3,

3,3]

,[3,

3,3,

3],[

3,3,

3,3]

,[3,

3,3,

3]])

#shape(3,4,4) -> batch,heigth,width

tt = torch.stack(

(t1,t2,t3)

)#shape(3,1,4,4) -> batch,channel,heigth,width

tt = torch.reshape(tt,(3

,1,4

,4))

#可以看成有3張**,而每張**的channel都是1,也就是都是黑白**。後面的是**的尺寸

理解為pre-process中的乙個trick

會對對應每個元素進行操作。

t1 = torch.rand(3,

4)t2 = torch.ones(1,

4)print

(t1 + t2)

print

(t1 +

1)

pytorch中tensor型別轉換

tensor轉numpy tensor.numpy numpy轉tensor torch.from numpy 2 tensor與list tensor轉list tensor.tolist list轉tensor torch.tensor 3 tensor型別轉換 tensor torch.ten...

pytorch中tensor的型別轉換

1 資料型別轉換 在tensor後加 long int float double 等即可,也可以用.to 函式進行轉換,所有的tensor型別可參考 2 資料儲存位置轉換 cpu張量 gpu張量,使用data.cuda gpu張量 cpu張量,使用data.cpu 3 與numpy資料型別轉換 te...

Pytorch中的Tensor常用的型別轉換函式

pytorch中的tensor常用的型別轉換函式 inplace操作 1 資料型別轉換 在tensor後加.long int float double 等即可,也可以用.to 函式進行轉換,所有的tensor型別可參考 2 資料儲存位置轉換 cpu張量 gpu張量,使用data.cuda gpu張量...