[PyTorch]基础学习


此博客为自用学习记录

本文内容速览

  1. tensor在CPU与GPU之间的移动
  2. tensor的初始化与基本计算
  3. ‘广播’
  4. 创建服从正态分布的随机数矩阵
  5. torch中几种不同的乘法操作
  6. torch自动求梯度与中断梯度的追踪

实验

import torch
from torch import tensor
import numpy

# 判断pytorch是否支持GPU加速
print(torch.cuda.is_available())
# 将Tensor在CPU和GPU之间相互移动
if torch.cuda.is_available():
    device = torch.device('cuda')  # GPU
    x = torch.ones(2, 3)
    y = torch.ones_like(x, device=device)
    print(x, y)
    x = x.to(device)
    z = x + y
    print(x, z)
    print(z.to('cpu', torch.double))


print('--------------1--------------')
# 1、使用tensor初始化一个1*3矩阵M和2*1的N,并进行减法操作
# 第一种方法
M = torch.tensor([1, 2, 3])
N = torch.tensor([[4], [5]])
print(M, M.size())
print(N, N.size())
# 进行减法操作的时候,发生了“广播”,M-> [[1,2,3],[1,2,3]],N-> [[4,4,4],[5,5,5]]
print('result=', M-N)
# 第二种方法
M = torch.rand(1, 3)
N = torch.rand(2, 1)
print(M)
print(N)
print('result=', torch.sub(M, N))
# 第三种方法, 原地操作
# M.sub_(N) 形状不同不能原地减法(不能广播
print(M)

print('--------------2--------------')
# 2、创建两个大小分别为3*2和4*2的随机数矩阵P和Q,要求服从均值为0,标准差为0.01的正态分布,
# 对Q转置得到Q*;求P和Q*的矩阵相乘
# P = torch.randn(3, 2)  # 标准正态分布,N(0,1)
P = torch.normal(mean=0, std=0.01, size=(3, 2))
Q = torch.normal(mean=0, std=0.01, size=(4, 2))
print('P', P)
print('Q', Q)
Q_ = Q.t()
print('Q_', Q_)
# torch.mul(a,b)是矩阵的对应位元素相乘,可以广播;而torch.mm是矩阵相乘
# torch.matmul在2维情况下就等价于torch.mm,而torch.mm仅能处理【矩阵】乘法
print('result', torch.mm(P, Q_))

print('--------------3--------------')
# 给定公式 y3=y1+y2=x^2+x^3,且x=1,利用tensor,求y3对x的梯度
# 要求在计算过程中,计算x^3时中断梯度的追踪,观察结果 (可使用with torch.no_grad()
x = torch.tensor([1.0], requires_grad=True)
print('x', x)
y1 = x * x
print('y1', y1)
with torch.no_grad():
    y2 = x * y1
    print('y2', y2)
    print(y2.requires_grad)
y3 = y1 + y2
print(y3)
print(y3.requires_grad)
y3.backward()  # 等价于 y3.backward(torch.tensor(1.))
print(x.grad)
x.grad.data.zero_()  # 梯度会逐步累加,一般清0,此处没有循环不写也可以

输出结果

True
tensor([[1., 1., 1.],
        [1., 1., 1.]]) tensor([[1., 1., 1.],
        [1., 1., 1.]], device='cuda:0')
tensor([[1., 1., 1.],
        [1., 1., 1.]], device='cuda:0') tensor([[2., 2., 2.],
        [2., 2., 2.]], device='cuda:0')
tensor([[2., 2., 2.],
        [2., 2., 2.]], dtype=torch.float64)
--------------1--------------
tensor([1, 2, 3]) torch.Size([3])
tensor([[4],
        [5]]) torch.Size([2, 1])
result= tensor([[-3, -2, -1],
        [-4, -3, -2]])
tensor([[0.2710, 0.0207, 0.7864]])
tensor([[0.9386],
        [0.1935]])
result= tensor([[-0.6676, -0.9179, -0.1522],
        [ 0.0775, -0.1728,  0.5929]])
tensor([[0.2710, 0.0207, 0.7864]])
--------------2--------------
P tensor([[-0.0055, -0.0075],
        [-0.0102, -0.0091],
        [-0.0032,  0.0034]])
Q tensor([[ 0.0222,  0.0066],
        [ 0.0066, -0.0004],
        [-0.0072,  0.0109],
        [-0.0162,  0.0076]])
Q_ tensor([[ 0.0222,  0.0066, -0.0072, -0.0162],
        [ 0.0066, -0.0004,  0.0109,  0.0076]])
result tensor([[-1.7286e-04, -3.3458e-05, -4.1710e-05,  3.1993e-05],
        [-2.8717e-04, -6.3942e-05, -2.4319e-05,  9.6110e-05],
        [-4.9104e-05, -2.2854e-05,  5.9968e-05,  7.7693e-05]])
--------------3--------------
x tensor([1.], requires_grad=True)
y1 tensor([1.], grad_fn=<MulBackward0>)
y2 tensor([1.])
False
tensor([2.], grad_fn=<AddBackward0>)
True
tensor([2.])

Process finished with exit code 0
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值