torch笔记合集

摘要:
火炬的y不需要转换成一个热的。它会自动帮助

Torch笔记

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基本信息

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数据类型转换

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)) 

tensor 转换到 numpy数据

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

tensor的维度变换

  • squeeze_
tensor_a.t_().size() # 对tensor进行转置
tensor_a.t_().size()
tensor_a.unsqueeze_(2) #
unsqu_tensor = tensor_a.squeeze_() #  将tensor中维度元素数为1 的全部压缩掉
  • reshape()
tensor = torch.reshape(tensor_a, [50,20])
# 也可以用tensor.reshape(50,20)
tensor.size()
  • tanspose()
tensor.transpose(1,2)  #交换tensor的1,2维度

从只包含一个元素的张量中提取值

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

拼接张量

  • 例如当参数是3个10×5的张量,torch.cat的结果是30×5的张量,而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)
NOTE:This function does not broadcast. For broadcasting matrix products, see torch.matmul().
result = torch.matmul(tensor1, tensor2)  # 支持broadcast
  • tensor中对应元素相乘
tensor1*tensor2  # 支持broadcast
  • 矩阵求最大组索引
res,index = torch.max(tensor,dim=-1)
  • 维度理解 :填入哪个维度则哪个维度消失 比如sum,softmax

  • 求平均值 ==avg_pooling
avg = torch.mean(tensor,dim=-1)

打印模型信息

  • 参数量
  • 模型结构 使用torch summary
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)

计算Softmax输出的准确率

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网络结构
  • model.load_state_dict(torch.load("params.pkl"))
一些奇怪的注意事项
  • torch.nn.CrossEntropyLoss的输入不需要经过Softmax。torch.nn.CrossEntropyLoss等价于torch.nn.functional.log_softmax + torch.nn.NLLLoss。
  • torch的y不用转成onehot 它会自动帮你转 这点比较怪异,相比之下keras在多分类时 y必须是onehot的才能计算损失
  • model.train() :启用 BatchNormalization 和 Dropout
  • model.eval() :不启用 BatchNormalization 和 Dropout
tricks
  • 用del及时删除不用的中间变量,节约GPU存储。
  • 使用inplace操作可节约GPU存储,如

免责声明:文章转载自《torch笔记合集》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇微服务业务开发三个难题-拆分、事务、查询(下)LRU缓存及其实现下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

ONNX-开放式神经网络交换格式

以下内容根据个人理解整理而成,如有错误,欢迎指出,不胜感激。 1. ONNX简介 ONNX是一种针对机器学习所设计的开放式的文件格式,用于存储训练好的模型。它使得不同的人工智能框架(如Pytorch, MXNet)可以采用相同格式存储模型数据并交互。 ONNX的规范及代码主要由微软,亚马逊 ,Facebook 和 IBM 等公司共同开发,以开放源代码的方式...

NVIDIA深度架构

NVIDIA深度架构 本文介绍A100 GPU,NVIDIA Ampere架构GPU的重要新功能。  现代云数据中心中运行的计算密集型应用程序的多样性推动了NVIDIA GPU加速的云计算的爆炸式增长。此类密集型应用程序包括AI深度学习(DL)训练和推理,数据分析,科学计算,基因组学,边缘视频分析和5G服务,图形渲染,云游戏等。从扩展的AI训练和科学计算,...

【学习】Python进行数据提取的方法总结【转载】

链接:http://www.jb51.net/article/90946.htm 数据提取是分析师日常工作中经常遇到的需求。如某个用户的贷款金额,某个月或季度的利息总收入,某个特定时间段的贷款金额和笔数,大于5000元的贷款数量等等。本篇文章介绍如何通过python按特定的维度或条件对数据进行提取,完成数据提取需求。 准备工作首先是准备工作,导入需要使用...

手把手带你使用360度评估系统实施绩效反馈全流程(附详细图文)

☞☞360度评估反馈实施全面教程☜☜ 在线免费360度评估反馈系统:www.jianjianrenshi.com        360度评估又称360度全方位评估或多源评估,该项评估是由与被评估者有密切关系的人,分别匿名对被评估者进行评估,同时被评估者也进行自评;然后,由专业人士根据他人的评估结果,对比自评结果,出具评估报告并向被评估者提供反馈,帮助被评估...

《StackGAN》

StackGAN 周枫 少年,愿有一天,你能用内心的沉稳安宁,洗去身上的躁动和铅华 已关注 12 人赞同了该文章 未经授权,严禁任何形式转载!能力有限,欢迎指正批评! 参考 StackGAN: Text to Photo-realistic Image Synthesis with Stacked Generative Adversa...

windows环境 pip离线安装pytorch-gpu版本总结(没用anaconda)

1.确定你自己的环境信息。 我的环境是:win8+cuda8.0+python3.6.5 各位一定要根据python版本和cuDa版本去官网查看所对应的.whl文件再下载! 2.去官网查看环境匹配的torch、torchversion版本信息,然后去镜像源下载对应的文件 (直接去官网下载会出现中断的情况,如果去官网下载建议尝试迅雷下载)或者镜像网站下载对应...