Pytorch学习笔记1——Tensor

Pytorch Learning Notes

Reference:Pytorch官方文档
以上是Pytorch官方的文档,本文主要对其进行翻译整理,并加入一些自己的理解,仅作日后复习查阅所用。

0. Intro

Numpy与Tensor高度相似,为什么有了Numpy还要引入Tensor?
Tensor相对于Numpy来说可以利用Gpu的并行运算优势,提高运算效率。

1. TENSORS

1.1引入方式

import torch

import numpy as np

1.2 定义方式
  • 从数据定义

    data = [[1,2],[3,4]]

    x_data = torch.tensor(data)

  • 从numpy array

    np_array = np.array(data)

    x_np = torch.from_numpy(np_array)

  • 从另一个tensor

    除非特别说明,不然新张量保留原来张量的特征(shape,datatype),值不保留,注意以下例子ones_like值填充为1,rand_like值填充为随机数

    x_ones = torch.ones_like(x_data) #保留特征

    x_rand = torch.rand_like(x_data,dtype=torch.float) #改变张量datatype

  • 从维度定义

    shape = (2,3,)

    rand_tensor = torch.rand(shape)

    ones_tensor = torch.ones(shape)

    zeros_tensor = torch.zeros(shape)

1.3 特性

描述tensor的shape、datatype、 the device on which they are stored(cpu\gpu)。

分别对应为tensor.shape、tensor.dtype、tensor.device。

1.4 操作
  • 设备转移

    tensor在初始化时都被建立在cpu上,可以通过如下方式将tensor转移到gpu上,大量tensor的转移会造成时间空间较大的消耗:

    if torch.cuda.is_available():

    tensor = tensor.to('cuda')

  • tensor拼接

    torch.cat((A,B…),dim=1),(A,B,…)代表要拼接的矩阵,dim=1代表在维度1上拼接

  • 乘法

    # This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
    y1 = tensor @ tensor.T
    y2 = tensor.matmul(tensor.T)
    y3 = torch.rand_like(tensor)
    torch.matmul(tensor, tensor.T, out=y3)
    
    # This computes the element-wise product. z1, z2, z3 will have the same value
    z1 = tensor * tensor
    z2 = tensor.mul(tensor)
    z3 = torch.rand_like(tensor)
    torch.mul(tensor, tensor, out=z3)
    
  • In-place operations(就地操作)

    加上一个后缀’_’

    x.copy_(y), x.t_(), will change x

1.5 Numpy转换

CPU上的tensor与Numpy array共享底层内存位置,因此改变一个就会改变另一个

  • Tensor to NumPy array

    t = torch.ones(5)
    print(f"t: {t}")
    n = t.numpy()
    print(f"n: {n}")
    
    Out:
    t: tensor([1., 1., 1., 1., 1.])
    n: [1. 1. 1. 1. 1.]
    
    #此时改变tensor会直接改变Numpy array
    t.add_(1)
    print(f"t: {t}")
    print(f"n: {n}")
    
    Out:
    t: tensor([2., 2., 2., 2., 2.])
    n: [2. 2. 2. 2. 2.]
    
  • NumPy array to Tensor

    n = np.ones(5)
    t = torch.from_numpy(n)
    
    #此时改变Numpy array会直接改变tensor
    np.add(n, 1, out=n)
    print(f"t: {t}")
    print(f"n: {n}")
    
    Out:
    t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
    n: [2. 2. 2. 2. 2.]
    
    

最近看到一篇对于tensor底层理解的文章,怕放收藏夹里找不到,所以引用过来,主要讲tensor在内存中的存储方式。PyTorch:view() 与 reshape() 区别详解

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值