# 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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。