本篇主要记录一下一些基础的pytorch知识,在前两节的基础上,回过头来温习一下

python与pytorch

  作为深度学习的GPU加速库,pytorch没有对string类型数据对象的直接支持。
all is about tensor
  有两种方法可以去表示string(编码方式)

  1. one-hot
  2. Embedding

tensor数据类型介绍

  pytorch的数据类型:FloatTensor, IntTensor, ByteTensor,需要注意的是:即使是同一种数据类型,在cpu和gpu(cuda)上并不能直接相互使用。下面是一些代码的具体演示,注意注释部分

import torch

# 正态分布随机初始化,方差:1
a = torch.randn(2, 3)
# torch提供的类型检测
print(a.type())
# python提供的类型检测
print(type(a))
# 参数的合法化检验
print(isinstance(a, torch.FloatTensor))
# cpu和gpu的类型不同
print(isinstance(a, torch.cuda.FloatTensor))
a = a.cuda()
print(isinstance(a, torch.cuda.FloatTensor))

# 标量的表示(0维 tensor)
a = torch.tensor(1.)
# .shape是一个成员,.size()是一个成员函数,因此有括号
print(a.shape)
print(a.size())
print(len(a.shape))
# 注意 1.3是0维,但是【1.3】是1维,长度为1的tensor
# 通常的loss就是一个dimension为0的标量

# 1维tensor
a = torch.tensor([1.1])
a = torch.tensor([1.1, 2.2])
# tensor可以直接指定生成的具体值,FloatTensor则会指定生成的维度,随机生成数据
a = torch.FloatTensor(1)
a = torch.FloatTensor(2)
# 1维tensor 通常用作bias,在神经元中有多个输入,进过偏置(bias),后经激活函数得到一个输出,因此通常要求是一维的
# 1维tensor 也会被用作线性层的输入,在进过打平之后,进入线性层的通常是1维的tensor

# 2维tensor
a = torch.randn(2, 3)
print(a.shape)
print(a.shape[0])
print(a.shape[1])
print(a.size())
print(a.size(0))
print(len(a.shape))
# 2维tensor 通常用作带有batch的线性层输入
# 如 [4, 784],4表示一组照片,第0/1/2/3张照片,784是照片的具体数据内容

# 3维tensor
# 随机均匀分布,范围【0,1】
a = torch.rand(1, 2, 3)
print(a.shape)
print(a[0])
# 3维tensor 通常用作带有batch的RNN输入(文字)

# 4维tensor
a = torch.rand(2, 3, 28, 28)
print(a.shape)
print(a[0])
# num of element(总元素个数)
print(a.numel())
# 维数
print(a.dim())
# 3维tensor 通常用作CNN输入(图片)【batch_size, channel, height, width】

创建tensor

import torch
import numpy

# 方法1 torch.from_numpy()
# 由numpy导入 (值和类型保持不变)
a = numpy.array([2, 3, 3])
a = torch.from_numpy(a)
a = numpy.ones([2, 3])
a = torch.from_numpy(a)

# 方法2 torch.tensor()
# 由list导入 (小数据量时)
# Tensor() 参数是数据的维度/数据 用[]区别
# tensor() 参数是数据
a = torch.tensor([2., 3.2])
a = torch.Tensor(2, 3)
a = torch.FloatTensor([2., 3.2])
# 创建未初始化数据
# 未初始化的tensor一定要在后面加上赋值,否则会导致奇怪bug(infinity等)
a = torch.empty()
a = torch.FloatTensor(2, 3)

# 设置类型
print(torch.tensor([1.2, 3]).type())
torch.set_default_tensor_type(torch.DoubleTensor)
print(torch.tensor([1.2, 3]).type())

# 随机初始化
a = torch.rand(3, 3)
b = torch.rand_like(a)
# low, high, shape
b = torch.randint(1, 10, [3, 3])
# 正态分布 N(0, 1)
a = torch.randd(3, 3)
a = torch.normal(mean=torch.full([10], 0), std=torch.arange(1, 0, -0.1))

# 其他
# 全部赋值为一个元素
a = torch.full([2, 3], 7)
a = torch.full([], 7)
# 递增递减等
a = torch.arange(0, 10)
a = torch.arange(0, 10, 2)
# 与arange不同的是,第三个参数是num of ele而不是步进
a = torch.linspace(0, 10, steps=4)
a = torch.logspace(0, -1, steps=10)
# 全0/1
a = torch.ones(3, 3)
a = torch.zeros(3, 3)
a = torch.eye(3, 3)
# 0~9 打乱填入
a = torch.randperm(10)
# eg. 协调shuffle
a = torch.rand(2, 3)
b = torch.rand(2, 3)
idx = torch.randperm(2)
a[idx]
b[idx]