컬렉션 노트 토치

토치 노트

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) 

텐서 차원 변환

  • 압착_
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 텐서 그 결과, 그 결과는 세 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