pytorch基础【3】torch运算

文章目录

torch运算

基本运算

  1. 创建张量:

    python 复制代码
    import torch
    
    # 直接从列表或数组创建张量
    x = torch.tensor([1, 2, 3])

    创建特定值的张量:

    python 复制代码
    # 全零张量
    zeros = torch.zeros(3, 3)
    
    # 全一张量
    ones = torch.ones(3, 3)
    
    # 单位张量(对角线为1,其余为0)
    eye = torch.eye(3)
    
    # 随机张量
    rand = torch.rand(3, 3)
    
    # 从均值为0,标准差为1的正态分布中抽取的随机张量
    randn = torch.randn(3, 3)

    创建等差数列张量:

    python 复制代码
    # 从0到10(不包括10)的等差数列,步长为2
    arange = torch.arange(0, 10, 2)

    创建特定间隔的数列张量:

    python 复制代码
    # 从0到10均匀分布的5个数
    linspace = torch.linspace(0, 10, 5)
  2. 加法和减法:

    python 复制代码
    # 加法
    z = x + y  # torch.add(x, y)
    print(z)  # 输出: tensor([5, 7, 9])
    
    # 减法
    z = x - y  # torch.sub(x, y)
    print(z)  # 输出: tensor([-3, -3, -3])
  3. 乘法和除法:

    python 复制代码
    # 元素乘法
    z = x * y  # torch.mul(x, y)
    print(z)  # 输出: tensor([ 4, 10, 18])
    
    # 元素除法
    z = x / y  # torch.div(x, y)
    print(z)  # 输出: tensor([0.2500, 0.4000, 0.5000])
  4. 矩阵乘法:

    python 复制代码
    a = torch.tensor([[1, 2], [3, 4]])
    b = torch.tensor([[5, 6], [7, 8]])
    
    # 矩阵乘法
    z = torch.matmul(a, b)  # 或者 a @ b
    print(z)  # 输出: tensor([[19, 22], [43, 50]])

形状操作

  1. 改变形状:view()

    python 复制代码
    a = torch.tensor([[1, 2, 3], [4, 5, 6]])
    
    # 改变形状
    b = a.view(3, 2)
    print(b)
    # 输出:
    # tensor([[1, 2],
    #         [3, 4],
    #         [5, 6]])
    自动调整size (参数-1)

    view中一个参数指定为-1,代表自动调整这个维度上的元素个数,以保证元素的总数不变。

    python 复制代码
    import torch
    x1 = torch.arange(0,16)
    print(x1)
    #a1: tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])
    ------------------------------------------------------------------------------------------------------   
    x2 = x1.view(-1, 16)
    x3 = x1.view(-1, 8)
    x4 = x1.view(-1, 4)
    x5 = x1.view(-1, 2)
    
    
    print(x2)
    print(x3)
    print(x4)
    print(x5)
    
    
    x2: tensor([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15]])
    x3: tensor([[ 0,  1,  2,  3,  4,  5,  6,  7],
            [ 8,  9, 10, 11, 12, 13, 14, 15]])
    x4: tensor([[ 0,  1,  2,  3],
            [ 4,  5,  6,  7],
            [ 8,  9, 10, 11],
            [12, 13, 14, 15]])
    x5: tensor([[ 0,  1],
            [ 2,  3],
            [ 4,  5],
            [ 6,  7],
            [ 8,  9],
            [10, 11],
            [12, 13],
            [14, 15]])
  2. 拼接:

    python 复制代码
    x = torch.tensor([[1, 2], [3, 4]])
    y = torch.tensor([[5, 6], [7, 8]])
    
    # 沿着0轴拼接(垂直拼接)
    z = torch.cat((x, y), dim=0)
    print(z)
    # 输出:
    # tensor([[1, 2],
    #         [3, 4],
    #         [5, 6],
    #         [7, 8]])
    
    # 沿着1轴拼接(水平拼接)
    z = torch.cat((x, y), dim=1)
    print(z)
    # 输出:
    # tensor([[1, 2, 5, 6],
    #         [3, 4, 7, 8]])
  3. 切片:

    python 复制代码
    a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    
    # 切片
    b = a[:, 1]  # 第二列
    print(b)  # 输出: tensor([2, 5, 8])

数学运算

  1. 求和:sum()

    python 复制代码
    x = torch.tensor([1, 2, 3, 4])
    
    # 求和
    sum_x = torch.sum(x)
    print(sum_x)  # 输出: tensor(10)
  2. 均值:mean()

    python 复制代码
    # 均值
    mean_x = torch.mean(x.float())  # 转换为浮点数类型
    print(mean_x)  # 输出: tensor(2.5000)
  3. 最大值和最小值:max(),min()

    python 复制代码
    # 最大值
    max_x = torch.max(x)
    print(max_x)  # 输出: tensor(4)
    
    # 最小值
    min_x = torch.min(x)
    print(min_x)  # 输出: tensor(1)

逻辑运算

  1. 比较运算:

    python 复制代码
    x = torch.tensor([1, 2, 3])
    y = torch.tensor([2, 2, 2])
    
    # 大于
    print(x > y)  # 输出: tensor([False, False,  True])
    
    # 小于
    print(x < y)  # 输出: tensor([ True, False, False])
  2. 逻辑与、或:

    python 复制代码
    a = torch.tensor([True, False, True])
    b = torch.tensor([False, False, True])
    
    # 逻辑与
    c = torch.logical_and(a, b)
    print(c)  # 输出: tensor([False, False,  True])
    
    # 逻辑或
    c = torch.logical_or(a, b)
    print(c)  # 输出: tensor([ True, False,  True])

常见的高级操作

  1. 广播机制:

    python 复制代码
    a = torch.tensor([1, 2, 3])
    b = torch.tensor([[1], [2], [3]])
    
    # 广播机制
    c = a + b
    print(c)
    # 输出:
    # tensor([[2, 3, 4],
    #         [3, 4, 5],
    #         [4, 5, 6]])
  2. 自动梯度计算:

    python 复制代码
    x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
    
    # 前向传播
    y = x + 2
    z = y * y * 2
    out = z.mean()
    
    # 反向传播
    out.backward()
    print(x.grad)  # 输出: tensor([4.6667, 6.0000, 7.3333])

随机数生成

  1. 从标准正态分布中生成随机张量:

    python 复制代码
    randn_tensor = torch.randn(3, 3) # 生成一个形状为 (3, 3) 的随机张量,服从标准正态分布
    print(randn_tensor)
    #tensor([[ 1.2335, -0.3941,  0.8990],
    #        [ 0.0470, -1.2671,  0.3248],
    #       [-0.4062, -0.6862,  0.1314]])
  2. 生成随机排列:

    python 复制代码
    randperm_tensor = torch.randperm(10)  # 生成一个从 0 到 9 的随机排列
    print(randperm_tensor)
    #tensor([2, 0, 5, 1, 8, 6, 3, 4, 7, 9])
  3. 生成等差数列张量:

    python 复制代码
    arange_tensor = torch.arange(0, 10, 2) # 生成从 0 到 10(不包括 10)的等差数列,步长为 2
    print(arange_tensor)
    #tensor([0, 2, 4, 6, 8])
相关推荐
IT古董28 分钟前
第四章:大模型(LLM)】06.langchain原理-(3)LangChain Prompt 用法
java·人工智能·python
TGITCIC1 小时前
AI Search进化论:从RAG到DeepSearch的智能体演变全过程
人工智能·ai大模型·ai智能体·ai搜索·大模型ai·deepsearch·ai search
lucky_lyovo5 小时前
自然语言处理NLP---预训练模型与 BERT
人工智能·自然语言处理·bert
fantasy_arch5 小时前
pytorch例子计算两张图相似度
人工智能·pytorch·python
AndrewHZ6 小时前
【3D重建技术】如何基于遥感图像和DEM等数据进行城市级高精度三维重建?
图像处理·人工智能·深度学习·3d·dem·遥感图像·3d重建
飞哥数智坊7 小时前
Coze实战第18讲:Coze+计划任务,我终于实现了企微资讯简报的定时推送
人工智能·coze·trae
WBluuue7 小时前
数学建模:智能优化算法
python·机器学习·数学建模·爬山算法·启发式算法·聚类·模拟退火算法
Code_流苏7 小时前
AI热点周报(8.10~8.16):AI界“冰火两重天“,GPT-5陷入热议,DeepSeek R2模型训练受阻?
人工智能·gpt·gpt5·deepseek r2·ai热点·本周周报
赴3357 小时前
矿物分类案列 (一)六种方法对数据的填充
人工智能·python·机器学习·分类·数据挖掘·sklearn·矿物分类
大模型真好玩7 小时前
一文深度解析OpenAI近期发布系列大模型:意欲一统大模型江湖?
人工智能·python·mcp