1 Pytorch簡介
Pytorch是Facebook人工智能研究院基于Torch開發(fā)的一個開源的Python機(jī)器學(xué)習(xí)庫忽你,它提供了兩項(xiàng)強(qiáng)大的功能:1、強(qiáng)大的GPU加速的張量計(jì)算(NumPy)颖系。2、自動求導(dǎo)系統(tǒng)的深度神經(jīng)網(wǎng)絡(luò)辩越。
Tensorflow是純符號式編程嘁扼,運(yùn)行效率高,但實(shí)現(xiàn)復(fù)雜黔攒;Pytorch是命令式編程偷拔,實(shí)現(xiàn)方便,但運(yùn)行效率低亏钩。
[TOC]
2 Pytorch總覽
3 Pytorch詳解
3.1 torch
- 張量
函數(shù) | 函數(shù)功能 |
---|---|
torch.is_tensor(obj) | 判斷obj是否為tensor數(shù)據(jù)類型 |
torch.is_storage(obj) | 判斷obj是否為storage類型 |
torch.set_default_tensor_type(type) | 設(shè)置默認(rèn)的tensor數(shù)據(jù)類型 |
torch.set_printoptions(precision=None,threshold=None,linewidth=None,profile=None) | 設(shè)置打印格式 |
- 創(chuàng)建操作
函數(shù) | 函數(shù)功能 |
---|---|
torch.eye(n,m=None,out=None) | 創(chuàng)建主對角矩陣 |
torch.from_numpy(ndarray) | 將numpy.ndarray轉(zhuǎn)換為Tensor |
torch.linspace(start,end,steps=100,out=None) | 創(chuàng)建含steps個元素的一維張量 |
torch.logspace(start,end,steps=100,out=None) | 創(chuàng)建位于10start-10end內(nèi)的一維張量 |
torch.zeros(*sizes,out=None) | 創(chuàng)建全0張量 |
torch.ones(*sizes,out=None) | 創(chuàng)建全1張量 |
torch.rand(*sizes,out=None) | 創(chuàng)建位于0-1的均勻分布的張量 |
torch.randn(*sizes,out=None) | 從標(biāo)準(zhǔn)正態(tài)分布中抽取數(shù)據(jù)創(chuàng)建張量 |
torch.arange(start,end,step=1,out=None) | 創(chuàng)建一維張量 |
- 索引莲绰、切片、連接姑丑、換位
函數(shù) | 函數(shù)功能 |
---|---|
torch.cat(inputs,dimension=0) | 在給定維度上對inputs進(jìn)行拼接 |
torch.chunk(tensor,chunks,dim=0) | 在給定維度上對tensor進(jìn)行分塊 |
torch.split(tensor,split_size,dim=0) | 在給定維度上對tensor進(jìn)行分塊 |
torch.squeeze(input,dim=None,out=None) | 去除輸入張量形狀中的1并返回 |
torch.stack(sequence,dim=0) | 沿著新維度對輸入張量序列進(jìn)行拼接 |
torch.t(input,out=None) | 對input矩陣進(jìn)行裝置 |
torch.transpose(input,dim0,dim1,out=None) | 交換input的dim0與dim1 |
torch.unbind(tensor,dim=0) | 移除指定維度蛤签,并返回一個包含了沿著指定維度切片后的各個切片 |
torch.sequence(input,dim,out=None) | 返回一個新張量,對輸入的位置插入維度1 |
- 隨機(jī)抽樣
函數(shù) | 函數(shù)功能 |
---|---|
torch.normal(means,std,out=None) | 返回一個張量栅哀,包含從給定參數(shù)means,std離散分布中抽取隨機(jī)數(shù) |
- 序列化
函數(shù) | 函數(shù)功能 |
---|---|
torch.save(obj,f,pickle_moudle=<module 'pickle' from '/home/pickle.py'>,pickle_protoco1=2) | 保存一個對象到一個硬盤文件上 |
torch.load(f,map_location=None,pickle_module=<module 'pickle' from '/home/pickle.py'>) | 從磁盤文件中讀取一個通過torch.save()保存的對象 |
- 并行化
函數(shù) | 函數(shù)功能 |
---|---|
torch.get_num_threads() | 獲取用于并行化CPU操作的OpenMP線程數(shù) |
torch.set_num_threads(int) | 設(shè)定用于并行化CPU操作的OpenMP線程數(shù) |
- 數(shù)學(xué)操作
函數(shù) | 函數(shù)功能 |
---|---|
torch.div(input,value,out=None) | 將input逐元素除以標(biāo)量value |
torch.exp(tensor,out=None) | 計(jì)算input每個元素的指數(shù) |
torch.abs(input,out=None) | 計(jì)算input每個元素的絕對值 |
torch.sin(input,out=None) | 計(jì)算每個元素的正弦值 |
torch.cos(input,out=None) | 計(jì)算每個元素的余弦值 |
torch.atan(input,out=None) | 計(jì)算input每個元素的反正切 |
torch.asin(input,out=None) | 計(jì)算每個元素的反正弦 |
torch.acos(input,out=None) | 計(jì)算每個元素的反余弦 |
torch.cosh(input,out=None) | 計(jì)算input每個元素的雙曲余弦 |
torch.add(input,value,out=None) | 對input逐元素加上標(biāo)量value |
torch.addcdiv(tensor,value,tensor1,tensor2,out=None) | 用tensor2對tensor1逐元素相除震肮,乘以value并加到tensor |
torch.addcmul(tensor,value,tensor1,tensor2,out=None) | 用tensor2對tensor1逐元素相乘,乘以value留拾,然后加到tensor |
torch.floor(input,out=None) | 對input每個元素向下取整 |
torch.ceil(input,out=None) | 對input每個元素向上取整 |
torch.clamp(input,min,max,out=None) | 將input每個元素夾緊至【min,max】內(nèi) |
torch.fmod(input,divisor,out=None) | 計(jì)算input每個元素的除法余數(shù) |
torch.frac(tensor,out=None) | 返回每個元素的分?jǐn)?shù)部分 |
torch.log(input,out=None) | 計(jì)算log的自然對數(shù) |
torch.mul(input,value,out=None) | 將input逐元素乘以標(biāo)量value |
torch.net(input,out=None) | 將input逐元素取負(fù) |
torch.pow(input,exponent,out=None) | 將input逐元素求exponent次冪 |
torch.reciprocal(input,out=None) | 計(jì)算input每個元素的倒數(shù) |
torch.remainder(input,divisor,out=None) | 計(jì)算input每個元素的除法余數(shù) |
torch.round(input,out=None) | 計(jì)算input每個元素四舍五入后的值 |
torch.rsqrt(input,out=None) | 計(jì)算input每個元素的平方根倒數(shù) |
torch.sigmoid(input,out=None) | 計(jì)算input每個元素的sigmoid值 |
torch.sign(input,out=None) | 返回input每個元素的符號 |
torch.sqrt(input,out=None) | 計(jì)算input每個元素的平方根 |
torch.trunc(input,out=None) | 將input每個元素的小數(shù)部分截?cái)?/td> |
torch.cumprod(input,dim,out=None) | 沿著dim維度計(jì)算input累積積 |
torch.cumsum(input,dim,out=None) | 沿dim維度計(jì)算input累計(jì)和 |
torch.dist(input,other,p=2,out=None) | 返回(input-other)的p范數(shù) |
torch.mean(input) | 計(jì)算input所有元素的均值 |
torch.mean(input,dim,out=None) | 計(jì)算input指定維度所有元素的均值 |
torch.median(input,dim=-1,values=None,indices=None) | 返回input給定維度所有元素的中位數(shù)戳晌,同時返回一個包含中位數(shù)的索引的LongTensor |
torch.mode(input,dim,values=None,indices=None) | 返回給定維度所有元素的眾數(shù),同時返回一個包含眾數(shù)索引的LongTensor |
torch.norm(input,p痴柔,dim,out=None) | 返回input的p范數(shù) |
torch.prod(input,dim) | 返回input所有元素的積 |
torch.std(input,dim) | 返回input所有元素的標(biāo)準(zhǔn)差 |
torch.sum(input,dim) | 返回input所有元素的和 |
torch.var(input,dim) | 返回input在給定維度上每個元素的方差 |
- 比較操作
函數(shù) | 函數(shù)功能 |
---|---|
torch.eq(input,other,out=None) | 比較input每個元素是否與other相等 |
torch.equal(tensor1,tensor2) | 比較tensor1與tensor2是否完全相等 |
torch.ge(input,other,out=None) | 逐元素比較input和other |
torch.gt(input,other,out=None) | 逐元素比較input和other |
torch.kthvalue(input,k,dim=None,out=None) | 取輸入張量input指定維度上第K個最小值 |
torch.le(input,other,out=None) | 逐元素比較input和other |
torch.lt(input,other,out=None) | 逐元素比較input和other |
torch.max(input,dim) | 返回input給定維度上的最大值 |
torch.min(input,dim) | 返回input給定維度上的最小值 |
torch.ne(input,other) | 逐元素比較input和other |
torch.sort(input,dim=None,descending=False,out=None) | 對輸入張量input沿著指定維度按升序排序 |
torch.topk(input,k,dim=None,largest=True,out=None) | 沿指定維度返回input中K個最大值 |
- 其他操作
函數(shù) | 函數(shù)功能 |
---|---|
torch.cross(input,other,dim,out=None) | 沿著指定維度計(jì)算input與other的向量積 |
torch.dot(tensor1,tensor2) | 計(jì)算兩個張量的內(nèi)積 |
torch.eig(a,eigenvectors=False,out=None) | 計(jì)算方陣a的特征值和特征向量 |
torch.inverse(input,out=None) | 對方陣input取逆 |
torch.mm(mat1,mat2,out=None) | 計(jì)算mat1與mat2的乘積 |
torch.mv(mat,vec,out=None) | 計(jì)算矩陣與向量vec的乘積 |
torch.abs_(input) | torch.abs(input)的in-place運(yùn)算形式 |
3.2 torch.nn
- 參數(shù)設(shè)置
函數(shù) | 函數(shù)功能 |
---|---|
torch.nn.Parameter(data,requires_grad) | 將不可訓(xùn)練的data轉(zhuǎn)換為可訓(xùn)練的類型parameter沦偎,并將這個parameter綁定到module內(nèi) |
- torch.nn.Module基類
函數(shù) | 函數(shù)功能 |
---|---|
add_module(name,module) | 將一個child module添加到當(dāng)前module,可通過name屬性獲取module |
cuda(device_id=None) | 將所有模型參數(shù)復(fù)制到GPU |
cpu(device_id=None) | 將所有模型參數(shù)復(fù)制到CPU |
double() | 將parameters和buffers的數(shù)據(jù)類型轉(zhuǎn)換為double |
float() | 將parameters和buffers的數(shù)據(jù)類型轉(zhuǎn)換為float |
half() | 將parameters和buffers的數(shù)據(jù)類型轉(zhuǎn)換為half |
eval() | 將模型設(shè)置成evaluation模式 |
forward(*input) | 定義了每次執(zhí)行的計(jì)算步驟咳蔚,在所有子類中都需要重寫這個函數(shù) |
modules() | 返回一個包含當(dāng)前模型所有模塊的迭代器 |
named_modules() | 返回包含網(wǎng)絡(luò)中所有模塊的迭代器 |
children() | 返回當(dāng)前模型子模塊的迭代器 |
named_children() | 返回包含模型當(dāng)前模塊的迭代器 |
load_state_dict(state_dict) | 加載模型參數(shù)豪嚎,將state_dict中的parameters和buffers復(fù)制到module和他的后代中 |
parametes(memo=None) | 返回一個包含模型所有參數(shù)的迭代器 |
register_backward_hook(hook) | 在module上注冊一個backward hook,hook(module,grad_input,grad_output) |
register_forward_hook(hook) | 在module上注冊一個forward hook,hook(module,input,output) |
register_buffer(name,tensor) | 給module添加一個永久buffer |
register_parameter(name,param) | 向module添加parameter |
state_dict() | 返回一個保存著module所有狀態(tài)的字典 |
train(mode=True) | 將module設(shè)置為training mode |
zero_grad() | 將module中所有模型參數(shù)的梯度設(shè)置為0 |
torch.nn.Sequential(*args) | 一個時序容器谈火,modules會以它們傳入的順序被添加到容器中侈询,也可以傳入一個orderedDict |
torch.nn.ModuleList(modules=None) | 將submodules保存在一個list中 |
append(module) | 等價與list中的append |
extend(modules) | 等價于list中的extend |
torch.nn.ParameterList(parameters=None) | 將submodules保存在一個list中 |
- 卷積層
torch.nn.Conv1d(in_channels,out_channels,kernel_size,stride=1,padding=0,dilation=1,groups=1,bias=True)
torch.nn.Conv2d(in_channels,out_channels,kernel_size,stride=1,padding=0,dilation=1,groups=1,bias=True)
torch.nn.Conv3d(in_channels,out_channels,kernel_size,stride=1,padding=0,dilation=1,groups=1,bias=True)
參數(shù) | 參數(shù)意義 |
---|---|
in_channels | 輸入信號的信道 |
out_channels | 卷積產(chǎn)生的通道 |
kernel_size(int or tuple) | 卷積核尺寸 |
stride(int,tuple,optional) | 卷積步長 |
padding(int or tuple,optional) | 輸入的每一條邊補(bǔ)充0的層數(shù) |
dilation(int or tuple,optional) | 卷積核元素之間的間距 |
groups(int,optional) | 從輸入通道到輸出通道的阻塞連接數(shù) |
bias(bool,optional) | 是否添加偏置 |
torch.nn.ConvTranspose1d(in_channels,out_channels,kernel_size,stride=1,padding=0,outpu_padding=0,groups=1,bias=True)
torch.nn.ConvTranspose2d(in_channels,out_channels,kernel_size,stride=1,padding=0,outpu_padding=0,groups=1,bias=True)
torch.nn.ConvTranspose3d(in_channels,out_channels,kernel_size,stride=1,padding=0,outpu_padding=0,groups=1,bias=True)
參數(shù) | 參數(shù)意義 |
---|---|
in_channels(int) | 輸入信號的通道 |
out_channels(int) | 卷積產(chǎn)生的通道 |
kernel_size(int or tuple) | 卷積核尺寸 |
stride(int,tuple,optional) | 卷積步長 |
padding(int or tuple,optional) | 輸入的每一條邊補(bǔ)充0的層數(shù) |
output_padding(int or tuple,optional) | 輸出的每一條邊補(bǔ)充0的層數(shù) |
dilation(int or tuple,optional) | 卷積核元素之間的間距 |
groups(int,optional) | 從輸入通道到輸出通道的阻塞連接數(shù) |
bias(bool,optional) | 是否添加偏置 |
torch.nn.MaxPool1d(kernel_size,stride=None,padding=0,dilation=1,return_indices=False,ceil_mode=False)
torch.nn.MaxPool2d(kernel_size,stride=None,padding=0,dilation=1,return_indices=False,ceil_mode=False)
torch.nn.MaxPool3d(kernel_size,stride=None,padding=0,dilation=1,return_indices=None,ceil_mode=False)
參數(shù) | 參數(shù)意義 |
---|---|
kernel_size(int or tuple) | max pooling的窗口大小 |
stride(int,tuple,optional) | max pooling的窗口移動步長 |
padding(int or tuple,optional) | 輸入的每一條邊補(bǔ)充0的層數(shù) |
dilation(int or tuple,optional) | 控制窗口中元素的字符 |
return_indices | 為True時,會返回輸出最大值的序號 |
ceil_mode | 為True時糯耍,計(jì)算輸出信號的大小時使用向上取整 |
torch.nn.AvgPool1d(kernel_size,stride=None,padding=0,ceil_mode=False,count_include_pad=True)
torch.nn.AvgPool2d(kernel_size,stride=None,padding=0,ceil_mode=False,count_include_pad=True)
torch.nn.AvgPool3d(kernel_size,stride=None,padding=0,ceil_mode=False,count_include_pad=True)
參數(shù) | 參數(shù)意義 |
---|---|
kernel_size(int or tuple) | 池化層窗口大小 |
stride(int,tuple,optional) | 池化層窗口移動步長 |
padding(int or tuple,optional) | 輸入的每一條邊補(bǔ)充0的層數(shù) |
ceil_mode | 為True時扔字,計(jì)算輸出信號大小的時候囊嘉,會使用向上取整 |
count_include_pad | 為True時,計(jì)算平均池化時革为,將包括padding填充的0 |
torch.nn.AdaptiveMaxPool1d(output_size,return_indices=False)
torch.nn.AdaptiveMaxPool2d(output_size,return_indices=False)
torch.nn.AdaptiveMaxPool3d(output_size,return_indices=False)
參數(shù) | 參數(shù)意義 |
---|---|
output_size | 輸出信號的尺寸 |
return_indices | 為True時哗伯,會返回輸出的索引,對nn.MaxUnpool有用 |
torch.nn.AdaptiveAvgPool1d(output_size)
torch.nn.AdaptiveAvgPool2d(output_size)
參數(shù) | 參數(shù)意義 |
---|---|
output_size | 輸出信號的尺寸 |
torch.nn.MaxUnpool1d(kernel_size,stride=None,padding=0)
torch.nn.MaxUnpool2d(kernel_size,stride=None,padding=0)
torch.nn.MaxUnpool3d(kernel_size,stride=None,padding=0)
參數(shù) | 參數(shù)意義 |
---|---|
kernel_size(int or tuple) | maxunpooling的窗口的大小 |
stride(int,tuple,optional) | maxunpooling的窗口移動的步長 |
padding(int or tuple,optional) | 輸入的每一條邊補(bǔ)充0的層數(shù) |
torch.nn.FractionalMaxPool2d(kernel_size,output_size=None,output_ratio=None,return_indices=False,_random_samples=None)
參數(shù) | 參數(shù)意義 |
---|---|
kernel_size(int or tuple) | 池化層窗口大小 |
output_size | 輸出圖像的大小 |
output_ratio | 將輸入圖像大小的百分比指定為輸出圖像的大小 |
torch.nn.LPPool2d(norm_Type,kernel_size,stride=None,ceil_mode=False)
參數(shù) | 參數(shù)意義 |
---|---|
kernel_size(int or tuple) | 池化層窗口大小 |
- 非線性激活函數(shù)
函數(shù) | 函數(shù)功能 |
---|---|
torch.nn.ReLU() | |
torch.nn.ELU(alpha=1.0,inplace=Flase) | |
torch.nn.PReLU(num_parameters=1,init=0.25) | |
torch.nn.LeakyReLU(negative_slope=0.01,inplace=False) | |
torch.nn.Threshold(threshold,value,inplace=False) | |
torch.nn.Hardtanh(min_value=-1,max_value=1,inplace=False) | |
torch.nn.Sigmoid() | |
torch.nn.Tanh() | |
torch.nn.LogSigmoid() | |
torch.nn.Softplus(beta=1,threshold=20) | |
torch.nn.Softshrink(lambda=0.5) | |
torch.nn.Softsign() | |
torch.nn.Softmin() | |
torch.nn.Softmax() | |
torch.nn.LogSoftmax() |
- 正則化
torch.nn.BatchNorm1d(num_features,eps=1e-05,momentum=0.1,affine=True)
torch.nn.BatchNorm2d(num_features,eps=1e-05,momentum=0.1,affine=True)
torch.nn.BatchNorm3d(num_features,eps=1e-05,momentum=0.1,affine=True)
參數(shù) | 參數(shù)意義 |
---|---|
num_features | 來自期望輸入的特征數(shù)篷角,該期望輸入的大小為batch_size*num_features |
eps | 為保證數(shù)值穩(wěn)定性焊刹,給分布加上的值 |
momentum | 動態(tài)均值和動態(tài)方差所使用的動量 |
affine | 為True時,給該層添加學(xué)習(xí)的仿射變換參數(shù) |
- 循環(huán)層
torch.nn.RNN(input_size,hidden_size,num_layers=1,nonlinearity=tanh,bias=True,batch_first=False,dropout=0,bidirectional=False)
torch.nn.LSTM(input_size,hidden_size,num_layers=1,nonlinearity=tanh,bias=True,batch_first=False,dropout=0,bidirectional=False)
torch.nn.GRU(input_size,hidden_size,num_layers=1,nonlinearity=tanh,bias=True,batch_size=False,dropout=0,bidirectional=False)
參數(shù) | 參數(shù)意義 |
---|---|
input_size | 輸入特征的維度 |
hidden_size | 隱藏層神經(jīng)元個數(shù) |
num_layers | 網(wǎng)絡(luò)的層數(shù) |
nonlinearity | 激活函數(shù) |
bias | 是否使用偏置 |
batch_first | 輸入數(shù)據(jù)的形式 |
dropout | 是否使用dropout |
bidirectional | 是否使用雙向RNN |
torch.nn.RNNCell(input_size,hidden_size,bias=True,nonlinearity='tanh')
torch.nn.LSTMCell(input_size,hidden_size,bias=True,nonlinearity='tanh')
torch.GRUCell(input_size,hidden_size,bias=True,nonlinearity='tanh')
參數(shù) | 參數(shù)意義 |
---|---|
input_size | 輸入特征的維度 |
hidden_size | 隱藏層神經(jīng)元個數(shù) |
nonlinearity | 激活函數(shù) |
bias | 是否使用偏置 |
- 線性層
torch.nn.Linear(in_features,out_features,bias=True)
參數(shù) | 參數(shù)意義 |
---|---|
in_features | 每個輸入樣本的大小 |
out_features | 每個輸出樣本的大小 |
bias | 為False時恳蹲,不學(xué)習(xí)偏置 |
- 裁剪層
torch.nn.Dropout(p,inplace=False)
torch.nn.Dropout2d(p,inplace=False)
torch.nn.Dropout3d(p,inplace=False)
參數(shù) | 參數(shù)意義 |
---|---|
p | 將元素置0的概率 |
inplace | 為True時虐块,會原地執(zhí)行操作 |
- 稀疏層
torch.nn.Embedding(num_embeddings,embedding_dim,padding_idx=None,max_norm=None,norm_type=2,scale_grad_by_freq=False,sparse=False)
參數(shù) | 參數(shù)意義 |
---|---|
num_embeddings(int) | 嵌入字典的大小 |
embedding_dim(int) | 每個嵌入向量的大小 |
padding_idx(int,optional) | 如果提供的話,輸出遇到此下標(biāo)時用零填充 |
max_norm(float,optional) | 如果提供的話嘉蕾,會重新歸一化詞嵌入贺奠,使它們的范數(shù)小于提供的值 |
norm_type(float,optional) | 對于max_norm選項(xiàng)計(jì)算P范數(shù)時的p |
scale_grad_by_freq(bollean,optional) | 如果提供的話,會根據(jù)字典中單詞頻率縮放梯度 |
- 距離函數(shù)
torch.nn.PairwiseDistance(p=2,eps=1e-06)
參數(shù) | 參數(shù)意義 |
---|---|
p | 范數(shù)次數(shù) |
- 損失函數(shù)
torch.nn.L1Loss(size_average=True)|
torch.nn.MSELoss(size_average=True)
torch.nn.CrossEntropyLoss(weight=None,size_average=True)
torch.nn.NLLLoss(weight=None,size_average=True)
torch.nn.NLLLoss2d(weight=None,size_average=True)
torch.nn.KLDivLoss(weight=None,size_average=Ture)
torch.nn.BCELoss(weight=None,size_average=True)
torch.nn.MarginRankingLoss(margin=0,size_average=True)
torch.nn.HingeEmbeddingLoss(size_average=True)
torch.nn.MultiLabelMarginLoss(size_average=True)
torch.nn.SmoothL1Loss(size_average=True)
torch.nn.SoftMarginLoss(size_average=True)
torch.nn.MultiLabelSoftMarginLoss(weight=None,size_average=True)
torch.nn.CosineEmbeddingLoss(margin=0,size_average=True)
torch.nn.MultiMarginLoss(p=1,margin=1,weight=None,size_average=True)
- 視覺層
torch.nn.PixelShuffle(upscale_factor)
torch.nn.UpsamplingNearest2d(size=None,scale_factor=None)
torch.nn.UpsamplingBilnear2d(size=None,scale_factor=None)
- 多GPU層
torch.nn.DataParallel(module,device_ids=None,output_device=None,dim=0)
- 工具函數(shù)
torch.nn.utils.clip_grad_norm(parameters,max_norm,norm_type=2)
torch.nn.utils.rnn.PackedSequence(_cls,data,batch_sizes)
torch.nn.utils.rnn.pack_padded_sequence(input,lengths,batch_first=False)
torch.nn.utils.rnn.pad_packed_sequence(sequence,batch_first=False)
3.3 torch.nn.functional
包含與torch.nn相對的所有實(shí)現(xiàn)错忱;只不過torch.nn.functional是以函數(shù)形式封裝的這些實(shí)現(xiàn)儡率。
torch.nn.X | torch.nn.functional |
---|---|
類 | 函數(shù) |
結(jié)構(gòu)中包含所需要初始化的參數(shù) | 需要在函數(shù)外定義并初始化相應(yīng)參數(shù),并作為參數(shù)傳入 |
一般情況下放在init中實(shí)例化以清,并在forward中完成操作 | 一般在init中初始化相應(yīng)參數(shù)儿普,在forward中傳入 |
3.4 torch.nn.autograd
torch.autograd.backward(variables,grad_variables,retain_variables=False)
參數(shù) | 參數(shù)意義 |
---|---|
variables | 將計(jì)算導(dǎo)數(shù)的變量 |
grad_variables | 漸變寫入相應(yīng)變量的每個元素 |
retain_gradph | 若為False,則用于計(jì)算grad的圖形將被釋放 |
create_grahp | 若為True,則構(gòu)造導(dǎo)數(shù)的圖形 |
torch.autograd.grad(outputs,inputs,grad_outputs=Noneretain_graph=None,create_graph=None,only_inputs=True)
參數(shù) | 參數(shù)意義 |
---|---|
outputs | 差分函數(shù)的輸出 |
inputs | 輸入將返回梯度的積分 |
grad_outputs | 漸變wrd每個輸出 |
retain_graph | 若為False掷倔,則用于計(jì)算grad的圖形被釋放 |
create_graph | 若為True眉孩,則構(gòu)造導(dǎo)數(shù)的圖形 |
only_inputs | 若為True,則漸變wrt離開時圖形的一部分,但不顯示inputs不會被計(jì)算和累積 |
- torch.autograd.Variable
包裹張量并記錄應(yīng)用的操作
函數(shù) | 函數(shù)意義 |
---|---|
backward(gradient=None,retain_variables=False) | 當(dāng)前Variable對leaf variable求偏導(dǎo) |
detach() | 返回一個新變量與當(dāng)前圖形分離 |
detach_() | 從創(chuàng)建它的圖形中分離變量勒葱,與當(dāng)前圖形分離 |
register_hook(hook) | 注冊一個backward鉤子 |
reinforce(reward) | 注冊一個獎勵浪汪,這個獎勵是由一個隨機(jī)過程得到的 |
retain_grad() | 啟用非葉變量的.grad屬性 |
- torch.autograd.Function
記錄操作歷史并定義用于區(qū)分操作的公式
函數(shù) | 函數(shù)意義 |
---|---|
backward(*grad_output) | 定義用于區(qū)分操作的公式 |
static forward | 執(zhí)行操作 |
3.5 torch.optim
- torch.optim.Optimizer(params,default)
所有優(yōu)化器的基類
函數(shù) | 函數(shù)意義 |
---|---|
load_state_dict(state_dict) | 加載optimizer狀態(tài) |
state_dict() | 以dict類型返回optimizer狀態(tài) |
step(closure) | 進(jìn)行單步優(yōu)化 |
zero_grad() | 清空所有被優(yōu)化過的Variable的梯度 |
優(yōu)化器 | 優(yōu)化器意義 |
---|---|
torch.optim.Adadelta(params,lr=1.0,rho=0.9,eps=1e-06,weight_decay=0) | 實(shí)現(xiàn)Adadelta算法 |
torch.optim.Adagrad(params,lr=0.01,lr_decay=0,weight_decay=0) | 實(shí)現(xiàn)Adagrad算法 |
torch.optim.Adam(params,lr=0.001,betas=(0.9,0.999),eps=1e-08,weight_decay=0) | 實(shí)現(xiàn)Adam算法 |
torch.optim.Adamax(params,lr=0.002,betas=(0.9,0.999),eps=1e-08,weight_decay=0) | 實(shí)現(xiàn)Adamax算法 |
torch.optim.ASGD(params,lr=0.01,lambd=0.0001,alpha=0.75,t0=1000000.0,weight_decay=0) | 實(shí)現(xiàn)平均隨機(jī)梯度下降算法 |
torch.optim.LBFGS(params,lr=1,max_iter=20,max_eval=None,tolerance_grad=1e-05,tolerance_change=1e-09,history_size=100,line_search_fn=None) | 實(shí)現(xiàn)L-BFGS算法 |
torch.optim.RMSprop(params,lr=0.01,alpha=0.99,eps=1e-08,weight_decay=0,momentum=0,centered=False) | 實(shí)現(xiàn)RMSprop算法 |
torch.optim.Rprop(params,lr=0.01,etas=(0.5,1.2),step_sizes=(1e-06,50)) | 實(shí)現(xiàn)彈性反向傳播算法 |
torch.optim.SGD(params,lr,momentum=0,dampening=0,weight_decay=0,nesterov=False) | 實(shí)現(xiàn)隨機(jī)梯度下降算法 |
3.6 torch.nn.init
torch.nn.init.calculate_gain(nonlinearity,param=None)
torch.nn.init.uniform(tensor,a=0,b=1)
torch.nn.init.normal(tensor,mean=0,std=1)
torch.nn.init.constant(tensor,val)
torch.nn.init.eye(tensor)
torch.nn.init.dirac(tensor)
torch.nn.init.xavier_uniform(tensor,gain=1)
torch.nn.init.xavier_normal(tensor,gain=1)
torch.nn.init.kaiming_uniform(tensor,a=0,mode='fan_in')
torch.nn.init.kaiming_normal(tensor,a=0,mode='fan_in')
torch.nn.init.orthogonal(tensor,gain=1)
torch.nn.init.sparse(tensor,sparsity,std=0.01)
3.7 torch.multiprocessing
用于在相同數(shù)據(jù)的不同進(jìn)程中共享視圖
3.8 torch.cuda
實(shí)現(xiàn)與CPU張量相同的功能,但使用GPU進(jìn)行計(jì)算
函數(shù) | 函數(shù)意義 | |
---|---|---|
torch.cuda.current_blas_handle() | 返回cublasHandle_t指針 | |
torch.cuda.current_device() | 返回當(dāng)torch.cuda.current_stream() | 返回一個當(dāng)前所選的stream |
torch.cuda.device(idx) | 上下文管理器凛虽,可以更改所選設(shè)備 | |
torch.cuda.device_count() | 返回可獲得的GPU數(shù)量 | |
torch.cuda.device_of(obj) | 將當(dāng)前設(shè)備更改為給定對象的上下文管理器 | |
torch.cuda.is_available() | 指示CUDA當(dāng)前是否可用 | |
torch.cuda.set_device(device) | 設(shè)置當(dāng)前設(shè)備 | |
torch.cuda.stream(stream) | 選擇給定流的上下文管理器 | |
torch.cuda.synchronize() | 等待當(dāng)前設(shè)備上所有流中的所有核心完成 | |
torch.cuda.comm.broadcast(tensor,devices) | 向一些GPU廣播張量 | |
torch.cuda.comm.reduce_add(inputs,destination=None) | 將來自多個GPU的張量相加 | |
torch.cuda.comm.scatter(tensor,devices,chunk_sizes=None,dim=0,streams=None) | 打散橫跨多個GPU的張量 | |
torch.cuda.comm.gather(tensors,dim=0,destination=None) | 從多個GPU收集張量 | |
torch.cuda.Stream | CUDA流的包裝 | |
torch.cuda.Event(enable_timing=False,blocking=False,interprocess=False,_handle=None) | CUDA事件的包裝 |
3.9 torch.utils
- torch.utils.data.Dataset
表示Dataset的抽象類死遭,所有子類應(yīng)該override len和getitem,前者提供了數(shù)據(jù)集的大小凯旋,后者支持整數(shù)索引
函數(shù) | 函數(shù)意義 |
---|---|
torch.utils.data.TensorDataset(data_tensor,target_tensor) | 包裝數(shù)據(jù)和目標(biāo)張量的數(shù)據(jù)集 |
torch.utils.data.DataLoader(dataset,batch_size,shuffle,sampler,num_workers,collate_fn,pin_memory,drop_last) | 數(shù)據(jù)加載器呀潭,組合數(shù)據(jù)集和采集器,并在數(shù)據(jù)集上提供單進(jìn)程或多進(jìn)程迭代器 |
- torch.utils.data.sampler.Sampler(data_source)
所有采樣器的基礎(chǔ)類瓦阐,每個采樣器子類必須提供一個iter方法蜗侈,提供一種迭代數(shù)據(jù)集元素的索引的方法篷牌,以及返回迭代器長度的len方法
函數(shù) | 函數(shù)意義 |
---|---|
torch.utils.data.sampler.SequentialSampler(data_source) | 樣本元素順序排列睡蟋,始終以相同的順序 |
torch.utils.data.sampler.RandomSampler(data_source) | 樣本元素隨機(jī),沒有替換 |
torch.utils.data.sampler.SubsetRandomSampler(indices) | 樣本元素從指定的索引列表中隨機(jī)抽取枷颊,沒有替換 |
torch.utils.data.sampler.WeightedRandomSampler(weights,num_samples,replace=True) | 樣本元素來自于【0戳杀,len(weights)-1】该面,給定概率 |
torch.utils.model_zoo.load_url(url,model_dir=None) | 在給定的URL上加載Torch序列化對象 |
3.10 torch.torchvision
- 內(nèi)含數(shù)據(jù)集
torchvision.datasets.MNIST(root,train=True,transform=None,target_transform=None,download=False)
torchvision.datasets.CocoCaptions(root='dir where images are',annFile='json annotation file',[transform,target_transform])
torchvision.datasets.CocoDetection(root='dir where images are',annFile='json annotation file',[transform,target_transform])
torchvision.datasets.LUSN(db_path,classes='train',[transform,target_transform])
torchvision.datasets.ImageFolder(root='root_folder path',[transform,target_transform])
torchvision.datasets.CIFAR10(root,train=True,transform=None,target_transform=None,download=False)
torchvision.datasets.CIFAR100(root,train=True,transform=None,target_transform=None,download=False)
torchvision.datasets.STL10(root,split='train',transform=None,target_transform=None,download=False)
- 內(nèi)含模型
torchvision.models.alexnet(pretrained=False,**kwargs)
torchvision.models.resnet18(pretrained=False,**kwargs)
torchvision.models.resnet34(pretrained=False,**kwargs)
torchvision.models.resnet50(pretrained=False,**kwargs)
torchvision.models.resnet101(pretrained=False,**kwargs)
torchvision.models.resnet152(pretrained=False,**kwargs)
torchvision.models.vgg11(pretrained=False,**kwargs)
torchvision.models.vgg11_bn(**kwargs)
torchvision.models.vgg13(pretrained=False,**kwargs)
torchvision.models.vgg13_bn(**kwargs)
torchvision.models.vgg16(pretrained=False,**kwargs)
torchvision.models.vgg16_bn(**kwargs)
torchvision.models.vgg19(pretrained=False,**kwargs)
torchvision.models.vgg19_bn(**kwargs)
- 數(shù)據(jù)預(yù)處理
torchvision.transforms.Compose(transforms)
torchvision.transforms.CenterCrop(size)
torchvision.transforms.RandomCrop(size,padding=0)
torchvision.transforms.RandomHorizontalFlip
torchvision.transforms.RandomSizedCrop(size,interpolation=2)
torchvision.transforms.Pad(padding,fill=0)
torchvision.transform.Normalize(mean,std)
torchvision.transforms.ToTensor
torchvision.transforms.ToPILImage
torchvision.transforms.Lambda(lambda)
torchvision.utils.make_grid(tensor,nrow=8,padding=2,normalize=False,range=None,scale_each=False)
torchvisin.utils.save_image(tensor,filename,nrow=8,padding=2,normalize=False,range=None,scale_each=False)