pytorch學習筆記(一)

2021-10-20 01:36:17 字數 3288 閱讀 2847

pytprch最基本的操作物件是tensor(張量),它表示乙個多維矩陣,類似於numpy的ndaarrays,張量可以在gpu上做高速計算

使用步驟:

構造乙個初始化矩陣:torch.rand

全0矩陣:torch.zeros

全1矩陣:torch.ones

pytorch基本資料型別

inttensor of size()------------>對應python中int

floattensor of size()------------>對應python中int

inttensor of size[d1,d2====]------------>對應python中int array

floattensor of size()------------>對應python中float array

import torch

a=torch.randn(2,

3)# 正態分佈

b=torch.rand(2,

3)# 生成均勻分布的隨機數

c=torch.zeros(2,

3)d=torch.ones(2,

2,3)

print

(a.size(0)

)# 可以指定維度

print

(a.shape)

print

(a)print

(b)print

(c)print

(d)print

(a.type()

)# torch.floattensor

print

(isinstance

(a,torch.floattensor)

)e = torch.tensor([6

,2],dtype=torch.float32)

print

(e)e.

type

(torch.int32)

# 型別轉換

print

(e)

tensor方法:

torch.full 填充

torch.empty 為空

torch.rand 隨機數

torch.randn 均值為0,方差為1

torch.randint隨機整數

torch.add 加法

torch.tensor 建立

torch.torch.from_numpy(numpy矩陣):numpy轉換為tensor

torch.reshape 改變形狀

torch.numel 統計數目

torch.view 檢視

torch.arrange 範圍

torch.linspace 間隔

torch.eye 對角線

torch.cat 連線

torch.index_select 根據索引選擇

torch.narrow 縮小

torch.t 轉置

torch.take 根據索引獲取元素

torch.transpose 轉置

torch.split分割

import torch

import numpy as np

# tensor方法

t1 = torch.rand(1,

2)a = torch.is_tensor(t2)

print

(a)# 建立乙個全0 tensor

t3 = torch.zeros(3,

2)num = torch.numel(t3)

# 建立對角線為1的tensor

t4 = torch.eye(3,

3)print

(t4)

# 將numpy轉化為tensor

n = np.array([1

,2,3

,4])

t5 = torch.from_numpy(n)

print

(int

)# 切分

t6 = torch.linspace(1,

10,steps=5)

# 從1開始到10,切分成5份

print

(t6)

# 建立均勻分布,值在0到1之間

t7 = torch.rand(10)

print

(t7)

# 建立正態分佈

t8 = torch.randn(10)

print

(t8)

# 選擇隨機數 從1到10

t9 = torch.randperm(10)

# 生成乙個固定區間的數

t10 = torch.arange(1,

10,3)

# 從1到10,步長為3

# 獲取行或列的最小值和最大值索引

x = torch.randint(1,

99,(3

,3))

t11 = torch.argmin(x,dim=0)

t12 = torch.argmax(x,dim=0)

# 連線

y = torch.randint(1,

10,(2

,3))

t13 = torch.cat(y,y,dim=1)

# 1是橫軸

# 切塊

z= torch.randint(1,

10,(3

,3))

torch.chunk(a,2,

0)# 根據索引選擇

m = torch.randn(4,

4)index= torch.tensor([0

,2])

# 輸出0行和第2行

t15 = torch.index_select(m,

0,index)

# 分割

n = torch.tensor([1

,2,3

,4,5

,6,7

])t16 = torch.split(n,3)

# 將n切分成3份

# 轉置

p = torch.tensor([[

1,3]

[2,4

]])p.transpose(1,

0)p.t(

)# tensor運算

t17 = torch.tensor([[

1,2]

[3,4

]])torch.add(t17,1)

# 所有元素加1

torch.mul(t17,2)

# 所有元素乘2

深度學習 Pytorch學習筆記(一)

pytorch中需要自己定義網路模型,該模型需要封裝到乙個自定義的類中,該類只是乙個子類,其繼承的父類為torch.nn.module,可見如下樹形結構圖 module實際又是繼承了object類,關於為什麼要繼承object類有興趣的可以看這篇部落格mro演算法 也就是說,自定義的模型除了要有 i...

Pytorch 學習筆記

本渣的pytorch 逐步學習鞏固經歷,希望各位大佬指正,寫這個部落格也為了鞏固下記憶。a a b c 表示從 a 取到 b 步長為 c c 2 則表示每2個數取1個 若為a 1 1 1 即表示從倒數最後乙個到正數第 1 個 最後乙個 1 表示倒著取 如下 陣列的第乙個為 0 啊,第 0 個!彆扭 ...

Pytorch學習筆記

資料集 penn fudan資料集 在學習pytorch官網教程時,作者對penn fudan資料集進行了定義,並且在自定義的資料集上實現了對r cnn模型的微調。此篇筆記簡單總結一下pytorch如何實現定義自己的資料集 資料集必須繼承torch.utils.data.dataset類,並且實現 ...