文章目录
1.Tensor
1.1 创建tensor
#直接创建
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)
1.2 tensor维度
1.2.1 广义维度
#tensor维度转换,实际上还是二维的
t = torch.reshape(t,(1,12))
#Dense拉扯为一维
t = t.reshape(1,12).squeeze()
#效果与reshape+squeeze一致
t = t.flatten()
1.2.2 操作中的维度
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())
1.3 级联操作cat
t1 = torch.rand(2,2)
t2 = torch.rand(2,2)
t3 = torch.cat((t1,t2),dim=0)
# t3 = torch.cat((t1,t2),dim=1)
1.4 常用Tensor
#对角矩阵
torch.eye(2)
#零矩阵
torch.zeros(2,2)
#一矩阵
torch.ones(2,2)
1.5 tensor在cnn中的形式
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,也就是都是黑白照片。后面的是照片的尺寸
1.6 element-wise
理解为pre-process中的一个trick
会对对应每个元素进行操作。
t1 = torch.rand(3,4)
t2 = torch.ones(1,4)
print(t1 + t2)
print(t1 + 1)