张量操作和线性回归
张量操作
张量的拼接
torch.cat()
torch.cat(
tensor,
dim=0,
out=None)
功能:将张量按照维度dim进行拼接
tensor:张量序列
dim:要拼接的维度
torch.stack()
torch.stack(
tensor,
dim=0,
out=None)
功能:在新创建的维度上进行拼接
tensor:张量序列
dim:要拼接的维度
注意
cat与stack同为拼接,但不同之处在于stack创建新的维度。
可以将cat理解为List的extend操作,stack理解为List的append操作。
张量的切分
torch.chunk()
torch.chunk(
input_data,
chunks,
dim=0)
功能:将张量按照维度dim进行平均切分
返回值:张量列表
input_data:要切分的张量
chunks:要切分的份数
dim:要切分的维度
注意:若不能整除则最后一份张量要小于其他张量
torch.split()
torch.split(
tensor,
split_size_or_sections,
dim=0)
功能:将张量按照维度dim进行切分
返回值:张量列表
tensor:要切分的张量
split_size_or_sections:
- 为int时,表示每一份的长度
- 为list时,按照list元素切分
dim:要切分的维度
注意:当为int时,与chunk一样,当为list时,切分前后的大小必须相同
张量的索引
torch.index_select()
torch.index_select(
tensor,
dim,
index,
out=None)
功能:在维度dim上,按照index索引数据
返回值:依据index索引数据拼接的张量
tensor:要索引的张量
dim:要索引的维度
index:要索引数据的序号
torch.masked_select()
torch.masked_select(
tensor,
mask,
out=None)
功能:按照mask中的True进行索引
返回值:一维张量
tensor:要索引的张量
mask:与tensor形状相同的布尔类型张量
注意:masked_select多用于筛选数据
张量的变换
torch.reshape()
torch,reshape(
tensor,
shape)
功能:变换张量形状
tensor:要变换的张量
shape:新张量的形状
注意:如果张量在内存中是连续的时候,新张量与原始张量共享内存
torch.transpose()
torch.transpose(
tensor,
dim0,
dim1)
功能:交换张量的两个维度
tensor:要交换的张量
dim0:要交换的维度
dim1:要交换的维度
torch.t()
torch.t(tensor)
功能:2维张量(矩阵)转置,等价于torch.transpose(tensor,0,1)
torch.squeeze()
torch.squeeze(
tensor,
dim=None,
out=None)
功能:压缩长度为1的维度(轴)
dim:
- 若为None,移除所有长度为1的轴
- 若指定数值,当且仅当该轴的长度为1时,可被移除
torch.unsqueeze()
torch.unsqueeze(
tensor,
dim,
out=None)
功能:依据dim扩展维度
dim:扩展的维度
张量的数学运算
张量的数学运算包含有:
- 加减乘除
- 对数、指数、幂函数
- 三角函数
torch.add()
torch.addcdiv()
torch.addcmul()
torch.sub()
torch.div()
torch.mul()
torch.log(tensor,out=None)
torch.log10(tensor,out=None)
torch.log2(tensor,out=None)
torch.exp(tensor,out=None)
torch.pow()
torch.abs(tensor,out=None)
torch.acos(tensor,out=None)
torch.cosh(tensor,out=None)
torch.cos(tensor,out=None)
torch.asin(tensor,out=None)
torch.atan(tensor,out=None)
torch.atan2(tensor,other,out=None)
torch.add()
torch.add(
tensor,
alpha=1,
other,
out=None)
功能:逐个元素计算
tensor:第一个张量
alpha:乘项因子
other:第二个张量
torch.addcdiv()
torch.addcmul()
线性回归
线性回归是分析一个变量与另外一个(或多个)变量之间关系的方法。
因变量:y
自变量:x
关系:线性
求解
和
的步骤:
- 确定模型:
Model: - 选择损失函数
MSE: - 求解梯度,并更新
和