深度學習-Pytorch模型運算的基本數據類型
用pytorch構建模型,并訓練模型,得到一個優化的模型,那么模型構造的數據類型怎樣的?
數據分析
數據分析-Pandas如何轉換產生新列
數據分析-Pandas如何統計數據概況
數據分析-Pandas如何輕松處理時間序列數據
數據分析-Pandas如何選擇數據子集
數據分析-Pandas如何重塑數據表-CSDN博客
經典算法
經典算法-遺傳算法的python實現
經典算法-模擬退火算法的python實現
經典算法-粒子群算法的python實現-CSDN博客
pytorch中常常遇到的,最基本的數據類型就是tensors。
Tensors
Tensors是一種特殊的數據結構,與數組和矩陣非常相似。 在 PyTorch 中,我們使用張量對模型的輸入和輸出以及模型的參數進行處理。
Tensors也類似于 NumPy 的 ndarrays,不同之處在于
- Tensors還可以加載到 GPU 或其他硬件加速器上運行。事實上,Tensors和 NumPy 數組通常可以共享相同的底層內存,無需復制數據。
- 另外,Tensors還針對自動微分進行了優化(將在稍后的 Autograd 部分看到更多相關內容)。
如果您熟悉 ndarrays,那么您將可以再熟悉下 Tensor API 。如果沒有,請繼續!
import torch
import numpy as np
初始化Tensors
Tensors可以通過多種方式初始化。請看以下示例:
從數據生成
Tensors可以直接從數據創建。數據類型是自動生成的。
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
從 NumPy 數組生成
Tensors可以從 NumPy 數組創建(反之亦然 - 參見 Bridge with NumPy)。
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
從另一個Tensor
新tensor將保留參數tensor的屬性(形狀、數據類型),除非顯式覆蓋。
x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")
Ones Tensor:tensor([[1, 1],[1, 1]])Random Tensor:tensor([[0.8823, 0.9150],[0.3829, 0.9593]])
用隨機值或常量值:
shape
是張量維數的元組。在下面的函數中,它確定輸出張量的維數。
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
Random Tensor:tensor([[0.3904, 0.6009, 0.2566],[0.7936, 0.9408, 0.1332]])Ones Tensor:tensor([[1., 1., 1.],[1., 1., 1.]])Zeros Tensor:tensor([[0., 0., 0.],[0., 0., 0.]])
Tensors的屬性
Tensors屬性描述它們的形狀、數據類型和存儲它們的設備。
tensor = torch.rand(3,4)print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
Tensors的操作
超過 100 種tensors運算,包括算術、線性代數、矩陣操作(轉置、 索引、切片)、采樣等。
默認情況下,Tensors是在 CPU 上創建的,在GPU運行需要顯式地使用 .to 函數,將tensor移動到 GPU(當然首先是檢查 GPU 可用性之后)。請記住,跨設備復制大量Tensors ,在時間和內存方面可能很費的!
.to
# We move our tensor to the GPU if available
if torch.cuda.is_available():tensor = tensor.to("cuda")
tensors中的一些操作,和NumPy API類似,比如索引和切片
索引和切片:
tensor = torch.ones(4, 4)print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0
print(tensor)
First row: tensor([1., 1., 1., 1.])
First column: tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],[1., 0., 1., 1.],[1., 0., 1., 1.],[1., 0., 1., 1.]])
連接Tensors
可以使用按給定維度,連接一系列張量。 參見 torch.stack, 另一個張量連接運算符,它與 略有不同。torch.cat
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])
算術運算
# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
# ``tensor.T`` returns the transpose of a tensor
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)y3 = torch.rand_like(y1)
torch.matmul(tensor, tensor.T, out=y3)# This computes the element-wise product. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
tensor([[1., 0., 1., 1.],[1., 0., 1., 1.],[1., 0., 1., 1.],[1., 0., 1., 1.]])
單元素Tensor
如果你有一個單元素張量,例如通過聚合所有 一個張量的值變成一個值,可以將其轉換為Python 數值使用:item()
agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))
12.0 <class 'float'>
in place操作
將結果存儲到操作數中的操作,稱為in place操作。它們用后綴表示。 例如:,,將更改。_x.copy_(y)
x.t_() x
print(f"{tensor} \n")
tensor.add_(5)
print(tensor)
tensor([[1., 0., 1., 1.],[1., 0., 1., 1.],[1., 0., 1., 1.],[1., 0., 1., 1.]])tensor([[6., 5., 6., 6.],[6., 5., 6., 6.],[6., 5., 6., 6.],[6., 5., 6., 6.]])
注意
in place運算可以節省一些內存,但在計算導數時可能會出現問題,因為會立即丟失運算的歷史記錄。因此,不鼓勵使用它們。
覺得有用 收藏 收藏 收藏
點個贊 點個贊 點個贊
End
GPT專欄文章:
GPT實戰系列-ChatGLM3本地部署CUDA11+1080Ti+顯卡24G實戰方案
GPT實戰系列-LangChain + ChatGLM3構建天氣查詢助手
大模型查詢工具助手之股票免費查詢接口
GPT實戰系列-簡單聊聊LangChain
GPT實戰系列-大模型為我所用之借用ChatGLM3構建查詢助手
GPT實戰系列-P-Tuning本地化訓練ChatGLM2等LLM模型,到底做了什么?(二)
GPT實戰系列-P-Tuning本地化訓練ChatGLM2等LLM模型,到底做了什么?(一)
GPT實戰系列-ChatGLM2模型的微調訓練參數解讀
GPT實戰系列-如何用自己數據微調ChatGLM2模型訓練
GPT實戰系列-ChatGLM2部署Ubuntu+Cuda11+顯存24G實戰方案
GPT實戰系列-Baichuan2本地化部署實戰方案
GPT實戰系列-Baichuan2等大模型的計算精度與量化
GPT實戰系列-GPT訓練的Pretraining,SFT,Reward Modeling,RLHF
GPT實戰系列-探究GPT等大模型的文本生成-CSDN博客