目录
一.创建数据
张量Tensors表示由一个数值组成的数组,这个数组可能有多个维度。
张量中的每个值都称为张量的元素
理解张量:
张量是多维数组
把三维张量画成一个立方体:
>>> import torch
>>> x = torch.arange(12) #arange创建一个行向量x。这个行向量包含从0开始的前12个整数,它们被默认创建为浮点数
>>> x
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
通过张量的shape
属性来访问张量的形状 (沿每个轴的长度)
>>> x.shape
torch.Size([12])
张量中元素的总数,即形状的所有元素乘积,可以检查它的大小(size)。 因为这里在处理的是一个向量,所以它的shape
与它的size
相同。
>>> x.numel()
12
改变一个张量的形状而不改变元素数量和元素值,可以调用reshape
函数
>>> x.reshape(3,4)
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.reshape(-1,3) #张量在给出其他部分后可以自动计算出一个维度
tensor([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
>>> x.reshape(3,-1)
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
另:
>>> m=torch.arange(12, dtype=torch.float32).reshape((3,4)) #创建为float32的浮点数的张量
>>> m
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
全0、全1、其他常量或者从特定分布中随机采样的数字来初始化矩阵 torch.zeros(行,列,dtype=torch.long) 全0,数据类型是 long.torch.ones(行,列) 全1torch.randn(行,列) 随机初始化参数的值torch.tensor([值]) 自己制定,类C语言二维数组赋值torch.empty(行,列) 不初始化
创建一个 tensor 基于已经存在的 tensor
x = x.new_ones(5, 3, dtype=torch.double) #x是张量名
>>> torch.zeros(3,4)
tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
>>> torch.ones(3,4)
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
>>> torch.randn(3, 4)
tensor([[-1.3953, 1.4881, -0.1567, 0.8208],
[ 1.1283, -0.7510, -0.3695, -1.3861],
[-0.2492, 0.6856, -0.5805, 0.7981]])
>>> torch.tensor([[1,2],[2,2]])
tensor([[1, 2],
[2, 2]])
.item() 来获得一个元素 tensor value
x = torch.randn(1) print(x) print(x.item())
二.运算
所有的运算都是按元素进行
四则运算、乘幂运算都可参照如下:
torch.add(x, y, out=result) #加法的一种方式,加的值在result 中 print(result)y.add_(x) print(y)
张量形状相同的运算
>>> x=torch.tensor([[1,2],[3,4]]) #元素是整型,就创建整型
>>> y=torch.tensor([[2,3],[4,5]])
>>> x+y
tensor([[3, 5],
[7, 9]])
张量形状不相同的运算 广播机制
>>> a = torch.arange(3).reshape((3, 1))
>>> b = torch.arange(2).reshape((1, 2))
>>> a
tensor([[0],
[1],
[2]])
>>> b
tensor([[0, 1]])
>>> a+b
tensor([[0, 1],
[1, 2],
[2, 3]])
实质为将两个矩阵广播为一个更大的3×2
矩阵a
将复制列,矩阵b
将复制行,然后再按元素相加。
求幂运算---exp是高等数学里以自然常数e为底的指数函数。exp(x)表示的是e的x次方
>>> torch.exp(x) #x是上述的值
tensor([[ 2.7183, 7.3891],
[20.0855, 54.5981]])
张量连接
torch.cat((张量1, 张量2), dim=0) #dim=0按行连接,dim=1按列连接
>>> torch.cat((x,y),dim=0)
tensor([[1, 2],
[3, 4],
[2, 3],
[4, 5]])
>>> torch.cat((x,y),dim=1)
tensor([[1, 2, 2, 3],
[3, 4, 4, 5]])
x(x行,x列)
y(y行,y列)
按行连接:x行,x列,y行,y列
按列连接:x行+y行,x列+y列
逻辑张量
>>> x==y
tensor([[False, False],
[False, False]])
张量名.sum()对张量中的所有元素进行求和会产生一个只有一个元素的张量
>>> x.sum()
tensor(10)
三.索引和切片
可以使用标准的 NumPy 类似的索引操作
>>> x[-1] #输出最后一行
tensor([3, 4])
>>> x[1,1]=99 #修改某一值
>>> x
tensor([[ 1, 2],
[ 3, 99]])