博主近期会将自己所学以及学习中遇到的一些问题记录下来,感兴趣的朋友可以点击关注!
大家可以一起学习,有什么问题随时欢迎提问!
目录
一、Pytorch 是什么?
PyTorch 是一个基于 Python 的科学计算包,主要定位两类人群:
- NumPy 的替代品,可以利用 GPU 的性能进行计算。
- 深度学习研究平台拥有足够的灵活性和速度
二、Tensors 张量的创建
1、直接创建 Tensors
torch.tensor(data)
- 标量:data 为标量
- 向量:data 为向量
- 矩阵:data 为矩阵
import torch
num = torch.tensor(3)
vector = torch.tensor([1, 2, 3, 4])
martix = torch.tensor([[1, 2], [3, 4], [5, 6]])
print(num)
print(vector)
print(martix)
输出:
2、创建特定 Tensors
零矩阵:
- torch.zeros(size) —— size 矩阵的维度;size 大小的零矩阵
- torch.zeros_like(martix) —— martix 矩阵;大小为矩阵martix相同的零矩阵
单位矩阵:
- torch.ones(size) —— size 矩阵的维度;size 大小的单位矩阵
- torch.ones_like(martix) —— martix 矩阵;大小为矩阵martix相同的单位矩阵
单位对角矩阵:
- torch.eye(n) —— 大小为 n * n 的单位对角矩阵
import torch
martix = torch.tensor([[1, 2], [3, 4], [5, 6]])
martix_0 = torch.zeros([3, 2]) # size为[3, 2]的零矩阵
martix_1 = torch.zeros_like(martix) # size与矩阵martix相同的零矩阵
martix_2 = torch.ones([3, 2]) # size为[3, 2]的单位矩阵
martix_3 = torch.ones_like(martix) # size与矩阵martix相同的单位矩阵
martix_4 = torch.eye(n=3) # n * n 的单位对角矩阵
print(martix_0)
print(martix_1)
print(martix_2)
print(martix_3)
print(martix_4)
输出:
3、创建随机 Tensors
[0, 1] 之间均匀分布:
- torch.rand(size) —— size 矩阵的维度;size 大小的矩阵,且值为[0,1]之间均匀分布的随机数
- torch.rand_like(martix_float) —— size与矩阵martix_float相同的矩阵,且值为[0,1]之间均匀分布的随机数
指定范围之间的均匀分布:
- torch.randint(low=min, high=max, size=size) —— 矩阵大小为size,且值在[min, max]之间的随机整数
- torch.randint_like(martix, low=min, high=max) —— 矩阵大小与矩阵martix相同,且值为[min, max]之间均匀分布的随机
注:这里需要注意的是,torch.rand_like()生成的是[0,1]之间的浮点数,数据类型为float,因此,martix_float矩阵中的数据类型需为float型,否则会报错!
RuntimeError: _th_uniform_ not supported on CPUType for Long
import torch
martix = torch.tensor([[1, 2], [3, 4], [5, 6]])
martix_float = torch.tensor([[1, 2], [3, 4], [5, 6]], dtype=torch.float)
martix_5 = torch.rand([3, 2]) # size为[3, 2]的且值为[0,1]之间均匀分布的随机数
martix_6 = torch.rand_like(martix_float) # size与矩阵martix_float相同且值为[0,1]之间均匀分布的随机数
martix_7 = torch.randint(low=2, high=10, size=[3, 2]) # size为[3, 2]且值在[low, hight]之间的随机整数
martix_8 = torch.randint_like(martix, low=2, high=10) # size与矩阵martix相同且值为[low, hight]之间均匀分布的随机数
print(martix_5)
print(martix_6)
print(martix_7)
print(martix_8)
输出: