Torch基础,张量
#首先要引入相关的包
import torch
import numpy as np
torch.__version__
'1.2.0'
张量的英文是Tensor,它是PyTorch里面基础的运算单位,与Numpy的ndarray相同都表示的是一个多维的矩阵。 与ndarray的最大区别就是,PyTorch的Tensor可以在 GPU 上运行,而 numpy 的 ndarray 只能在 CPU 上运行,在GPU上运行大大加快了运算速度。
x = torch.rand(2,3)
x
tensor([[0.6243, 0.9414, 0.9387],
[0.9347, 0.2431, 0.7243]])
#查看tensor的形状,两种方式的结果是一样的
print(x.shape)
print(x.size())
torch.Size([2, 3])
torch.Size([2, 3])
#tensor零阶是标量,一阶是向量,二阶是矩阵,三阶以上就是多为张量。下面直接用现有数字生成标量tensor
scala = torch.tensor(3.1)
print(scala)
print(scala.size())
print(scala.item())
#对于标量,可以直接使用.item()获取里面的python对象(只有一个元素一阶张量也可以用。item()获取里面的值)
tensor = torch.tensor([3.1433223])
print(tensor.item())
tensor(3.1000)
torch.Size([])
3.0999999046325684
3.143322229385376
tensor的基本书记类型
1:32位浮点型 。torch.FloatTensor(默认)
2:64位整型。torch.LongTensor
3:32位整型。torch.IntTensor
4:16位整型。torch.ShortTensor
5:出了以上数字类型外还有byte和char类型
long = tensor.long()
print(long)
tensor([3])
half = tensor.half()
print(half)
tensor([3.1426], dtype=torch.float16)
int_t = tensor.int()
print(int_t)
tensor([3], dtype=torch.int32)
flo = tensor.float()
print(flo)
tensor([3.1433])
short = tensor.short()
print(short)
tensor([3], dtype=torch.int16)
ch = tensor.char()
print(ch)
tensor([3], dtype=torch.int8)
bt = tensor.byte()
print(bt)
tensor([3], dtype=torch.uint8)
numpy 转化
#把torch转化为numpy
a = torch.randn(3,2)
print(a)
numpy_a = a.numpy()
print(numpt_a)
tensor([[-0.3951, 0.3288],
[ 0.2463, 0.0648],
[-0.4960, -0.5525]])
[[-0.7417315 0.70448285]
[-0.16260317 -2.5630066 ]
[-2.62509 -0.45682326]]
#把numpy转化为torch
torch_a = torch.from_numpy(numpy_a)
print(torch_a)
tensor([[-0.3951, 0.3288],
[ 0.2463, 0.0648],
[-0.4960, -0.5525]])
初始化tensor
#使用【0,1】均匀分布,随机初始化二维数组
rnd = torch.rand(5,3)
rnd
tensor([[0.6725, 0.3572, 0.2056],
[0.8898, 0.8133, 0.8364],
[0.9718, 0.4312, 0.0609],
[0.1034, 0.1715, 0.3022],
[0.6989, 0.3390, 0.8654]])
#初始化,使用1填充
one = torch.ones(2,2)
print(one)
#初始化,使用0填充
zero = torch.zeros(2,2)
print(zero)
tensor([[1., 1.],
[1., 1.]])
tensor([[0., 0.],
[0., 0.]])
#初始化一个单位矩阵,即对角线位1,其他未0的矩阵
eye = torch.eye(2,2)
print(eye)
tensor([[1., 0.],
[0., 1.]])
常用的方法
x = torch.randn(3,3)
x
tensor([[ 0.1635, 0.9026, 0.8449],
[-0.2458, 0.7157, 0.2600],
[-0.4684, -1.2232, -0.0749]])
#延行取最大最小值
max_value,max_idx = torch.max(x,dim=1)
print(max_value,max_idx)
tensor([ 0.9026, 0.7157, -0.0749]) tensor([1, 1, 2])
#每行求和
sum_x = torch.sum(x,dim=1)
print(sum_x)
tensor([ 1.9111, 0.7299, -1.7665])
y = torch.randn(3,3)
z = x + y
print(z)
tensor([[ 0.7132, 0.4541, -2.0532],
[-1.3002, 1.0904, 0.7578],
[-0.5994, -2.1798, -1.1667]])
#以_结尾的方法,均会改变调用者
x.add_(y)
print(x)
tensor([[ 0.7132, 0.4541, -2.0532],
[-1.3002, 1.0904, 0.7578],
[-0.5994, -2.1798, -1.1667]])