PyTorch基础(part1)
生活随笔
收集整理的這篇文章主要介紹了
PyTorch基础(part1)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
學習筆記,僅供參考,有錯必究
文章目錄
- PyTorch基礎
- PyTorch介紹
- PyTorch CPU版安裝
- 導包
- 構造tensor
- tensor的基本屬性
- 生成數據
PyTorch基礎
PyTorch介紹
- Torch
Torch是一個開源的機器學習的框架,早在2002年就發布了Torch的初版,Torch的編程語言為C和Lua。如今的Torch7依舊是熱門的深度學習框架之一。
- PyTorch
PyTorch是在2017年1月由Facebook推出的。它是經典機器學習庫Torch框架的一個端口,主要編程語言為python.
- PyTorch的快速發展
PyTorch CPU版安裝
首先進入PyTorch官網;
按照自己的情況,選擇想要安裝的PyTorch版本,如下圖所示:
將上圖中,被紅色長方形 框住的代碼復制到cmd中,并進行如下修改:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple torch torchvision torchaudio修改完成后,回車進行安裝:
導包
# 導入常用的包 import torch import numpy as np
構造tensor
a = torch.tensor([1, 2, 3], dtype = int) print(a) tensor([1, 2, 3]) b = torch.tensor([4, 5, 6], dtype = float) print(b) tensor([4., 5., 6.], dtype=torch.float64) t1 = torch.tensor([[1, 2, 3],[4, 5, 6]]) print(t1) tensor([[1, 2, 3],[4, 5, 6]])
tensor的基本屬性
# 查看數據類型 a.dtype b.dtype torch.int64torch.float64 # 查看數據維度 a.ndim t1.ndim 12 # 查看數據的形狀 a.shape t1.shape t1.size() torch.Size([3])torch.Size([2, 3])torch.Size([2, 3])
生成數據
# 生成全1張量 torch.ones(2, 3) tensor([[1., 1., 1.],[1., 1., 1.]]) # 生成全0張量 torch.zeros(3, 3) tensor([[0., 0., 0.],[0., 0., 0.],[0., 0., 0.]]) # 生成包含[0, 1)隨機數的張量 torch.rand(3, 4) tensor([[0.3797, 0.5408, 0.5703, 0.9994],[0.3843, 0.6358, 0.0099, 0.0339],[0.8164, 0.5019, 0.7004, 0.4033]]) # 生產包含隨機整數的張量 torch.randint(0, 5, (2, 3)) tensor([[3, 3, 3],[3, 1, 4]]) # 生成包含 服從正態分布的隨機數的張量 torch.randn(3, 4) tensor([[ 0.5376, -1.8396, 0.1551, -1.1469],[ 0.3814, 0.0709, 1.2827, 0.3375],[-0.6563, 0.9816, -0.7495, -1.4707]]) # 生成和某個張量形狀一樣的隨機數張量 a = torch.tensor([[1, 2],[4, 5],[6, 7]]) b = torch.rand_like(a, dtype = float) b print(b.shape) tensor([[0.8122, 0.4363],[0.3702, 0.4267],[0.8426, 0.4262]], dtype=torch.float64)torch.Size([3, 2]) # 使用view改變張量的形狀,類似于numpy中的reshape c = b.view(6) c tensor([0.8122, 0.4363, 0.3702, 0.4267, 0.8426, 0.4262], dtype=torch.float64) d = b.view(2, 3) d tensor([[0.8122, 0.4363, 0.3702],[0.4267, 0.8426, 0.4262]], dtype=torch.float64) e = d.reshape(6) e tensor([0.8122, 0.4363, 0.3702, 0.4267, 0.8426, 0.4262], dtype=torch.float64) # 獲取張量中的某個值,并轉換為python中的標準數值 e[0] e[0].item() tensor(0.8122, dtype=torch.float64)0.8122101766213651 # 將tensor變成numpy.array f = np.array(d) f array([[ 0.81221018, 0.43634955, 0.37021041],[ 0.4267468 , 0.84262264, 0.4261592 ]]) # 將numpy.array變成tensor arr = np.array([[1, 2, 3]]) tens = torch.tensor(arr) tens tensor([[1, 2, 3]], dtype=torch.int32) 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的PyTorch基础(part1)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Matlab中 pdist 函数详解
- 下一篇: 李瑞峰:长城Hi4等价四驱平替两驱 全民