目录
第二:torch里面的randn,randn_like,rand等用法
第一:张量的生成,以及与数组的相互转换
import torch
import numpy as np
a = np.array([[1, 2, 3], [1, 2, 3]])
print(a)
print(type(a))
print('---------------------')
b = torch.tensor([[1, 2, 4], [1, 2, 3]])
print(b)
print(type(b))
print('--------------------')
c = b.numpy()
print(c)
print(type(c))
print('--------------------')
d=torch.from_numpy(c)
print(d)
print(type(d))
print('--------------')
[[1 2 3]
[1 2 3]]
<class 'numpy.ndarray'>
---------------------
tensor([[1, 2, 4],
[1, 2, 3]])
<class 'torch.Tensor'>
--------------------
[[1 2 4]
[1 2 3]]
<class 'numpy.ndarray'>
--------------------
tensor([[1, 2, 4],
[1, 2, 3]])
<class 'torch.Tensor'>
--------------
进程已结束,退出代码0
第二:torch里面的randn,randn_like,rand等用法
import torch
import numpy as np
a=np.array([[1,2,3],[1,2,3]])
print(a)
print()
b=torch.from_numpy(a)
print(b)
c=torch.tensor([[4,5,6],[4,5,6]])
print(c)
d= torch.tensor([[4,5,6],[4,5,6]])
print(d)
print('-------------------------')
e=torch.empty(2)#一维张量,数据随机生成
print(e)
f=torch.Tensor(2,3)
print(f)
#随机生成
print('随即生成:')
g=torch.rand(3,3)#返回一个张量从[0,1)均匀分布中抽取的一组随机数
print('g:',g)
print(sum(g))
print(g.shape)
print('---------------')
G=torch.randn(3,3)#返回一个张量里面是从标准正态分布(均值为0,方差为1)中抽取的一组随机数
print('G:',G)
print(sum(G))
print('-------------------')
i=torch.randn_like(g)
print('i:',i)
print(sum(i))
print(i.shape)
print('---------------------')
#序列生成,创建
print('序列生成创建----------------------')
print(torch.arange(0,10))#返回一维张量,size为10,计算公式 size=(end-start)/step,step默认为1,start默认为0
print(torch.arange(0,10,2))#返回一维张量,size为5
print(torch.linspace(0,10,steps=10))#返回一个一位张量,包含在[0,10]均匀间隔的step个点,则step的个数=返回的张量的size
#全零,全一,单位矩阵,创建
print('全零,全一,单位矩阵,创建----------------------')
print("all 0:")
print(torch.zeros(5,6))
print("all 1:")
print(torch.ones(6,1))
print("单位矩阵:")
print(torch.eye(6,4))
print(torch.eye(6))
#计算
n1=torch.zeros(4,1)
print('n1:',n1)
n2=torch.ones(1,5)
print('n2:',n2)
print(n1*n2)
D:\Anaconda3\envs\pytorch\python.exe D:\learn_pytorch\学习过程\第一周的代码\代码2.py
[[1 2 3]
[1 2 3]]
tensor([[1, 2, 3],
[1, 2, 3]], dtype=torch.int32)
tensor([[4, 5, 6],
[4, 5, 6]])
tensor([[4, 5, 6],
[4, 5, 6]])
-------------------------
tensor([1.0194e-38, 9.0919e-39])
tensor([[9.2755e-39, 1.0837e-38, 8.4490e-39],
[1.1112e-38, 1.0194e-38, 9.0919e-39]])
随即生成:
g: tensor([[0.9639, 0.6810, 0.3536],
[0.0748, 0.5010, 0.3016],
[0.8314, 0.1013, 0.1155]])
tensor([1.8701, 1.2833, 0.7708])
torch.Size([3, 3])
---------------
G: tensor([[-1.2336, -1.2844, -0.4845],
[-0.8806, 0.7501, -0.4340],
[-1.0250, -0.6683, 0.2552]])
tensor([-3.1392, -1.2026, -0.6633])
-------------------
i: tensor([[ 1.1203, -1.0916, 0.9752],
[-2.1253, 0.9345, 0.0509],
[-0.4958, -0.4921, -0.6796]])
tensor([-1.5008, -0.6492, 0.3466])
torch.Size([3, 3])
---------------------
序列生成创建----------------------
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
tensor([0, 2, 4, 6, 8])
tensor([ 0.0000, 1.1111, 2.2222, 3.3333, 4.4444, 5.5556, 6.6667, 7.7778,
8.8889, 10.0000])
全零,全一,单位矩阵,创建----------------------
all 0:
tensor([[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]])
all 1:
tensor([[1.],
[1.],
[1.],
[1.],
[1.],
[1.]])
单位矩阵:
tensor([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
tensor([[1., 0., 0., 0., 0., 0.],
[0., 1., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0.],
[0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 1.]])
n1: tensor([[0.],
[0.],
[0.],
[0.]])
n2: tensor([[1., 1., 1., 1., 1.]])
tensor([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
进程已结束,退出代码0
第三:tensor属性
import torch
import numpy as np
print("tensor属性-------------------")
a=torch.tensor([[1,2,3,4],[1,2,3,4]],dtype=torch.float)
print(a.dtype)
print(a.shape)
print(a.size())
print(a.size(0))
print(a.size(1))
print(a.dim())
print(a.grad)
print(a.device)
D:\Anaconda3\envs\pytorch\python.exe D:\learn_pytorch\学习过程\第一周的代码\代码3.py
tensor属性-------------------
torch.float32
torch.Size([2, 4])
torch.Size([2, 4])
2
4
2
None
cpu
进程已结束,退出代码0
第四:tenso的变形
import torch
import numpy as np
print('tensor变形------------------')
a=torch.tensor([[1,2,3,4,5],[6,2,3,4,5]],dtype=torch.float)
print('a的值:',a)
print('a的形状:',a)
b=a.flatten() #拉平
print("b:",b)
print('b.shape:',b.shape)
c=b.reshape(5,2)
print('c:',c)
print('c.shape:',c.shape)
d=b.view(1,10)#从功能上来看,它们的作用是相同的,都是用来重塑 Tensor 的 shape 的。view 只适合对满足连续性条件 (contiguous) 的 Tensor进行操作,而reshape 同时还可以对不满足连续性条件的 Tensor 进行操作,具有更好的鲁棒性。view 能干的 reshape都能干,如果 view 不能干就可以用 reshape 来处理。
print('d:',d)
print('d.shape:',d.shape)
e=torch.squeeze(d) #将输入张量形状中的一去除
print('e:',e)
print("e.shape:",e.shape)
f=torch.unsqueeze(e,0) #对输出的既定位置插入 维度一
print('f:',f)
print("f.shape:",f.shape)
f=torch.unsqueeze(e,0) #对输出的既定位置插入维度一
print('f:',f)
print("f.shape:",f.shape)
D:\Anaconda3\envs\pytorch\python.exe D:\learn_pytorch\学习过程\第一周的代码\代码4.py
tensor变形------------------
a的值: tensor([[1., 2., 3., 4., 5.],
[6., 2., 3., 4., 5.]])
a的形状: tensor([[1., 2., 3., 4., 5.],
[6., 2., 3., 4., 5.]])
b: tensor([1., 2., 3., 4., 5., 6., 2., 3., 4., 5.])
b.shape: torch.Size([10])
c: tensor([[1., 2.],
[3., 4.],
[5., 6.],
[2., 3.],
[4., 5.]])
c.shape: torch.Size([5, 2])
d: tensor([[1., 2., 3., 4., 5., 6., 2., 3., 4., 5.]])
d.shape: torch.Size([1, 10])
e: tensor([1., 2., 3., 4., 5., 6., 2., 3., 4., 5.])
e.shape: torch.Size([10])
f: tensor([[1., 2., 3., 4., 5., 6., 2., 3., 4., 5.]])
f.shape: torch.Size([1, 10])
f: tensor([[1., 2., 3., 4., 5., 6., 2., 3., 4., 5.]])
f.shape: torch.Size([1, 10])
进程已结束,退出代码0
第五:tensor索引相关
import torch
import numpy as np
print('tensor索引和切片-------------------')
#注意:tensor所有元素都有编号,正索引是从左往右,从零开始,夫索引是从右往左,从-1开始
a=torch.tensor([[1,2,3],[1,2,4],[6,8,9]],dtype=torch.float)
b=torch.tensor([[6,666,66],[16,6,3],[66,86,96]],dtype=torch.float)
print('a:',a)
#索引a[:,:]
print('a[1,2]:',a[1,2])
print('a[-1,-1]:',a[-1,-1])
print('a 的第一行,第一列和第三列的值:',a[[1],[0,2]])
print('a的大于4的索引:',a>4)
print('a大于4的值:',a[a>4])
print('大于5输出a的值,否则输出b:\n',torch.where(a>5,a,b))#where条件
#切片
print('a的第1列:',a[:,0])
print('a的第2列:',a[:,1])
print('a的第3列:',a[:,-1])
print('a的第1到2列:',a[:,0:2])
print('a的第1行:',a[0,:])
print('a的第2行:',a[1,:])
print('a的最后一行:',a[-1:,:])
print('a的间隔行值',a[::2,::2])#设置了步长n,相当于要跳n-步
D:\Anaconda3\envs\pytorch\python.exe D:\learn_pytorch\学习过程\第一周的代码\代码5.py
tensor索引和切片-------------------
a: tensor([[1., 2., 3.],
[1., 2., 4.],
[6., 8., 9.]])
a[1,2]: tensor(4.)
a[-1,-1]: tensor(9.)
a 的第一行,第一列和第三列的值: tensor([1., 4.])
a的大于4的索引: tensor([[False, False, False],
[False, False, False],
[ True, True, True]])
a大于4的值: tensor([6., 8., 9.])
大于5输出a的值,否则输出b:
tensor([[ 6., 666., 66.],
[ 16., 6., 3.],
[ 6., 8., 9.]])
a的第1列: tensor([1., 1., 6.])
a的第2列: tensor([2., 2., 8.])
a的第3列: tensor([3., 4., 9.])
a的第1到2列: tensor([[1., 2.],
[1., 2.],
[6., 8.]])
a的第1行: tensor([1., 2., 3.])
a的第2行: tensor([1., 2., 4.])
a的最后一行: tensor([[6., 8., 9.]])
a的间隔行值 tensor([[1., 3.],
[6., 9.]])
进程已结束,退出代码0
第六:tensor的拼接和拆分
import torch
import numpy as np
print('tensor拼接和拆分-------------')
a=torch.tensor([[6,6,6],[7,7,7],[8,8,8]],dtype=torch.float)
b=torch.tensor([[10,10,10],[71,171,71],[28,28,82]],dtype=torch.float)
print(a)
print(b)
#在给定维度上对输入的张量进行连接操作
print('a,b行拼接:\n',torch.cat((a,b),dim=0))
print('a,b行拼接:\n',torch.cat((a,b),dim=0).shape)
print('a,b列拼接:\n',torch.cat((a,b),dim=1))
print('a,b列拼接:\n',torch.cat((a,b),dim=1).shape)
print('-------------------------------------------------')
#
print('a,b行拼接:\n',torch.stack((a,b),dim=0))#沿着一个新纬度对输入张量序列进行连接,在新维度拼接张量,将原始数据维度他们放在一个一位张量里面
print('a,b行拼接:\n',torch.stack((a,b),dim=0).shape)
print('a,b列拼接:\n',torch.stack((a,b),dim=1))#将每个tensor的第i行按行连接组成一个新的2维tensor,再将这些新tensor按照dim=0的方式连接
print('a,b列拼接:\n',torch.stack((a,b),dim=1).shape)
print('-----------------')
print('a:',a)
print(torch.split(a,2,dim=0))#按块大小拆分张量为多部份,每部分的数量=块的值,除不尽的取余数,返回一个元组tuple
print(torch.split(a,1,dim=0))
print(torch.split(a,1,dim=1))
print(torch.chunk(a,2,dim=0))#按快数拆分张量,块的值为多少,就分成多少块
print(torch.chunk(a,1,dim=1))
D:\Anaconda3\envs\pytorch\python.exe D:\learn_pytorch\学习过程\第一周的代码\代码6.py
tensor拼接和拆分-------------
tensor([[6., 6., 6.],
[7., 7., 7.],
[8., 8., 8.]])
tensor([[ 10., 10., 10.],
[ 71., 171., 71.],
[ 28., 28., 82.]])
a,b行拼接:
tensor([[ 6., 6., 6.],
[ 7., 7., 7.],
[ 8., 8., 8.],
[ 10., 10., 10.],
[ 71., 171., 71.],
[ 28., 28., 82.]])
a,b行拼接:
torch.Size([6, 3])
a,b列拼接:
tensor([[ 6., 6., 6., 10., 10., 10.],
[ 7., 7., 7., 71., 171., 71.],
[ 8., 8., 8., 28., 28., 82.]])
a,b列拼接:
torch.Size([3, 6])
-------------------------------------------------
a,b行拼接:
tensor([[[ 6., 6., 6.],
[ 7., 7., 7.],
[ 8., 8., 8.]],
[[ 10., 10., 10.],
[ 71., 171., 71.],
[ 28., 28., 82.]]])
a,b行拼接:
torch.Size([2, 3, 3])
a,b列拼接:
tensor([[[ 6., 6., 6.],
[ 10., 10., 10.]],
[[ 7., 7., 7.],
[ 71., 171., 71.]],
[[ 8., 8., 8.],
[ 28., 28., 82.]]])
a,b列拼接:
torch.Size([3, 2, 3])
-----------------
a: tensor([[6., 6., 6.],
[7., 7., 7.],
[8., 8., 8.]])
(tensor([[6., 6., 6.],
[7., 7., 7.]]), tensor([[8., 8., 8.]]))
(tensor([[6., 6., 6.]]), tensor([[7., 7., 7.]]), tensor([[8., 8., 8.]]))
(tensor([[6.],
[7.],
[8.]]), tensor([[6.],
[7.],
[8.]]), tensor([[6.],
[7.],
[8.]]))
(tensor([[6., 6., 6.],
[7., 7., 7.]]), tensor([[8., 8., 8.]]))
(tensor([[6., 6., 6.],
[7., 7., 7.],
[8., 8., 8.]]),)
进程已结束,退出代码0
第七:tensor换位和置换
import torch
import numpy as np
print('tensor换位或置换--------------------------')
a=torch.tensor([[1,2,3],[6,6,6],[7,7,7]],dtype=torch.float)
print('a:',a)
print(a.T) #a的转置,只接受二维的张量
print(torch.t(a))#a的转置,只接受二维的张量
print(torch.transpose(a,1,0))##a的转置,只接受二维的张量,其他和permute差不多,(1,0),(0,1)一样
print(a.permute(1,0))#a的转置,接受多维的张量,1,0转置,0,1原样
c=torch.unsqueeze(a,0)#unsqueeze()函数起升维的作用,参数表示在哪个地方加一个维度
print(c)
print(c.shape)
print(c.permute(1,0,2).shape)#将tensor的维度换位。参数:也就是里面的数就是换位顺序,大的对应维度大的数值
#permute相当于可以同时操作于tensor的若干维度,transpose只能同时作用于tensor的两个维度;
D:\Anaconda3\envs\pytorch\python.exe D:\learn_pytorch\学习过程\第一周的代码\代码7.py
tensor换位或置换--------------------------
a: tensor([[1., 2., 3.],
[6., 6., 6.],
[7., 7., 7.]])
tensor([[1., 6., 7.],
[2., 6., 7.],
[3., 6., 7.]])
tensor([[1., 6., 7.],
[2., 6., 7.],
[3., 6., 7.]])
tensor([[1., 6., 7.],
[2., 6., 7.],
[3., 6., 7.]])
tensor([[1., 6., 7.],
[2., 6., 7.],
[3., 6., 7.]])
tensor([[[1., 2., 3.],
[6., 6., 6.],
[7., 7., 7.]]])
torch.Size([1, 3, 3])
torch.Size([3, 1, 3])
进程已结束,退出代码0
第八:tensor运算
import torch
import numpy as np
print('----------------tensor运算---------')
a=torch.tensor([[1,2,3],[4,5,6],[7,8,9]],dtype=torch.float)
b=torch.tensor([[10,10,10],[6,6,6],[15,15,15]],dtype=torch.float)
print('a:',a)
print('b:',b)
print(a+100)#对应位置的数相加
print(a+b)#对应位置的数相加
print(a.add(b))#点加
print(a*b)#对应位置的数相乘
print('a @ b:',a @ b) #矩阵相乘
print(a.matmul(b)) #矩阵相乘
print(torch.mm(a,b)) #矩阵相乘
D:\Anaconda3\envs\pytorch\python.exe D:\learn_pytorch\学习过程\第一周的代码\代码8.py
----------------tensor运算---------
a: tensor([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
b: tensor([[10., 10., 10.],
[ 6., 6., 6.],
[15., 15., 15.]])
tensor([[101., 102., 103.],
[104., 105., 106.],
[107., 108., 109.]])
tensor([[11., 12., 13.],
[10., 11., 12.],
[22., 23., 24.]])
tensor([[11., 12., 13.],
[10., 11., 12.],
[22., 23., 24.]])
tensor([[ 10., 20., 30.],
[ 24., 30., 36.],
[105., 120., 135.]])
a @ b: tensor([[ 67., 67., 67.],
[160., 160., 160.],
[253., 253., 253.]])
tensor([[ 67., 67., 67.],
[160., 160., 160.],
[253., 253., 253.]])
tensor([[ 67., 67., 67.],
[160., 160., 160.],
[253., 253., 253.]])
进程已结束,退出代码0
第九:tensor的自动微分(自动求导或者说偏导)
import torch
import numpy as np
print('----tensor自动微分(自动求导)')
x=torch.tensor([1.,2.,3.,4.,5.],requires_grad=True,dtype=torch.float32)#requires_grad=True设置为一个张量时,它告诉PyTorch跟踪涉及该张量的操作,以便在后向传播期间计算梯度。
print(x.requires_grad)
print(x.grad)#没有梯度返回none
print(x.grad_fn)#grad_fn: grad_fn用来记录变量是怎么来的,方便计算梯度,y = x*3,grad_fn记录了y由x计算的过程。
y=torch.sum(x**2)
print(y)
print(y.item()) #打印计算值
print(y.grad_fn)#打印计算方法
y.backward()#自动微分
print('shape:{0};{1}'.format(x.grad.size(),x.grad)) # 打印y对x的微分值
D:\Anaconda3\envs\pytorch\python.exe D:\learn_pytorch\学习过程\第一周的代码\代码9.py
----tensor自动微分(自动求导)
True
None
None
tensor(55., grad_fn=<SumBackward0>)
55.0
<SumBackward0 object at 0x000002326699ACD0>
shape:torch.Size([5]);tensor([ 2., 4., 6., 8., 10.])
进程已结束,退出代码0
以上就是tensor相关的所有运算了,大家可以和我一样,当笔记来看。