目录
(1)深度学习数据为tensor
1. tensor 类型转换
import numpy as np
import torch
torch.tensor([1,2,3,4])
>>>tensor([1,2,3,4])
torch.tensor([1,2,3,4]).dtype
>>>torch.int64
指定数据类型:
torch.tensor([1,2,3,4],dtype=torch.float32)
>>>tensor([1.,2.,3.,4.])
torch.tensor([1,2,3,4],dtype=torch.float32).dtype
>>>torch.float32
2. tensor 生成
(1)生成3*3的矩阵,矩阵元素服从【0,1)上的均匀分布
torch.rand(3,3)
(2)生成2*3*4的tensor,张量元素服从标准正太分布
torch.randn(2,3,4)
tensor([[[a,b,c,d],[ ],[ ]],[[ ],[ ],[ ]]])
(3)生成2*2*2的tensor,元素全部为0
torch.zeros(2,2,2)
tensor([[[a,b],[a,b]],[[ ],[ ]]])
(4)生成1*2*3的tensoe,元素全部为1
torch.ones(1,2,3)
tensor([[[1,1,1],[1,1,1]]])
(5)生成3*3的单位矩阵
torch.eyes(3)
tensor([[1.,0.,0.],[0.,1.,0.],[0.,0.,.]]
(6)生成0-10 均匀分布整数的3*3矩阵
torch。randint(0,10,(3,3))
3. tensor 形状
torch.size
4. tensor维度变化
【a 】view函数:
torch.view(-1) 第一个-1系统自动划分维度值
【b 】reshape函数:
5.tensor索引、切片
t=torch.randn(2,3,4)
tensor([[[1,2,3,4]
[5,6,7,8]
[9,1,4,6]]
[[1,3,4,5]
[3,4,5,6]
[5,4,6,7]]])
(1)t[1,2,3]
张量0维1号、1维2号、2维3号元素
>>>tensor(7)
解释;
排号都是从0开始
0维1号: [[1,3,4,5]
[3,4,5,6]
[5,4,6,7]]
1维2号:1维: [1,3,4,5] 2号:[5,4,6,7]
[3,4,5,6]
[5,4,6,7]
2维3号:[5,4,6,7] 3号:7
(2)t[:,1:-1,1:3]
:代表所有
>>>tensor([[[6,7]
[1,4]]
[[4,5]
[4,6]]])
解释:
:所有维度 [[[ ],[ ],[ ]],[[ ],[ ],[ ]]]
1:-1 第一行数---最后一行数
1:3 第一列数---第二列数
6.tensor函数运算、求极值、排序
t=torch.rand(3,4)
t.sqrt() --------求平方根
torch.sqrt(t) ---求平方根,函数形式
不改变原来张量
t.sqrt_()
torch.sqrt_(t)
原地操作,改变原来张量
torch.argmax(t,0)
第0维,最大值所在位置
t.argmin(1)
第一维度,最小值位置
torch.max()
t.max(0)
t.sort ------返回排序后tensor, 位置 :
举例:
原:[[[0,2,9,6],[ ],[ ]],[[ ],[ ],[ ]]]
后:[[[0,2,6,9],[ ],[ ]],[[ ],[ ],[ ]]]
[[[0,1,3,2],[ ],[ ]],[[ ],[ ],[ ]]] 对用原来张量的位置索引
7. 张量的广播
不同维度之间进行运算,将维度较小的张量扩增。
举例:
t1=torch.randn(3,4,5)
t2=torch.randn(3,5)
【将t2 展开成 3*1*5 和t1运算沿着第二维度复制四次,变成3*4*5】
t2.unsequeeeze(1)
补充:
安装:
1、
pip install -i https://pypi.tuna.stinghua.edu.cn/simple/ torch==1.7.0