PyTorch 入门

1 什么是 PyTorch?

PyTorch 是一个基于 Python 的科学计算包,主要定位两类人群:

  • NumPy 的替代品,可以利用 GPU 的性能进行计算。

  • 深度学习研究平台拥有足够的灵活性和速度

2 Tensors (张量)

一些tensor运算:

import torch
x = torch.empty(2,4) # 或者 x = torch.Tensor(2,4)
y = torch.ones(2,4) # 类似,还可以用torch.zeros(2,4)
z = torch.randn(2,4) # 服从标准正态分布,随机初始化,还可以torch.rand()
print(x) 
print(y)
print(z)

输出:
tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.]])
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.]])
tensor([[-0.4729, -1.1895, 1.1723, -0.9725],
[ 0.3441, -0.3834, -0.4745, 1.7842]])

torch.randn_like(x, dtype=torch.float)#创建一个 tensor 基于已经存在的 tensor
tensor([[ 1.6117,  0.4020,  0.3922, -0.1897],
        [-0.0896, -0.4295,  0.5841, -0.1743]])
print(y+z) # 加法运算1
result = torch.empty_like(x)
print(torch.add(y,z, out = result))# 加法运算2
y.add(z) # 加法运算3: y不会改变
y.add(z) # 加法运算3: y会改变

输出:
tensor([[ 0.5271, -0.1895, 2.1723, 0.0275],
[ 1.3441, 0.6166, 0.5255, 2.7842]])
tensor([[ 0.5271, -0.1895, 2.1723, 0.0275],
[ 1.3441, 0.6166, 0.5255, 2.7842]])
tensor([[ 0.5271, -0.1895, 2.1723, 0.0275],
[ 1.3441, 0.6166, 0.5255, 2.7842]])

a = torch.tensor([1,2,3])
print(a[0])
print(a[0].item()) # item()方法可以将tensor转化为python的scale,但是只能对于单个数值使用
print(a.size()) # 获取维度信息

输出:
tensor(1)
1

torch.Size([3])
x = torch.empty(2,4) 
print(x[1,:]) # 切片操作,类似于Numpy
print(x[1,1:3])
y.copy_(x) # 复制

输出:
tensor([0., 0., 0., 0.])
tensor([0., 0.])
tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.]])

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值