pytorch api文档:torch.pow()函数-幂运算 作者:马育民 • 2026-01-24 17:15 • 阅读:10001 # 介绍 PyTorch 中的 `torch.pow()` 函数,用于对张量进行 **幂运算** 的核心工具,支持标量幂、张量逐元素幂等多种运算形式。 ### 作用 **对张量中的每个元素进行幂运算**,支持“张量^标量”“张量^张量”两种核心形式,返回与输入形状匹配的新张量(除非指定 `out` 参数)。 # 基本语法 ```python torch.pow(input, exponent, out=None) ``` #### 参数说明: - `input`:输入张量(必传),可以是任意维度的张量; - `exponent`:指数,可以是**标量**(int/float/torch.Tensor)或**与input形状相同的张量**; - `out`:可选,指定输出张量(需与输入形状/类型匹配),节省内存。 ### 简洁写法 ``` input ** exponent ``` 效果与 `torch.pow(input, exponent)` 完全一致。 # 例子 ```python import torch # ========== 示例1:张量^标量(最常用) ========== # 一维张量的平方运算 x1 = torch.tensor([1, 2, 3, 4]) y1 = torch.pow(x1, 2) # 等价于 x1 ** 2 print("张量平方:", y1) # tensor([ 1, 4, 9, 16]) # 二维张量的立方运算 x2 = torch.tensor([[0.5, 1.5], [-2.0, 3.0]]) y2 = torch.pow(x2, 3) # 等价于 x2 ** 3 print("\n二维张量立方:\n", y2) # 输出: # tensor([[ 0.1250, 3.3750], # [-8.0000, 27.0000]]) # ========== 示例2:张量^张量(逐元素对应幂) ========== # 两个形状相同的张量,逐元素做幂运算 base = torch.tensor([[2, 3], [4, 5]]) exp = torch.tensor([[1, 2], [3, 4]]) y3 = torch.pow(base, exp) # 等价于 base ** exp print("\n张量^张量(逐元素):\n", y3) # 输出: # tensor([[ 2, 9], # [ 64, 625]]) # ========== 示例3:标量^张量(交换顺序) ========== # 注意:若指数是张量、底数是标量,需把标量放前面(或用运算符) y4 = torch.pow(2, torch.tensor([1, 2, 3])) # 2^1, 2^2, 2^3 print("\n标量^张量:", y4) # tensor([2, 4, 8]) # 运算符写法更直观:2 ** torch.tensor([1,2,3]) # ========== 示例4:负数幂(倒数运算) ========== x5 = torch.tensor([2.0, 4.0, 8.0]) y5 = torch.pow(x5, -1) # 等价于 1/x5 print("\n负数幂(倒数):", y5) # tensor([0.5000, 0.2500, 0.1250]) # ========== 示例5:小数幂(开方/开根) ========== x6 = torch.tensor([4.0, 9.0, 16.0]) y6 = torch.pow(x6, 0.5) # 平方根,等价于 torch.sqrt(x6) y7 = torch.pow(x6, 1/3) # 立方根 print("\n平方根:", y6) # tensor([2., 3., 4.]) print("立方根:", y7) # tensor([1.5874, 2.0801, 2.5198]) # ========== 示例6:指定out参数(节省内存) ========== x8 = torch.tensor([1,2,3]) out_tensor = torch.empty_like(x8) # 预分配输出张量 torch.pow(x8, 2, out=out_tensor) # 结果直接写入out_tensor print("\nout参数输出:", out_tensor) # tensor([1, 4, 9]) ``` # 注意 ### 数据类型兼容 若输入是整数张量、指数是小数,输出会自动转为浮点型;若输入是整数张量、指数是整数,输出保持整数型(除非结果溢出)。 ### 负数开偶次幂 整数张量的负数开偶次幂会报错(如 `torch.pow(torch.tensor(-2), 2)` 可行,但 `torch.pow(torch.tensor(-2), 0.5)` 会NaN),浮点张量的负数开偶次幂会返回NaN。 ```python # 示例:负数开平方(浮点型返回NaN,整数型报错) print(torch.pow(torch.tensor(-4.0), 0.5)) # tensor(nan) # print(torch.pow(torch.tensor(-4), 0.5)) # RuntimeError ``` ### 梯度支持 `torch.pow()` 支持自动微分( `requires_grad=True` 时),适合神经网络中的可微运算。 # 总结 1. `torch.pow(input, exponent)` 实现张量的幂运算,核心支持“张量^标量”“张量^张量”“标量^张量”三种形式,运算符 `**` 是更简洁的写法; 2. 常用场景:平方/立方、倒数(-1次幂)、开方(0.5次幂)、逐元素自定义幂运算; 3. 注意负数开偶次幂的NaN问题,整数/浮点张量的类型转换规则。 原文出处:http://malaoshi.top/show_1GW2eRN8CfdJ.html