pytorch基本学习

详见:

pytorch:http://121.199.45.168:8020/1/

自然语言处理入门:http://121.199.45.168:8005/

文本预处理:http://121.199.45.168:8003/1/#11

经典序列模型:http://121.199.45.168:8004/1/

RNN及其变体:http://121.199.45.168:8002/1/

Transformer:http://121.199.45.168:8001/1/

迁移学习:http://121.199.45.168:8007/1/

pytorch中基本元素的操作

tensor张量:张量的概念类似于、numpy中的narray数据结构,最大的区别在于tensor可以利用GPU的加速功能

创建矩阵的操作(本身不包括值,只是磁盘上的原始值)

x = torch.empty(5,3)
print(x)

创建随机初始化矩阵(0-1范围内)(插一句:高斯分布也叫正态分布:均值为0,方差为1)

x = torch.rand(5,3)
print(x)

创建全零矩阵,指定元素类型为long

x = torch.zeros(5,3,dtype=torch.long)
print(x)

直接通过数据创建张量

x = torch.zeros([2.5,3.5])
print(x)

通过已有的张量创建相同尺寸的张量

x = x.new_ones(5,3,dtype = torch.double)#全一张量
print(x)

y = torch.randn_like(x,dtype = torch.float)#得到相同尺寸张量
print(y)

print(x.size())#得到张量的形状

torch.size类型是一个元组(用两个值来接受这个元组)

pytorch基本运算操作

加法操作:

#第一种+
x = torch.rand(5,3)
y = torch.rand(5,3)
print(x+y)

#第二种或者是用torch.add()方法
print(torch.add(x,y))#结果都一样

#第三种torch.add(x,y,out = result)
result = torch.empty(5,3)
torch.add(x,y,out = result)
print(result)

#第四种原地置换
y.add_(x)#执行y = y+x

减乘除类似于此

#切片
print(x[:,1])#所有行第一列,列表结果
#切片
print(x[:,:3])#打印012列

和numpy操作一样

x = torch.rand(4,4)
y = x.view(16)#改变张量形状
z = x.view(-1,8)#行自动匹配
print(x.size(),y.size,z.size)#4 4   1 6    2 8

 如果张量中有唯一的元素,item函数可以返回python类型

x = torch.rand(1)
print(x.item())

关于torch tensor 和Numpy array之间的相互转化

torch tenser 和numpy array共享底层内存

将torch tensor转化为numpy

x = torch.ons(5)
y = x.numpy()
print(x)
print(y)

a.add_(1)
print(x)
print(y)#y会随着x改变,由于是共享底层内存

反过来

x = numpy.ons(5)
y = torch.from_numpy(x)
print(x)
print(y)

numpy.add(x,1,out = x)
print(x)
print(y)#y同样会随着x改变而改变

注:所有在CPU上的Tensor,除了CharTensor,都可以转换为Numpy array并可以反向转换

关于Cuda Tensor:Tensor可以用to()方法将其移动到任意设备上

if torch.cuda.is_available():
    #定义设备
    device = torch.device("cuda")
    #直接在GPU上创建张量y,在CPU上创建张量x
    x = torch.randn(1)
    y = torch.ones_like(x,device = device)#得到相同尺寸全零张量
    #需要将x转移到GPU上才能进行加法运算
    x = x.to(device)#x = x.to("cuda")也可以
    z = x+y
    #把z转移到cpu上
    print(z.to("cpu",float))

二、Pytorch初步应用

2.1使用Pytorch构建神经网络

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值