张量的形状操作以及拼接

张量的形状操作函数概括

张量的形状变换操作函数

reshape()

squeeze()

unsqueeze()

transpose()

permute()

view()

contiguous()

需要掌握的函数

reshape()、unsqueeze()、permute()、view()

reshape()

在不改变内容的前提下,对其形状做改变。

注意:转换后元素总的个数不能变

python 复制代码
torch.random.manual_seed(10)
t1 = torch.randint(0,11,[2,3])
print(f"t1 = {t1}")
print(f"t1.shape = {t1.shape}")
t2  = t1.reshape(3,2)
print(f"t2 = {t2}")
print(f"t2.shape = {t2.shape}")

unsqueeze()

在指定的轴上增加一个(1)维度

python 复制代码
t1 = torch.randint(0, 11, [2, 3])
    t2 = t1.unsqueeze(0)
    print(f"t2 = {t2}")
    print(f"t2.shape = {t2.shape}")
    t3 = t1.unsqueeze(1)
    print(f"t3 = {t3}")
    print(f"t3.shape = {t3.shape}")
    t4 = t1.unsqueeze(2)
    print(f"t4 = {t4}")
    print(f"t4.shape = {t4.shape}")

squeeze()

删除所有为1的维度,等价于降维

python 复制代码
t1 = torch.randint(0, 11, [2,1,3,1,1])
    print(f"t1 = {t1}")
    print(f"t1.shape = {t1.shape}")
    t2 = t1.squeeze()
    print(f"t2 = {t2}")
    print(f"t2.shape = {t2.shape}")

transpose()和permute()

transpose() 一次只能交换2个维度

permute() 一次可以同时交换多个维度

python 复制代码
t1 = torch.randint(0, 11, [2,3,4])
    print(f"t1.shape = {t1.shape}")
    t2 = t1.transpose(0,1)
    print(f"t2.shape = {t2.shape}")
    t3 = t1.permute(2,0,1)
    print(f"t3.shape = {t3.shape}")

view()和contiguous()

view只修改连续的张量的形状(连续指的是内存的连续)

view可以改变原来的张量比如t1.view(),t1的形状也发生了改变

is_contiguous() 判断张量是否连续

contiguous() 将不连续的张量变成连续的

python 复制代码
t1 = torch.randint(0, 11, [2,3])
    t2 = t1.view(3,2)
    print(f"t2.shape = {t2.shape}")
    #通过transpose将张量变为不连续的
    t1 = t1.transpose(1,0)
    # print(f"t1.is_contiguous() = {t1.is_contiguous()}")
    # t3 = t1.view(2,3)
    # print(f"t3.shape = {t3.shape}")
    #通过contiguous()变为连续的然后再转换
    t1 = t1.contiguous()
    print(f"t1.shape = {t1.shape}")
    t4 = t1.view(2,3)
    print(f"t4.shape = {t4.shape}")

张量的拼接

cat() 不改变维度数拼接张量,除了拼接的那个维度外其它的维度必须保持一致

stack() 会改变维度,拼接张量,所有的维度都必须保持一致

拼接张量可以是新维度,但是无论新旧维度,所有维度都必须保持一致

cat()

python 复制代码
t1 = torch.randint(0,5,[3,4])
t2 = torch.randint(0,5,[2,4])
t3 = torch.cat([t1,t2],dim=0)
print(f"t3.shape = {t3.shape}")

stack()

python 复制代码
t1 = torch.randint(0,5,[2,3])
t2 = torch.randint(0,5,[2,3])
t3 = torch.stack([t1,t2],dim=0)
print(f"t3.shape:{t3.shape}")
t4 = torch.stack([t1,t2],dim=1)
print(f"t4.shape:{t4.shape}")
t5 = torch.stack([t1,t2],dim=2)
print(f"t5.shape:{t5.shape}")
相关推荐
民乐团扒谱机16 分钟前
【微实验】NSGA-II(非支配排序遗传算法)——解决多目标优化问题的“自然选择模拟器”
linux·人工智能·算法
怎么全是重名1 小时前
VerdictAD
人工智能·异常检测·few-shot·zsas·异常分割
Bode_20021 小时前
具身智能机构设计的质量控制
人工智能
阿里云大数据AI技术1 小时前
EMR Serverless StarRocks × Lance:多模态分析与检索的云上实践
人工智能
SelectDB2 小时前
数据不能出境的数仓选型与迁移落地:四问框架、可复算成本与迁移三段式
人工智能
李青菜2 小时前
一个人 + AI,用 Tauri 2 和 Rust 写了个开源的 Windows 效率工具:提醒 + 笔记 + 启动器
人工智能
泯泷2 小时前
做 AI 产品,路线图该数“实验”,而不是数“功能”
人工智能·llm·产品
百度Geek说2 小时前
AI 内容核查怎么做:智能内容 AI 核查系统实践
人工智能
武子康2 小时前
Qwen-Drive 到底是什么:4B 级 VLM 如何成为驾驶策略底座
人工智能·算法·机器学习