pytorch学习教程

pytorch一小时入门教程

from __future__ import print_function
import torch

#初始化5*3的矩阵
x = torch.empty(5, 3)
print("x0",x)
#创建一个随机初始化矩阵
x = torch.rand(5, 3)
print("x1",x)
#以0填充的矩阵,并定义type
x = torch.zeros(5, 3, dtype=torch.long)
print("x3",x)

#直接从数据构建tensor
x = torch.tensor([5.5, 3])
print("x4",x)

x = x.new_ones(5, 3, dtype=torch.double)      # new_* methods take in sizes
print("x5",x)

x = torch.randn_like(x, dtype=torch.float)    # 重载 dtype!
print("x6",x)

print(x.size())
#注意:torch.Size 本质上还是 tuple ,所以支持 tuple 的一切操作。
#相加
y = torch.rand(5, 3)
print(x + y)
print(torch.add(x, y))

result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)

# adds x to y
y.add_(x)
print(y)
#注意:任何一个就地改变张量的操作后面都固定一个 _ 。例如 x.copy_(y), x.t_()将更改x

#也可以使用像标准的 NumPy 一样的各种索引操作:

print(x[:, 1])


x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)  # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())


#如果是仅包含一个元素的 tensor,可以使用 .item() 来得到对应的 python 数值

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

#将 torch 的 Tensor 转换为 NumPy 数组
a = torch.ones(5)
print(a)
b = a.numpy()
print(b)

a.add_(1)
print(a)
print(b)

#将numpy转化成tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)


# 当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




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值