Pytorch 是當下最流行的算法框架,很多大模型都是基于Pytorch 搭建而成,它提供了大量操作用于創建和訓練神經網絡。
今天給大家分享 Pytorch 的19個方面,涉及到70個細節操作,這部分內容梳理花了我一天的時間,喜歡記得點個贊
本文從 Pytorch 的操作開始分享,
-
創建張量
-
張量屬性
-
張量索引、切片與拼接
-
張量變換
-
數學運算
-
匯總統計
-
梯度相關
-
數據管理
-
其他操作基礎操作
-
自動求導
-
神經網絡模塊
-
數據加載與處理
-
損失函數
-
優化器
-
模型訓練與驗證
-
模型保存與加載
-
GPU 加速
-
模型調優
-
遷移學習
技術交流&資料
技術要學會分享、交流,不建議閉門造車。一個人可以走的很快、一堆人可以走的更遠。
成立了 Pytorch 算法面試和技術交流群,相關資料、技術交流&答疑,均可加我們的交流群獲取,群友已超過2000人,添加時最好的備注方式為:來源+興趣方向,方便找到志同道合的朋友。
方式①、微信搜索公眾號:機器學習社區,后臺回復:加群
方式②、添加微信號:mlc2040,備注:來自CSDN + 技術交流
創建張量
torch.tensor(data)
: 從數據創建張量
這個函數會根據提供的數據創建一個新的張量。數據可以是列表、數組等。
import torchdata = [1, 2, 3, 4, 5]
tensor_data = torch.tensor(data)
print(tensor_data)
torch.zeros(size)
: 創建元素全為0的張量
創建一個指定大小的張量,其中所有元素的值都為0。
import torchsize = (2, 3)
zeros_tensor = torch.zeros(size)
print(zeros_tensor)
torch.ones(size)
: 創建元素全為1的張量
創建一個指定大小的張量,其中所有元素的值都為1。
import torchsize = (2, 3)
ones_tensor = torch.ones(size)
print(ones_tensor)
torch.empty(size)
: 創建未初始化的張量
創建一個指定大小的未初始化張量,其值取決于內存的狀態。
import torchsize = (2, 3)
empty_tensor = torch.empty(size)
print(empty_tensor)
torch.randn(size)
: 創建服從標準正態分布的張量
創建一個指定大小的張量,其中的元素值是從標準正態分布中隨機抽取的。
import torchsize = (2, 3)
randn_tensor = torch.randn(size)
print(randn_tensor)
torch.arange(start, end, step)
: 創建一個范圍內的一維張量
創建一個一維張量,其中的元素值從起始值到結束值,步長為給定的步長。
import torchstart = 0
end = 5
step = 1
arange_tensor = torch.arange(start, end, step)
print(arange_tensor)
torch.linspace(start, end, steps)
: 創建一個在指定范圍內均勻間隔的張量
創建一個一維張量,其中的元素值在指定范圍內均勻分布。
import torchstart = 0
end = 5
steps = 5
linspace_tensor = torch.linspace(start, end, steps)
print(linspace_tensor)
張量屬性
.dtype
: 獲取張量的數據類型
返回張量中元素的數據類型。
import torchtensor = torch.tensor([1, 2, 3])
print(tensor.dtype)
.shape
: 獲取張量的形狀
返回一個元組,表示張量的形狀。
import torchtensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(tensor.shape)
.device
: 獲取張量所在的設備
返回一個字符串,表示張量所在的設備,如’cpu’或’cuda:0’。
import torchtensor = torch.tensor([1, 2, 3])
print(tensor.device)
張量索引、切片與拼接
tensor[index]
: 索引操作
使用索引來訪問張量中的元素。
import torchtensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
element = tensor[0, 1] # Accesses the element at row 0, column 1
print(element)
tensor[start:end]
: 切片操作
使用切片來獲取張量的子張量。
import torchtensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
sub_tensor = tensor[:, 1:] # Slices the tensor to get all rows and columns starting from the second column
print(sub_tensor)
torch.cat(tensors, dim)
: 在給定維度上連接張量
沿著指定維度將多個張量連接在一起。
import torchtensor1 = torch.tensor([[1, 2], [3, 4]])
tensor2 = torch.tensor([[5, 6], [7, 8]])
concatenated_tensor = torch.cat((tensor1, tensor2), dim=0) # Concatenates along the row dimension
print(concatenated_tensor)
torch.stack(tensors, dim)
: 在新維度上堆疊張量
在一個新的維度上堆疊多個張量。
import torchtensor1 = torch.tensor([1, 2, 3])
tensor2 = torch.tensor([4, 5, 6])
stacked_tensor = torch.stack((tensor1, tensor2), dim=1) # Stacks tensors along a new dimension
print(stacked_tensor)
張量變換
tensor.view(shape)
: 返回給定形狀的張量視圖
返回一個具有指定形狀的新張量,原始張量的形狀必須與新形狀兼容。
import torchtensor = torch.tensor([[1, 2], [3, 4]])
reshaped_tensor = tensor.view(1, 4) # Reshapes the tensor to a 1x4 tensor
print(reshaped_tensor)
tensor.reshape(shape)
: 改變張量的形狀
返回一個具有指定形狀的新張量,原始張量的元素數量必須與新形狀一致。
import torchtensor = torch.tensor([[1, 2], [3, 4]])
reshaped_tensor = tensor.reshape(1, 4) # Reshapes the tensor to a 1x4 tensor
print(reshaped_tensor)
tensor.transpose(dim0, dim1)
: 交換兩個維度
交換張量中兩個維度的位置。
import torchtensor = torch.tensor([[1, 2], [3, 4]])
transposed_tensor = tensor.transpose(0, 1) # Swaps the first and second dimensions
print(transposed_tensor)
tensor.permute(*dims)
: 按照指定順序排列張量的維度
按照給定順序重新排列張量的維度。
import torchtensor = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
permuted_tensor = tensor.permute(1, 0, 2) # Permutes the dimensions to (1, 0, 2)
print(permuted_tensor)
tensor.squeeze()
: 刪除所有長度為1的維度
刪除張量中所有長度為1的維度。
import torchtensor = torch.tensor([[[1, 2], [3, 4]]])
squeezed_tensor = tensor.squeeze() # Removes the single-dimensional entries
print(squeezed_tensor)
tensor.unsqueeze(dim)
: 在指定位置增加一個維度
在指定位置增加一個長度為1的新維度。
import torchtensor = torch.tensor([[1, 2], [3, 4]])
unsqueezed_tensor = tensor.unsqueeze(0) # Adds a dimension at index 0
print(unsqueezed_tensor)
數學運算
torch.add(x, y)
: 加法
對兩個張量進行逐元素加法運算。
import torchx = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 6])
result = torch.add(x, y)
print(result)
torch.sub(x, y)
: 減法
對兩個張量進行逐元素減法運算。
import torchx = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 6])
result = torch.sub(x, y)
print(result)
torch.mul(x, y)
: 乘法
對兩個張量進行逐元素乘法運算。
import torchx = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 6])
result = torch.mul(x, y)
print(result)
torch.div(x, y)
: 除法
對兩個張量進行逐元素除法運算。
import torchx = torch.tensor([1.0, 2.0, 3.0])
y = torch.tensor([4.0, 5.0, 6.0])
result = torch.div(x, y)
print(result)
torch.matmul(x, y)
: 矩陣乘法
計算兩個張量的矩陣乘法。
import torchx = torch.tensor([[1, 2], [3, 4]])
y = torch.tensor([[5, 6], [7, 8]])
result = torch.matmul(x, y)
print(result)
torch.pow(base, exponent)
: 冪運算
計算張量的冪。
import torchbase = torch.tensor([1, 2, 3])
exponent = 2
result = torch.pow(base, exponent)
print(result)
torch.exp(tensor)
: 指數運算
計算張量中所有元素的指數。
import torchtensor = torch.tensor([1.0, 2.0, 3.0])
result = torch.exp(tensor)
print(result)
torch.sqrt(tensor)
: 開方運算
計算張量中所有元素的平方根。
import torchtensor = torch.tensor([1.0, 4.0, 9.0])
result = torch.sqrt(tensor)
print(result)
匯總統計
torch.sum(input)
: 求和
計算張量中所有元素的和。
import torchtensor = torch.tensor([[1, 2], [3, 4]])
result = torch.sum(tensor)
print(result)
torch.mean(input)
: 求平均值
計算張量中所有元素的平均值。
import torchtensor = torch.tensor([[1, 2], [3, 4]], dtype=torch.float)
result = torch.mean(tensor)
print(result)
torch.max(input)
: 求最大值
找出張量中所有元素的最大值。
import torchtensor = torch.tensor([[1, 2], [3, 4]])
result = torch.max(tensor)
print(result)
torch.min(input)
: 求最小值
找出張量中所有元素的最小值。
import torchtensor = torch.tensor([[1, 2], [3, 4]])
result = torch.min(tensor)
print(result)
torch.std(input)
: 求標準差
計算張量中所有元素的標準差。
import torchtensor = torch.tensor([[1, 2], [3, 4]], dtype=torch.float)
result = torch.std(tensor)
print(result)
torch.var(input)
: 求方差
計算張量中所有元素的方差。
import torchtensor = torch.tensor([[1, 2], [3, 4]], dtype=torch.float)
result = torch.var(tensor)
print(result)
梯度相關
tensor.requires_grad_()
: 標記張量需要計算梯度
標記張量以便在反向傳播中計算梯度。
import torchtensor = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
tensor.grad
: 獲取張量的梯度
獲取張量的梯度值,前提是該張量需要計算梯度。
import torchtensor = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
tensor.sum().backward()
print(tensor.grad)
tensor.backward()
: 計算梯度
計算張量的梯度值,前提是該張量需要計算梯度。
import torchtensor = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
tensor.sum().backward()
數據管理
tensor.to(device)
: 將張量移動到指定的設備上(如GPU)
將張量移動到指定的設備上,例如GPU。
import torchtensor = torch.tensor([1, 2, 3])
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
tensor = tensor.to(device)
print(tensor.device)
torch.save(obj, f)
: 保存對象到文件
將對象保存到文件中。
import torchtensor = torch.tensor([1, 2, 3])
torch.save(tensor, 'tensor.pt') # Save tensor to file
torch.load(f)
: 從文件加載對象
從文件中加載對象。
import torchtensor = torch.load('tensor.pt') # Load tensor from file
print(tensor)
其他操作基礎操作
torch.nn.functional.relu(input)
: 應用ReLU激活函數
對輸入張量應用ReLU激活函數。
import torch.nn.functional as F
import torchinput = torch.tensor([-1, 0, 1], dtype=torch.float)
output = F.relu(input)
print(output)
torch.nn.Conv2d(in_channels, out_channels, kernel_size)
: 創建二維卷積層
創建一個二維卷積層。
import torch.nn as nn
import torchconv_layer = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3)
input = torch.randn(1, 3, 64, 64)
output = conv_layer(input)
print(output.shape)
torch.optim.SGD(params, lr)
: 使用SGD優化器
使用隨機梯度下降(SGD)優化器來優化模型參數。
import torch.optim as optim
import torchparams = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
optimizer = optim.SGD([params], lr=0.1)
自動求導(Autograd)
自動求導是 PyTorch 中一個重要的功能,能夠自動計算張量的梯度。
import torchx = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = x ** 2
y.backward(torch.tensor([1.0, 1.0, 1.0])) # 計算 y 對 x 的梯度
print(x.grad) # 輸出梯度值
神經網絡模塊(nn.Module)
使用 nn.Module 類來定義神經網絡模型,可以方便地管理和組織模型的結構。
import torch.nn as nn
import torchclass Net(nn.Module):def __init__(self):super(Net, self).__init__()self.fc = nn.Linear(10, 1)def forward(self, x):return self.fc(x)model = Net()
數據加載與處理(Data Loading and Processing)
使用 DataLoader 和 Dataset 類來加載和處理數據集。
import torch
from torch.utils.data import DataLoader, Datasetclass CustomDataset(Dataset):def __init__(self, data):self.data = datadef __len__(self):return len(self.data)def __getitem__(self, index):return self.data[index]data = [1, 2, 3, 4, 5]
dataset = CustomDataset(data)
dataloader = DataLoader(dataset, batch_size=2, shuffle=True)
損失函數(Loss Functions)
使用損失函數來衡量模型輸出與真實標簽之間的差異。
import torch.nn as nn
import torchcriterion = nn.CrossEntropyLoss()
output = torch.tensor([[0.1, 0.2, 0.7], [0.3, 0.6, 0.1]])
target = torch.tensor([2, 1])
loss = criterion(output, target)
print(loss)
優化器(Optimizers)
使用優化器來更新模型的參數,常見的優化器包括 SGD、Adam 等。
import torch.optim as optim
import torchmodel = Net()
optimizer = optim.SGD(model.parameters(), lr=0.01)
模型訓練與驗證(Model Training and Validation)
使用 PyTorch 來訓練和驗證神經網絡模型。
import torch.nn as nn
import torch.optim as optim
import torchmodel = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)for epoch in range(10):# 訓練模型for data in dataloader:inputs, labels = dataoptimizer.zero_grad()outputs = model(inputs)loss = criterion(outputs, labels)loss.backward()optimizer.step()# 驗證模型with torch.no_grad():# 計算準確率等指標
模型保存與加載(Model Saving and Loading)
在訓練完成后,將模型保存到文件中以便后續使用。
import torchtorch.save(model.state_dict(), 'model.pth') # 保存模型參數
GPU 加速(GPU Acceleration)
利用 GPU 加速計算可以顯著提高模型訓練的速度。
import torchdevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = Net().to(device) # 將模型移動到 GPU 上
模型調優(Model Tuning)
使用交叉驗證和超參數搜索來調優模型,以提高模型性能。
from sklearn.model_selection import GridSearchCV
import torchparameters = {'lr': [0.01, 0.1, 1.0]}
model = Net()
optimizer = optim.SGD(model.parameters(), lr=0.01)
grid_search = GridSearchCV(optimizer, parameters)
遷移學習(Transfer Learning)
遷移學習是一種常見的訓練技巧,可以使用預訓練的模型來加速模型的訓練過程。
import torchvision.models as models
import torchpretrained_model = models.resnet18(pretrained=True)
# 將預訓練模型的參數凍結
for param in pretrained_model.parameters():param.requires_grad = False
最后
掌握以上19種操作方法可以讓你更好地使用 PyTorch 進行深度學習任務。這些操作方法涵蓋了張量的創建、變換、數學運算、梯度計算、模型構建、數據處理等方面,是使用 PyTorch 進行深度學習的基礎操作。
用通俗易懂的方式講解系列
-
重磅來襲!《大模型面試寶典》(2024版) 發布!
-
重磅來襲!《大模型實戰寶典》(2024版) 發布!
-
用通俗易懂的方式講解:不用再找了,這是大模型最全的面試題庫
-
用通俗易懂的方式講解:這是我見過的最適合大模型小白的 PyTorch 中文課程
-
用通俗易懂的方式講解:一文講透最熱的大模型開發框架 LangChain
-
用通俗易懂的方式講解:基于 LangChain + ChatGLM搭建知識本地庫
-
用通俗易懂的方式講解:基于大模型的知識問答系統全面總結
-
用通俗易懂的方式講解:ChatGLM3 基礎模型多輪對話微調
-
用通俗易懂的方式講解:最火的大模型訓練框架 DeepSpeed 詳解來了
-
用通俗易懂的方式講解:這應該是最全的大模型訓練與微調關鍵技術梳理
-
用通俗易懂的方式講解:Stable Diffusion 微調及推理優化實踐指南
-
用通俗易懂的方式講解:大模型訓練過程概述
-
用通俗易懂的方式講解:專補大模型短板的RAG
-
用通俗易懂的方式講解:大模型LLM Agent在 Text2SQL 應用上的實踐
-
用通俗易懂的方式講解:大模型 LLM RAG在 Text2SQL 上的應用實踐
-
用通俗易懂的方式講解:大模型微調方法總結
-
用通俗易懂的方式講解:漲知識了,這篇大模型 LangChain 框架與使用示例太棒了
-
用通俗易懂的方式講解:掌握大模型這些優化技術,優雅地進行大模型的訓練和推理!
-
用通俗易懂的方式講解:九大最熱門的開源大模型 Agent 框架來了