pytorch学习笔记(一)
一、pytorch基本数据类型
pytprch最基本的操作对象是tensor(张量),它表示一个多维矩阵,类似于NumPy的ndaarrays,张量可以在GPU上做高速计算
使用步骤:
构造一个初始化矩阵:torch.rand
全0矩阵:torch.zeros
全1矩阵:torch.ones
pytorch基本数据类型
IntTensor of size()------------>对应python中int
FloatTensor of size()------------>对应python中int
IntTensor of size[d1,d2====]------------>对应python中Int array
FloatTensor of size()------------>对应python中Float array
import torch
a=torch.randn(2,3) # 正态分布
b=torch.rand(2,3) # 生成均匀分布的随机数
c=torch.zeros(2,3)
d=torch.ones(2,2,3)
print(a.size(0)) # 可以指定维度
print(a.shape)
print(a)
print(b)
print(c)
print(d)
print(a.type()) # torch.FloatTensor
print(isinstance(a,torch.FloatTensor))
e = torch.tensor([6,2],dtype=torch.float32)
print(e)
e.type(torch.int32) # 类型转换
print(e)
二、tensor方法
Tensor方法:
torch.full 填充
torch.empty 为空
torch.rand 随机数
torch.randn 均值为0,方差为1
torch.randint随机整数
torch.add 加法
torch.tensor 创建
torch.torch.from_numpy(numpy矩阵):Numpy转换为Tensor
torch.reshape 改变形状
torch.numel 统计数目
torch.view 视图
torch.arrange 范围
torch.linspace 间隔
torch.eye 对角线
torch.cat 连接
torch.index_select 根据索引选择
torch.narrow 缩小
torch.t 转置
torch.take 根据索引获取元素
torch.transpose 转置
torch.split分割
import torch
import numpy as np
# Tensor方法
t1 = torch.rand(1,2)
a = torch.is_tensor(t2)
print(a)
# 创建一个全0 tensor
t3 = torch.zeros(3,2)
num = torch.numel(t3)
# 创建对角线为1的tensor
t4 = torch.eye(3,3)
print(t4)
# 将numpy转化为tensor
n = np.array([1,2,3,4])
t5 = torch.from_numpy(n)
print(int)
# 切分
t6 = torch.linspace(1,10,steps=5) # 从1开始到10,切分成5份
print(t6)
# 创建均匀分布,值在0到1之间
t7 = torch.rand(10)
print(t7)
# 创建正态分布
t8 = torch.randn(10)
print(t8)
# 选择随机数 从1到10
t9 = torch.randperm(10)
# 生成一个固定区间的数
t10 = torch.arange(1,10,3) # 从1到10,步长为3
# 获取行或列的最小值和最大值索引
x = torch.randint(1,99,(3,3))
t11 = torch.argmin(x,dim=0)
t12 = torch.argmax(x,dim=0)
# 连接
y = torch.randint(1,10,(2,3))
t13 = torch.cat(y,y,dim=1) # 1是横轴
# 切块
z= torch.randint(1,10,(3,3))
torch.chunk(a,2,0)
# 根据索引选择
m = torch.randn(4,4)
index= torch.tensor([0,2]) # 输出0行和第2行
t15 = torch.index_select(m,0,index)
# 分割
n = torch.tensor([1,2,3,4,5,6,7])
t16 = torch.split(n,3) # 将n切分成3份
# 转置
p = torch.tensor([[1,3][2,4]])
p.transpose(1,0)
p.t()
# tensor运算
t17 = torch.tensor([[1,2][3,4]])
torch.add(t17,1) # 所有元素加1
torch.mul(t17,2) # 所有元素乘2