pytorch中的Tensor使用入门

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值