深度学习—从入门到放弃(一)pytorch

Tensor

类似于numpy的array,pandas的dataframe;在pytorch里的数据结构是tensor,即张量

tensor简单操作

1.Flatten and reshape
###
Original z: tensor([[ 0,  1],[ 2,  3],[ 4,  5],[ 6,  7],[ 8,  9],[10, 11]])
Flattened z: tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
Reshaped (3x4) z: tensor([[ 0,  1,  2,  3],[ 4,  5,  6,  7],[ 8,  9, 10, 11]])
###
2.Squeezing tensors

当我们处理类似于x.shape=[1,10]或[256,1,3]这样的高维数据时,单纯输入下x[0]可能无法输出对应的点数据,所以我们需要用torch.squeeze()提取某一个具体维度

x = torch.randn(1, 10)
x = x.squeeze(0)#取到了第一行的x的数据
print(x.shape)
print(f"x[0]: {x[0]}")
###
torch.Size([10])
x[0]: -0.7390837073326111
###
3.permute

torch.permute()可以用来重新排列维度之间的顺序

x = torch.rand(3, 48, 64)
x = x.permute(1, 2, 0)
###
torch.Size([48, 64, 3])
###
4.Concatenation

tensor和tensor之间按维度的拼接

x = torch.arange(12, dtype=torch.float32).reshape((3, 4))
y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
#行连接
cat_rows = torch.cat((x, y), dim=0)
#列连接
cat_cols = torch.cat((x, y), dim=1)
###
行连接: shape[6, 4] tensor([[ 0.,  1.,  2.,  3.],[ 4.,  5.,  6.,  7.],[ 8.,  9., 10., 11.],[ 2.,  1.,  4.,  3.],[ 1.,  2.,  3.,  4.],[ 4.,  3.,  2.,  1.]])
列连接: shape[3, 8]  tensor([[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],[ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],[ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.]])
###

GPU vs CPU

在处理大规模与高速数据时,CPU很难满足需要,而深度学习往往就需要处理大规模的数据,所以我们需要灵活的选择CPU或GPU

def set_device():device = "cuda" if torch.cuda.is_available() else "cpu"if device != "cuda":print("GPU is not enabled in this notebook. \n""If you want to enable it, in the menu under `Runtime` -> \n""`Hardware accelerator.` and select `GPU` from the dropdown menu")else:print("GPU is enabled in this notebook. \n""If you want to disable it, in the menu under `Runtime` -> \n""`Hardware accelerator.` and select `None` from the dropdown menu")return deviceDEVICE = set_device()

简单神经网络

Pytorch有一个 nn.Module类专门用于构建深度学习网络,我们需要从 nn.Module中继承并实现一些重要的方法:

  1. init
    在该__init__方法中,我们需要定义网络的结构。在这里,我们将指定网络由哪些层组成,将使用哪些激活函数等。
  2. forward
    所有神经网络模块都需要实现该forward方法。它指定了当数据通过网络时网络需要进行的计算。
  3. predict
    这不是神经网络模块的强制性方法,但可用于快速从网络中获得最可能的标签
  4. train
    这也不是强制性方法,但可用于训练网络中的参数
# Inherit from nn.Module - the base class for neural network modules provided by Pytorch
class NaiveNet(nn.Module):# Define the structure of your networkdef __init__(self):super(NaiveNet, self).__init__()# The network is defined as a sequence of operationsself.layers = nn.Sequential(nn.Linear(2, 16),  # Transformation from the input to the hidden layernn.ReLU(),         # Activation function (ReLU) is a non-linearity which is widely used because it reduces computation. The function returns 0 if it receives any# negative input, but for any positive value x, it returns that value back.nn.Linear(16, 2),  # Transformation from the hidden to the output layer)# Specify the computations performed on the datadef forward(self, x):# Pass the data through the layersreturn self.layers(x)# Choose the most likely label predicted by the networkdef predict(self, x):# Pass the data through the networksoutput = self.forward(x)# Choose the label with the highest scorereturn torch.argmax(output, 1)# Implement the train function given a training dataset X and correcsponding labels y
def train(model, X, y):# The Cross Entropy Loss is suitable for classification problemsloss_function = nn.CrossEntropyLoss()# Create an optimizer (Stochastic Gradient Descent) that will be used to train the networklearning_rate = 1e-2optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)# Number of epochsepochs = 15000# List of losses for visualizationlosses = []for i in range(epochs):# Pass the data through the network and compute the loss# We'll use the whole dataset during the training instead of using batches# in to order to keep the code simple for now.y_logits = model.forward(X)loss = loss_function(y_logits, y)# Clear the previous gradients and compute the new onesoptimizer.zero_grad()loss.backward()# Adapt the weights of the networkoptimizer.step()# Store the losslosses.append(loss.item())# Print the results at every 1000th epochif i % 1000 == 0:print(f"Epoch {i} loss is {loss.item()}")plot_decision_boundary(model, X, y, DEVICE)plt.savefig('frames/{:05d}.png'.format(i))return losses# Create a new network instance a train it
model = NaiveNet().to(DEVICE)
losses = train(model, X, y)

以上为一个简单神经网络应用于分类的实例,整个网络的结构如下:1 个大小为 2 的输入层+1 个大小为 16 的隐藏层(ReLU为激活函数)+1 个大小为 2 的输出层

NaiveNet(
(layers): Sequential(
(0): Linear(in_features=2, out_features=16, bias=True)
(1): ReLU()
(2): Linear(in_features=16, out_features=2, bias=True)
)
)

今天大家只需对神经网络的基本结构有一个了解,明天将会系统学习简单线性神经网络的详细结构。也欢迎大家关注公众号奇趣多多一块交流!

深度学习—从入门到放弃(二)简单线性神经网络

深度学习---从入门到放弃(一)pytorch基础相关推荐

  1. 深度学习---从入门到放弃(九)RNN入门

    深度学习-从入门到放弃(九)RNN入门 1.RNN简介 RNN(Recurrent Neural Network)是一类用于处理序列数据的神经网络.回想一下我们之前说到过的CNN,它可以通过在空间上共 ...

  2. 150页书籍《PyTorch 深度学习快速入门指南》附PDF电子版

    为什么说是极简教程,首先本书只涵盖了150页.内容比较精简,特别适合作为 PyTorch 深度学习的入门书籍.为什么这么说呢?因为很多时候,一份厚重的书籍往往会削弱我们学习的积极性,在学习一门新的语言 ...

  3. 2_初学者快速掌握主流深度学习框架Tensorflow、Keras、Pytorch学习代码(20181211)

    初学者快速掌握主流深度学习框架Tensorflow.Keras.Pytorch学习代码 一.TensorFlow 1.资源地址: 2.资源介绍: 3.配置环境: 4.资源目录: 二.Keras 1.资 ...

  4. 15个小时彻底搞懂NLP自然语言处理(2021最新版附赠课件笔记资料)【LP自然语言处理涉及到深度学习和神经网络的介绍、 Pytorch、 RNN自然语言处理】 笔记

    15个小时彻底搞懂NLP自然语言处理(2021最新版附赠课件笔记资料)[LP自然语言处理涉及到深度学习和神经网络的介绍. Pytorch. RNN自然语言处理] 笔记 教程与代码地址 P1 机器学习与 ...

  5. 深度学习小白入门教程-基础环境篇

    深度学习小白入门教程-基础环境篇 如有图片显示失败,请回小主主页查看~ Anaconda 安装包下载方式一:官网(科学上网比较慢,不推荐) 安装包下载方式二:清华镜像(推荐) 具体安装步骤(跟着箭头来 ...

  6. 深度学习地震勘探入门

    深度学习地震勘探入门 简介 我们在论文中提供了一个例子,但是由于数据不容易下载,很多同学没有测试成功,这个帖子中我们将这个例子进行了详细注释,同时提供手把手教学,数据也上传到了百度网盘.如果大家觉得有 ...

  7. 深度学习报错 | THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp

    深度学习报错 | THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp 错误定位 解决历程 错误定位 近日在自己的服务器上跑别人的代码时 ...

  8. 图深度学习,入门教程七,残差多层图注意力模型

    深度学习还没学完,怎么图深度学习又来了?别怕,这里有份系统教程,可以将0基础的你直接送到图深度学习.还会定期更新哦. 主要是基于图深度学习的入门内容.讲述最基本的基础知识,其中包括深度学习.数学.图神 ...

  9. 基于深度学习的口罩识别与检测PyTorch实现

    基于深度学习的口罩识别与检测PyTorch实现 1. 设计思路 1.1 两阶段检测器:先检测人脸,然后将人脸进行分类,戴口罩与不戴口罩. 1.2 一阶段检测器:直接训练口罩检测器,训练样本为人脸的标注 ...

最新文章

  1. python 重载_python模块重载的五种方法
  2. 你想要的宏基因组-微生物组知识全在这(180601)
  3. java中文乱码问题的原因是什么?怎么解决中文乱码问题?
  4. 通过pxe从网络启动安装Windows XP
  5. (诡异事件)iframe标签后面的alert不执行
  6. 在 Windows Azure 上部署预配置 Oracle VM
  7. 如何有效提高你的沟通技巧
  8. 基于麻雀算法的投影寻踪模型 - 附代码
  9. MAC机上JAVA对话框死锁的案例之一
  10. Confluence 6 审查日志的对象
  11. 妙用chrome插件,实现U校园自动填答案
  12. python批量处理text_【RhinoPython】Rhino如何批量替换text 和Dot
  13. Android Studio快捷键设置 (实现原eclipse ctrl+m 代码全屏的效果)
  14. 写一篇简单的 IEEE 会议论文
  15. 什么是网站的样本设计
  16. wdcp服务器权限修改,Linux下wdcp控制面板安装tipask3.0教程
  17. nvm介绍、nvm下载、安装与使用
  18. throttle/debounce应用及原理
  19. Ghost还原出错An internal inconsistency has been detected
  20. ReactDOM.render 是如何串联渲染链路的?(中)

热门文章

  1. 面试测试岗想拿13K,HR说你最多值10K,教你怼死HR?
  2. 小白入门STM32(1)----手机蓝牙控制STM32单片机点亮LED
  3. 怎么理解无界队列和有界队列
  4. 手工改造debian安装U盘
  5. HashSet-哈希值
  6. 如何判断是不是个maven项目
  7. C语言 第十二章 文件
  8. XNA学习笔记(5)-调节刷新率(framerate)
  9. GHost++ CB (Custom Build) MOD
  10. 计算机专业要不要读研?