Pytorch学习笔记一——Tensor创建,改变形状等操作

主要记录一些Pytorch使用过程中的操作及技巧,便于以后的查阅与参考。

PyTorch是一个开源的Python机器学习库。

  • 2017年1月,由Facebook人工智能研究院(FAIR)基于Torch推出的一人工智能库
  • 一个基于Python的可续计算包,提供两个高级功能:

具有强大的GPU加速的张量计算(如NumPy)

import torch

print(torch.cuda.is_availble())
"""
True: GPU
False: CPU
"""

包含自动求导系统的的深度神经网络

Pytorch官网

今天在Pytorch官网的版本已是最新的1.4了,但在本笔记集里还是以之前安装的1.3版本为主。


pytorch安装包
pytorch.version
import argparse
import os

import torch
import torchvision

os.environ['CUDA_VISIBLE_DEVICES'] = '0' # #设置当前使用的GPU设备仅为0号设备  设备名称为'/gpu:0'。可以指定使用的环境,是GPU还是CPU。

print(torchvision.__version__) #获取torchvision版本
print(torch.__version__) # 获取torch版本

torch.cuda.set_device(0) # 设定使用指定GPU:0号GPU
print(torch.cuda.is_available()) # 是否有已经配置好可以使用的GPU (若True则有)
print(torch.cuda.device_count())  # 可用GPU块数
print(torch.cuda.get_device_capability()) #获取所使用的GPU的计算力
print(torch.cuda.get_device_name()) #获取该GPU的名称
print(torch.cuda.get_device_properties(0)) #获取指定GPU的常见属性,必须指定GPU,否则报错
"""
>>> torch.cuda.current_device()
0
>>> torch.cuda.is_available()
True
>>> torch.cuda.current_device()
0
>>> torch.cuda.device_count()
1
>>> torch.version.cuda
'10.1'
>>> torch.backends.cudnn.version()
7501
>>> torch.cuda.get_device_name(0)
'GeForce GTX 1660 Ti'
>>> torch.cuda.get_device_capability(0)
(7, 5)
>>> torch.cuda.get_device_properties(0)
_CudaDeviceProperties(name='GeForce GTX 1660 Ti', major=7, minor=5, total_memory=6144MB, multi_processor_count=24)
>>> 
"""

Tensor创建等基础操作

创建Tensor数据

  • 以torch.rand(*size)为例
  • 大部分操作跟numpy相似的。
import torch

# 创建一5*3的随机矩阵,数值为0~1区间均匀分布
x = torch.rand(5, 3)
print(x)
"""
tensor([[0.0602, 0.7614, 0.0417],
        [0.3430, 0.8572, 0.8224],
        [0.5222, 0.5827, 0.3820],
        [0.9570, 0.0863, 0.9979],
        [0.1126, 0.1289, 0.2431]])
"""
# 可通过help(torch.rand)查看该函数的具体使用
help(torch.rand)
""""
rand(...)
    rand(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
    
    Returns a tensor filled with random numbers from a uniform distribution
    on the interval :math:`[0, 1)`
    
    The shape of the tensor is defined by the variable argument :attr:`size`.
    
    Args:
        size (int...): a sequence of integers defining the shape of the output tensor.
            Can be a variable number of arguments or a collection like a list or tuple.
        out (Tensor, optional): the output tensor.
        dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
            Default: if ``None``, uses a global default (see :func:`torch.set_default_tensor_type`).
        layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
            Default: ``torch.strided``.
        device (:class:`torch.device`, optional): the desired device of returned tensor.
            Default: if ``None``, uses the current device for the default tensor type
            (see :func:`torch.set_default_tensor_type`). :attr:`device` will be the CPU
            for CPU tensor types and the current CUDA device for CUDA tensor types.
        requires_grad (bool, optional): If autograd should record operations on the
            returned tensor. Default: ``False``.
    
    Example::
    
        >>> torch.rand(4)
        tensor([ 0.5204,  0.2503,  0.3525,  0.5673])
        >>> torch.rand(2, 3)
        tensor([[ 0.8237,  0.5781,  0.6879],
                [ 0.3816,  0.7249,  0.0998]])
"""
  • 与numpy的创建array相似,pytorch里也提供了很多方法创建矩阵数据,如:
    • torch.ones(*size)
    • torch.empty(*size)
    • torch.zero(*size)
    • ……


      tensor

根据数据直接创建Tensor

import torch

x = torch.tensor([4., 6.])
print(x)  # tensor([4., 6.])

根据已有的Tensor创建

新的tensor属性默认与原tensor一样,除非重新定义相关属性值,如数据类型等.

  • tensor.new_*()
  • tocrh.*_like()
  • 可通过shape, size()查看tensor的形状
  • type(tensor)或tensor.type()查看数据类型
import torch

x = torch.randn(2, 2)
print(x)
print(x.type())
"""
tensor([[-0.1132, -0.7127],
        [-2.1580,  0.1524]])
torch.FloatTensor
"""
y = x.new_ones(3, 1)
print(y)
print(type(y))
print(y.type())
"""
tensor([[1.],
        [1.],
        [1.]])
<class 'torch.Tensor'>
torch.FloatTensor
"""
# 重新定义数据类型
z = torch.rand_like(x, dtype=torch.float64) 
print(z)
print(z.type())
print(z.shape)
print(z.size())
"""
tensor([[0.5013, 0.6398],
        [0.7003, 0.7045]], dtype=torch.float64)
torch.DoubleTensor
torch.Size([2, 2])
torch.Size([2, 2])
"""

创建Tensor官网API

creation-ops

creation-ops

索引,切片等操作

索引切片等操作与Numpy类似

  • 索引出来的结果与原数据共享内存,也即修改一个,另⼀个会跟着修改。
import torch

x = torch.randn(3, 2)
print(x)
"""
tensor([[-0.9832, -0.5647],
        [ 2.0707, -1.5602],
        [-0.7770,  0.6269]])
"""
y = x[0, :]
y += 1
print(y)
print(x)
"""
tensor([0.0168, 0.4353])
tensor([[ 0.0168,  0.4353],
        [ 2.0707, -1.5602],
        [-0.7770,  0.6269]])
"""

其他索引等操作函数

other ops

Tensor与Numpy.ndarray互换

  • 将numpy的多维数组转换成tensor

torch.from_numpy(ndarray)

注意 若对转换过来的tensor进行重新赋值操作,numpy的原数据值也会跟着改变。
The returned tensor and ndarray share the same memory. Modifications to the tensor will be reflected in the ndarray and vice versa. The returned tensor is not resizable.

import numpy as np
import torch

a = np.array([1., 2., 5.])
b = torch.from_numpy(a)
print(b)m # tensor([1., 2., 5.], dtype=torch.float64)

b[0] = -3
print(b) # tensor([-3.,  2.,  5.], dtype=torch.float64)
print(a) # [-3.,  2.,  5.]
  • torch.tensor(numpy.data)

torch.tensor()将numpy数组转换成Tensor,新的tensor与原来的数据不共享内存

import numpy as np
import torch

a = np.ones([4,2])
print(a)
"""
[[1. 1.]
 [1. 1.]
 [1. 1.]
 [1. 1.]]
"""

b = torch.tensor(a)
print(b)
"""
tensor([[1., 1.],
        [1., 1.],
        [1., 1.],
        [1., 1.]], dtype=torch.float64)
"""

a += 1
print(a)
print(b)
"""
[[2. 2.]
 [2. 2.]
 [2. 2.]
 [2. 2.]]
tensor([[1., 1.],
        [1., 1.],
        [1., 1.],
        [1., 1.]], dtype=torch.float64)
"""
  • 将tensor转换为numpy数组

tensor.numpy()

import numpy as np
import torch

a = torch.rand(2, 2)
b = a.numpy()
print(a.size())
print(b.shape)
print(type(b))
"""
torch.Size([2, 2])
(2, 2)
<class 'numpy.ndarray'>
"""

改变形状

用view()改变tensor形状

import torch

x = torch.randn(5, 3)
print(x)

y = x.view(15)
z = x.view(-1, 5)  # -1所指的维度可以根据其他维度的值推出来
print(x.size(), y.size(), z.size())
"""
tensor([[ 0.1175, -0.3235, -0.3558],
        [-0.5256,  0.6905,  0.1356],
        [ 1.1083,  0.1446,  2.2707],
        [ 1.2616, -0.1385,  0.2672],
        [ 3.6323,  0.3644,  0.3646]])
torch.Size([5, 3]) torch.Size([15]) torch.Size([3, 5])
"""

view() 返回的新tensor与源tensor共享内存,也即更更改其中的一个,另外⼀个也会跟着改变

import torch

x = torch.randn(5, 3)
print(x)

x_cp = x.clone().view(15)
x += 1

print(x)
print(x_cp)
"""
tensor([[-1.2922, -0.1457,  1.6732],
        [-2.0736,  0.1704,  0.7486],
        [ 1.1084,  1.4401, -0.3245],
        [-0.0184, -0.2662, -1.8648],
        [-0.2941,  0.9768, -0.4823]])
tensor([[-0.2922,  0.8543,  2.6732],
        [-1.0736,  1.1704,  1.7486],
        [ 2.1084,  2.4401,  0.6755],
        [ 0.9816,  0.7338, -0.8648],
        [ 0.7059,  1.9768,  0.5177]])
tensor([-1.2922, -0.1457,  1.6732, -2.0736,  0.1704,  0.7486,  1.1084,  1.4401,
        -0.3245, -0.0184, -0.2662, -1.8648, -0.2941,  0.9768, -0.4823])
"""

若tensor是个标量时,可用item()取得一python数据

import torch

x = torch.rand(1)
print(x)
print(x.item())
"""
tensor([0.9280])
0.9279811978340149
"""
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335