import torch
import numpy as np
DEVICE='cuda' if torch.cuda.is_available() else 'cpu'
# 初始化方法1
x=torch.tensor([[1,2,7],[3,4,5]],dtype=torch.float32,device=DEVICE,requires_grad=True)
# 初始化方法2
input=torch.rand((3,3))
x=torch.rand_like(input) # 产生与input相同尺寸的tensor 数据时均匀分布的
x=torch.ones((2,3)) # 全1
# 常见方法
torch.is_tensor(x) # 判断是不是一个tensor
torch.numel(x) # 统计tensor中元素的个数
torch.zeros((2,3)) # 创建全0的tensor
torch.eye(3,3) # 创建对角阵
x=np.array([1,2,3])
x=torch.from_numpy(x) # 将numpy装换成tensor
torch.linspace(start=2,end=10,steps=5) # 将2-10直接的数字切分为5份
torch.rand((2,3)) # 创建数据为均匀分布
torch.randn((2,3)) # 创建数据为正态分布
torch.randperm(10) # 得到0-9 10个数 但是顺序打乱
torch.arange(start=0,end=10,step=1) #生成0-10区间的数 步长为1 但是不包含10
x=torch.randint(low=1,high=5,size=(2,3)) #可以规定元素的最大最小值
torch.argmax(x,dim=0) # 获取每一列的最大值的下标 dim=0每一列 dim=1是每一行
x=torch.cat((x,x),dim=0) # 将两个tensor堆叠起来 dim=0是纵方向的堆叠 dim=1是横方向的堆叠
list= torch.chunk(x,chunks=2,dim=0) #将一个tensor切开 chunks表示切到哪里为止 返回一个tensor列表
index=torch.tensor([0,2])
x=torch.index_select(x,dim=0,index=index) # 根据索引选择
torch.split(x,3,dim=0) # 将tensor切分为若干份 每份是3个元素
x.t() # 矩阵转置
torch.add(x,1) # 每个元素+1
torch.mul(x,2) # 每个元素乘上2
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)