您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# torch.tensor中fill_(value)如何使用
## 一、函数概述
`fill_(value)`是PyTorch中张量(Tensor)对象的一个原地(in-place)操作方法,用于将张量的所有元素设置为指定的标量值。该操作会直接修改原始张量,不返回新的张量对象。
### 基本语法
```python
tensor.fill_(value)
import torch
# 创建一个3x3的未初始化张量
x = torch.empty(3, 3)
print("原始张量:\n", x)
# 使用fill_填充值
x.fill_(5)
print("填充后的张量:\n", x)
# 浮点型张量
float_tensor = torch.tensor([1.0, 2.0, 3.0])
float_tensor.fill_(0.5)
# 整型张量
int_tensor = torch.tensor([1, 2, 3], dtype=torch.int32)
int_tensor.fill_(10)
# 布尔型张量
bool_tensor = torch.tensor([True, False])
bool_tensor.fill_(True)
x = torch.arange(9).view(3, 3)
print("原始矩阵:\n", x)
# 只填充特定区域
x[1:, 1:].fill_(-1)
print("部分填充后:\n", x)
x = torch.randn(3, requires_grad=True)
y = x * 2
y.fill_(10) # 这会破坏计算图,导致无法反向传播
注意:对需要梯度的张量使用原地操作可能导致梯度计算错误
import time
large_tensor = torch.zeros(10000, 10000)
# 方法1: 使用fill_
start = time.time()
large_tensor.fill_(1.0)
print(f"fill_耗时: {time.time()-start:.4f}s")
# 方法2: 使用乘法
start = time.time()
large_tensor = large_tensor * 0 + 1.0
print(f"乘法耗时: {time.time()-start:.4f}s")
# fill_是原地操作
x = torch.empty(2, 2)
x.fill_(7)
# full是构造函数
y = torch.full((2, 2), 7)
可能原因: 1. 对非连续内存的张量操作 2. 张量被其他操作锁定 3. 在requires_grad=True的张量上操作
x = torch.randn(3, requires_grad=True)
with torch.no_grad():
x.fill_(10)
weights = torch.empty(256, 256)
weights.fill_(0.01) # 小常数初始化
mask = torch.empty(10, 10)
mask.fill_(float('-inf'))
mask.fill_diagonal_(0) # 对角线置0
# 创建RGB图像张量 (H, W, 3)
image = torch.empty(256, 256, 3)
image.fill_(0) # 黑色背景
image[100:150, 100:150].fill_(255) # 白色矩形区域
# GPU加速示例
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
large_tensor = torch.empty(10000, 10000, device=device)
large_tensor.fill_(0.5)
fill_(value)
是PyTorch中高效初始化或重置张量内容的利器,掌握其使用方法和注意事项可以:
- 简化代码逻辑
- 提高内存使用效率
- 避免不必要的张量复制
- 在特定场景下显著提升性能
使用时需特别注意原地操作对自动微分的影响,合理选择是否需要在计算图中保留该操作。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。