Pytorch笔记(一)

开始学习Pytorch

这是我的第一篇CSDN博客,作为一个我开始学习Pytorch的记录,学习的方式主要是阅读Pytorch的官方Tutorials,最新版是英文版,所采取一个边学习英语边学习Pytorch的心态开始。
教程传送门

Tensor

什么是Tensor,可能如雷贯耳的名字是TensorFlow 但是,Tensor的本质含义是高纬度矩阵,按照维度高低来看

标量
向量
二维矩阵
张量

按照箭头的方向,纬度逐渐增加的,所以Tensor就可以看做是一个更高维度的矩阵

如何构建一个Tensor

import torch
x=torch.empty(5,3)

表示创建一个纬度是5行3列的未初始化Tensor

类似的方法还有

  1. torch.rand 表示一个随机初始化的变量
  2. torch.ones 全为1的张量
  3. torch.zeros 全为0的张量

还有一类创建张量的函数为,继承另外一个已经存在的张量,继承他的形状,或者继承他的gpu或者cpu状态,以及dtype等等

x=torch.ones(2,2,dtype=torch.float)
print(x)
x = x.new_ones(5, 3)      # new_* methods take in sizes
print(x.dtype)

x = torch.randn_like(x, dtype=torch.float)    # override dtype!
print(x.dtype)                                      # result has the same size

‘’‘
运行结果:
tensor([[1., 1.],
        [1., 1.]])
torch.float32
torch.float32
’‘’

获得张量大小的函数:

x.size()

Tensor的操作

如果要表示Tensor a + Tensor b

import torch
a=torch.rand(3,5)
b=torch.rand(3,5)
#方法一
print(a+b)
#方法二
print(torch.add(a,b))
#方法三
result=torch.empty(3,5)
torch.add(a,b,out=result)
print(result)
#方法四
print(a.add_(b))

特别注意方法四,后面有 _ 表示为执行这个操作,但是把结果赋值给执行这个操作的对象,类似于++或者 - -这样的操作
更多的操作传送门

Tensor的索引

NumPy-like indexing with all bells and whistles 这是对于索引的描述,所以这里可以使用所有的类似于Numpy的索引方式

print(x[:, 1]) #输出x的第一列所有的内容

-1的含义是,这个维度的大小取决于其他维度

Numpy和Torch Tensor的关系

这里我们开始介绍ndarray和tensor的互相转换,这里有个需要注意的是,如果在cpu下,把一个numpy数组转化成tensor的话,从本质上,两者使用同一块内存空间,所以改变tensor就会牵连到ndarray的改变

把tensor转化为numpy

使用 .numpy() 把tensor转化成ndarray

a = torch.ones(5)
print(a)
#结果为:tensor([1., 1., 1., 1., 1.])
b = a.numpy()
print(b)
#结果为:[1. 1. 1. 1. 1.]
a.add_(1)  #这里_后缀表示在自身值会改变
print(a)
print(b)
#结果为:
#tensor([2., 2., 2., 2., 2.])
#[2. 2. 2. 2. 2.]

出现这样的结果就是之前提到的,内存共享问题

把numpy转化为tensor

使用torch.from_numpy()

import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)

'''输出结果:
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
'''

在CUDA上使用Tensor

先贴上教程中的代码:

# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
    device = torch.device("cuda")          # a CUDA device object
    y = torch.ones_like(x, device=device)  # directly create a tensor on GPU
    x = x.to(device)                       # or just use strings ``.to("cuda")``
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # ``.to`` can also change dtype together!

首先这个程序只能在有cuda的设备商运行,所以前面的 torch.cuda.is_available() 就是在判断这个设备上是否有CUDA,使用torch.device可以创建一个cuda device对象,很明显里面的cuda是可以改成cpu的,当我们的设备有多个gpu得话,cuda可能会有一个编号,ones_like表示会继承x的size,但是我们指定他的设备是cuda
使用.to函数可以把一个tensor从一个设备搬移到另外一个设备上
另外一种简化的写法是:

x=x.to(“cuda”)

同时to()函数不仅仅只有搬移tensor的功能,还可以改变数据的data type

到此我们已经完成了对于60min入门pytorch的学习(Blitz 是闪电战的意思)

猜你喜欢

转载自blog.csdn.net/weixin_43869493/article/details/105385349