コレクションノートトーチ

トーチノート

import torch
import numpy as np
import torch.nn as nn
a_np = np.random.rand(10,100)

numpyの知識のレビュー

a_np.dtype  # 数据类型
a_np.ndim #维度个数
a_np.shape # 形状   整数元祖
a_np.dtype=np.int32  # 修改数据类型

テンソルは、基本的な情報を得ます

tensor_a = torch.from_numpy(a_np)
tensor_a.type() # 获取tensor类型
tensor_a.size() # 获取维度特征 并返回数组
tensor_a.size(0) #获取第一个维度信息
tensor_a.dim() # 获取维度个数
tensor_a.device # 返回设备类型

データ型変換テンソル

tensor_b = tensor_a.float()  
tensor_b = tensor_a.to(torch.float) 

デバイスタイプ変換

tensor_b = tensor_b.cuda()
tensor_b = tensor_b.cpu()
tensor_b = tensor_a.to(torch.device(0)) 

テンソルデータはnumpyのに変換しました

tensor_b = tensor_b.numpy()
# 注意*gpu上的tensor不能直接转为numpy
ndarray = tensor_b.cpu().numpy()
# numpy 转 torch.Tensor
tensor = torch.from_numpy(ndarray) 

テンソル次元変換

  • squeeze_
tensor_a.t_().size() # 对tensor进行转置
tensor_a.t_().size()
tensor_a.unsqueeze_(2) #
unsqu_tensor = tensor_a.squeeze_() #  将tensor中维度元素数为1 的全部压缩掉
  • リシェイプ()
tensor = torch.reshape(tensor_a, [50,20])
tensor.size()

テンソルから抽出されただけで一つの要素値が含まれています

tensor_a = tensor_a.cuda()
tensor_a[1][1].item()
tensor_a.device

ステッチングテンソル

  • パラメータがある場合、例えば、10×5テンソル、30×5 torch.catそのテンソル結果、結果の3つがtorch.stackテンソル3×10×5のです。
temp1 = torch.from_numpy(np.random.rand(5,4))
temp2 = torch.from_numpy(np.random.rand(5,4))

temp1.size()
temp2.size()
temp3 = torch.stack([temp1,temp2],dim=0)
temp4 = torch.cat([temp1,temp2],dim=0)

temp3.size()
temp4.size()

行列乗算

# Matrix multiplication: (m*n) * (n*p) -> (m*p).
result = torch.mm(tensor1, tensor2)
# Batch matrix multiplication: (b*m*n) * (b*n*p) -> (b*m*p).
result = torch.bmm(tensor1, tensor2)

モデル情報を印刷

  • パラメータの量
  • モデル構造は、トーチの概要を使用しています
class myNet(nn.Module):
    def __init__(self,*other_para):
        super(myNet,self).__init__()
        self.embedding_layer = nn.Embedding(10,3)

net = myNet()
num_parameters = sum(torch.numel(parameter) for parameter in net.parameters())
from torchsummary import summary
summary(net,input_size=(2,2))

モデルの初期化

# Common practise for initialization.
for layer in model.modules():
    if isinstance(layer, torch.nn.Conv2d):
        torch.nn.init.kaiming_normal_(layer.weight, mode='fan_out',
                                      nonlinearity='relu')
        if layer.bias is not None:
            torch.nn.init.constant_(layer.bias, val=0.0)
    elif isinstance(layer, torch.nn.BatchNorm2d):
        torch.nn.init.constant_(layer.weight, val=1.0)
        torch.nn.init.constant_(layer.bias, val=0.0)
    elif isinstance(layer, torch.nn.Linear):
        torch.nn.init.xavier_normal_(layer.weight)
        if layer.bias is not None:
            torch.nn.init.constant_(layer.bias, val=0.0)

# Initialization with given tensor.
layer.weight = torch.nn.Parameter(tensor)

出力演算精度ソフトマックス

score = model(images)
prediction = torch.argmax(score, dim=1)
num_correct = torch.sum(prediction == labels).item()
accuruacy = num_correct / labels.size(0)

保存モデル

  • torch.save(my_model.state_dict()、 "params.pkl")

負荷モデル

  • まず、ネットワーク構造のモデルを初期化します
  • model.load_state_dict(torch.load( "params.pkl"))

いくつかの奇妙なノート

  • torch.nn.CrossEntropyLoss入力はソフトマックスを必要としません。torch.nn.CrossEntropyLoss同等torch.nn.functional.log_softmax + torch.nn.NLLLoss。
  • yが、それは自動的にあなたがマルチ分類yにこの奇妙な、比較kerasを回すのに役立ちますonehotに変わりはありませんトーチはonehotの損失を計算することができなければなりません
  • model.train():BatchNormalizationとドロップアウトを有効にします
  • model.eval():BatchNormalizationとドロップアウトを有効にしません

トリック

  • デルは、速やかにGPUのメモリを節約し、中間の変数を削除しました。
  • インプレース操作として、GPUメモリの節約を使用して

おすすめ

転載: www.cnblogs.com/rise0111/p/11931507.html