Pytorch基础代码

1. 创建tensor的方法

import torch

x = torch.empty(5, 3)  # 创建未初始化的矩阵
x = torch.rand(5, 3)  # 创建随机初始化矩阵
x = torch.zeros(5, 3, dtype=torch.long)  # 创建 0 矩阵
x = torch.tensor([5.5, 3])  # 直接从数据构造张量
x = x.new_ones(5, 3, dtype=torch.double)  # he returned Tensor has the same `torch.dtype` `torch.device` as this tensor.
x = torch.randn_like(x, dtype=torch.float)  # 重载 dtype!    
x.size()  # 获取张量形状

2. 运算

y = torch.rand(5, 3)  # 加法形式 1
print(torch.add(x, y))  # 加法形式 2
result = torch.empty(5, 3)  
torch.add(x, y, out=result)  # 加法形式 2+
y.add_(x)  # 加法形式 3
x[:, 1]  # 切片操作
x = torch.randn(4, 4)
y = x.view(16)  # 改变形状
z = x.view(-1, 8)  # -1 自动计算维度大小 
x = torch.randn(1)
x.item()  # item() 方法获取 python 数值

3. 与Numpy转换

a = torch.ones(5)
b = a.numpy()  # tensor 转换为 numpy
a.add_(1)  # a 改变,b 也会跟着变

import numpy as np

a = np.ones(5)
b = torch.from_numpy(a)  # numpy 转换为 pytorch

4. GPU加速

# 当GPU可用时,我们可以运行以下代码
# 我们将使用`torch.device`来将tensor移入和移出GPU
if torch.cuda.is_available():
    device = torch.device("cuda")          # a CUDA device object
    y = torch.ones_like(x, device=device)  # 直接在GPU上创建tensor
    x = x.to(device)                       # 或者使用`.to("cuda")`方法
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # `.to`也能在移动时改变dtype

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值