张量操作与线性回归
张量的操作
张量拼接与切分
torch.cat和torch.stack
torch.cat()
功能:将张量按维度dim进行拼接
- tensors: 张量序列
- dim: 要拼接的维度
torch.stack()
功能:在新创建的维度dim上进行拼接
- tensors: 张量序列
- dim: 要拼接的维度
import torch
torch.manual_seed(1)
# ======================================= example 1 =======================================
# torch.cat
# flag = True
flag = False
if flag:
t = torch.ones((2, 3))
t_0 = torch.cat([t, t], dim=0)
t_1 = torch.cat([t, t, t], dim=1)
print("t_0:{} shape:{}\nt_1:{} shape:{}".format(t_0, t_0.shape, t_1, t_1.shape))
flag = False
if flag:
t = torch.ones((2, 3))
t_stack = torch.stack([t, t, t], dim=0)
print("\nt_stack:{} shape:{}".format(t_stack, t_stack.shape))
torch.chunk
torch.chunk()
功能:将张量按维度dim进行平均切分
返回值: 张量列表
注意事项:若不能整除,最后一份张量小于其他张量
- input: 要切分的张量
- chunks: 要切分的份数
- dim: 要切分的维度
# torch.chunk
# flag = True
flag = False
if flag:
a = torch.ones((2, 7)) # 7
list_of_tensors = torch.chunk(a, dim=1, chunks=3) # 3
for idx, t in enumerate(list_of_tensors):
print("第{}个张量:{}, shape is {}".format(idx+1, t, t.shape))
torch.split
torch.split()
功能:将张量按维度dim进行切分
返回值:张量列表
- tensor: 要切分的张量
- split_size_or_sections: 为int时,表示每一份的长度;为list时,按list元素切分
- dim: 要切分的维度
# flag = True
flag = False
if flag:
t = torch.ones((2, 5))
list_of_tensors = torch.split(t, [2, 1, 1], dim=1) # [2 , 1, 2]
for idx, t in enumerate(list_of_tensors):
print("第{}个张量:{}, shape is {}".format(idx+1, t, t.shape))
# list_of_tensors = torch.split(t, [2, 1, 2], dim=1)
# for idx, t in enumerate(list_of_tensors):
# print("第{}个张量:{}, shape is {}".format(idx, t, t.shape))
张量的索引
torch.index_select
torch.index_select()
功能:在维度dim上,按index索引数据
返回值:依index索引数据拼接的张量
- input: 要索引的张量
- dim: 要索引的维度
- index: 要索引数据的序号
# torch.index_select
# flag = True
flag = False
if flag:
t = torch.randint(0, 9, size=(3, 3))
idx = torch.tensor([0, 2], dtype=torch.long) # float
t_select = torch.index_select(t, dim=0, index=idx)
print("t:\n{}\nt_select:\n{}".format(t, t_select))
torch.masked_select
torch.masked_select()
功能:按mask中的True进行索引
返回值:一维张量
- input: 要索引的张量
- mask: 与input同形状的布尔类型张量
# torch.masked_select
# flag = True
flag = False
if flag:
t = torch.randint(0, 9, size=(3, 3))
mask = t.le(5) # ge is mean greater than or equal/ gt: greater than le lt
t_select = torch.masked_select(t, mask)
print("t:\n{}\nmask:\n{}\nt_select:\n{} ".format(t, mask, t_select))
张量变换
torch.reshape
torch.reshape()
功能:变换张量形状注意事项:当张量在内存中是连续时,新张量与input共享数据内存
- input: 要变换的张量
- shape: 新张量的形状
# torch.reshape
# flag = True
flag = False
if flag:
t = torch.randperm(8)
t_reshape = torch.reshape(t, (-1, 2, 2)) # -1
print("t:{}\nt_reshape:\n{}".format(t, t_reshape))
t[0] = 1024
print("t:{}\nt_reshape:\n{}".format(t, t_reshape))
print("t.data 内存地址:{}".format(id(t.data)))
print("t_reshape.data 内存地址:{}".format(id(t_reshape.data)))
torch.transpose与torch.t
torch.transpose()
功能:交换张量的两个维度
- input: 要变换的张量
- dim0: 要交换的维度
- dim1: 要交换的维度
torch.t()
功能:2维张量转置,对矩阵而言,等价于torch.transpose(input,0,1)
# torch.transpose
# flag = True
flag = False
if flag:
# torch.transpose
t = torch.rand((2, 3, 4))
t_transpose = torch.transpose(t, dim0=1, dim1=2) # c*h*w h*w*c
print("t shape:{}\nt_transpose shape: {}".format(t.shape, t_transpose.shape))
torch.squeeze与torch.unsqueeze
torch.squeeze()
功能:压缩长度为1的维度(轴)
- dim:若为None,移除所有长度为1的轴;若指定维度,当且仅当该轴长度为1时,可以被移除
torch.unsqueeze()
功能:依据dim扩展维度
- dim:扩展的维度
# torch.squeeze
# flag = True
flag = False
if flag:
t = torch.rand((1, 2, 3, 1))
t_sq = torch.squeeze(t)
t_0 = torch.squeeze(t, dim=0)
t_1 = torch.squeeze(t, dim=1)
print(t.shape)
print(t_sq.shape)
print(t_0.shape)
print(t_1.shape)
张量的数学运算
常见操作
torch.add
torch.add()
功能:逐元素计算input+alpha×other
- input:第一个张量
- alpha:乘项因子
- other:第二个张量
torch.addcdiv()
torch.addcmul()
# torch.add
# flag = True
flag = False
if flag:
t_0 = torch.randn((3, 3))
t_1 = torch.ones_like(t_0)
t_add = torch.add(t_0, 10, t_1)
print("t_0:\n{}\nt_1:\n{}\nt_add_10:\n{}".format(t_0, t_1, t_add))
线性回归
求解步骤:
- 确定模型
- 选择损失函数
- 求解梯度并更新w,b
# -*- coding:utf-8 -*-
"""
@file name : lesson-03-Linear-Regression.py
@author : tingsongyu
@date : 2018-10-15
@brief : 一元线性回归模型
"""
import torch
import matplotlib.pyplot as plt
torch.manual_seed(10)
lr = 0.05 # 学习率 20191015修改
# 创建训练数据
x = torch.rand(20, 1) * 10 # x data (tensor), shape=(20, 1)
y = 2*x + (5 + torch.randn(20, 1)) # y data (tensor), shape=(20, 1)
# 构建线性回归参数
w = torch.randn((1), requires_grad=True)
b = torch.zeros((1), requires_grad=True)
for iteration in range(1000):
# 前向传播
wx = torch.mul(w, x)
y_pred = torch.add(wx, b)
# 计算 MSE loss
loss = (0.5 * (y - y_pred) ** 2).mean()
# 反向传播
loss.backward()
# 更新参数
b.data.sub_(lr * b.grad)
w.data.sub_(lr * w.grad)
# 清零张量的梯度 20191015增加
w.grad.zero_()
b.grad.zero_()
# 绘图
if iteration % 20 == 0:
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), y_pred.data.numpy(), 'r-', lw=5)
plt.text(2, 20, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'})
plt.xlim(1.5, 10)
plt.ylim(8, 28)
plt.title("Iteration: {}\nw: {} b: {}".format(iteration, w.data.numpy(), b.data.numpy()))
plt.pause(0.5)
if loss.data.numpy() < 1:
break
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」