深度学习---从入门到放弃pytorch基础(代码片段)

佩瑞 佩瑞     2022-12-22     663

关键词:

深度学习—从入门到放弃(一)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 device
  
 DEVICE = 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 network
  def __init__(self):
    super(NaiveNet, self).__init__()

    # The network is defined as a sequence of operations
    self.layers = nn.Sequential(
        nn.Linear(2, 16),  # Transformation from the input to the hidden layer
        nn.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 data
  def forward(self, x):
    # Pass the data through the layers
    return self.layers(x)

  # Choose the most likely label predicted by the network
  def predict(self, x):
    # Pass the data through the networks
    output = self.forward(x)

    # Choose the label with the highest score
    return 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 problems
  loss_function = nn.CrossEntropyLoss()

  # Create an optimizer (Stochastic Gradient Descent) that will be used to train the network
  learning_rate = 1e-2
  optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

  # Number of epochs
  epochs = 15000

  # List of losses for visualization
  losses = []

  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 ones
    optimizer.zero_grad()
    loss.backward()

    # Adapt the weights of the network
    optimizer.step()

    # Store the loss
    losses.append(loss.item())

    # Print the results at every 1000th epoch
    if 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)
)
)

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

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

深度学习---从入门到放弃优化器(代码片段)

深度学习—从入门到放弃(四)优化器1.案例引入-MNIST手写数字识别现代深度学习优化中的许多核心思想(和技巧)可以在训练MLP以解决图像分类任务的中进行说明。在这里我们使用的是手写数字的MNIST数据集࿰... 查看详情

初识pytorch:从安装到入门,从入门到放弃(代码片段)

目录PyTorch安装配置安装验证PyTorchPyTorch是Facebook团队于2017年1月发布的一个深度学习框架,虽然晚于TensorFlow,也没有TensorFlow火,但目前已经与TensorFlow奇虎相当。而且PyTorch采用了Python语言的接口,可以说它才是Pytho... 查看详情

对比学习:《深度学习之pytorch》《pytorch深度学习实战》+代码

PyTorch是一个基于Python的深度学习平台,该平台简单易用上手快,从计算机视觉、自然语言处理再到强化学习,PyTorch的功能强大,支持PyTorch的工具包有用于自然语言处理的AllenNLP,用于概率图模型的Pyro,扩展了PyTorch的功能。通... 查看详情

深度学习:从入门到放弃

https://zhuanlan.zhihu.com/p/22976342 首发于深度学习:从入门到放弃写文章登录 FCN学习:SemanticSegmentation余俊1年前感谢@huangh12 @郑途 @麦田守望者对标签图像生成的研究和讨论,这几天研究了一下,补充如下。-------------------... 查看详情

[资源]深度学习从入门到放弃

Relationship:  MachineLearning---->DeepLearning                           ---->DeepReinforcementLearning[LearningRoadMap]              ReinforcementLearningPapers:  DeepLearningPapersReadin 查看详情

深度学习---从入门到放弃简单线性神经网络(代码片段)

深度学习—从入门到放弃(二)简单线性神经网络1.基本结构就像昨天说的,我们构建深度学习网络一般适用于数据大,处理难度也大的任务,因此对于网络的结构需要有一个非常深入的了解。这里以一个分类... 查看详情

pytorch从入门到精通100讲-pytorch张量从概念到应用(代码片段)

PyTorch张量的创建与基本类型0导读在我们不知道什么是深度学习计算框架时,我们可以把PyTorch看做是Python的第三方库,在PyTorch中定义了适用于深度学习的张量Tensor,以及张量的各类计算。就相当于NumPy中定义的Array和对应的科学... 查看详情

零基础如何入门到精通人工智能pytorch,深度学习,如何跟进ai领域的最新算法,如何读论文找代码

零基础如何入门人工智能,如何跟进AI领域的最新算法,如何读论文、找代码。【入门人工智能】1、掌握一门编程语言:Python【B站小甲鱼】零基础入门学习Pythonhttps://www.bilibili.com/video/BV1c4411e77t2、数学基础:微积... 查看详情

零基础如何入门到精通人工智能pytorch,深度学习,如何跟进ai领域的最新算法,如何读论文找代码

零基础如何入门人工智能,如何跟进AI领域的最新算法,如何读论文、找代码。【入门人工智能】1、掌握一门编程语言:Python【B站小甲鱼】零基础入门学习Pythonhttps://www.bilibili.com/video/BV1c4411e77t2、数学基础:微积... 查看详情

零基础如何入门到精通人工智能pytorch,深度学习,如何跟进ai领域的最新算法,如何读论文找代码

零基础如何入门人工智能,如何跟进AI领域的最新算法,如何读论文、找代码。【入门人工智能】1、掌握一门编程语言:Python【B站小甲鱼】零基础入门学习Pythonhttps://www.bilibili.com/video/BV1c4411e77t2、数学基础:微积... 查看详情

pytorch学习笔记3.深度学习基础(代码片段)

...多分类22.全连接层23.激活函数与GPU加速24.测试根据龙良曲Pytorch学习视频整理,视频链接:【计算机-AI】PyTorch学这个就够了!(好课推荐)深度学习与PyTorch入门实战——主讲人龙 查看详情

docker从入门到放弃(代码片段)

??为什么要学习docker呢?深有体会,由于一些原因只能在他人电脑上搭建环境,明明在自己电脑上的程序跑的好好的,在他人的电脑上就是死活出错。折磨人呀!!!!!可是能怎么办,工作还得继续,曲线救国呗,折腾了一天... 查看详情

自然语言处理pytorch基础入门(必备基础知识)(代码片段)

PyTorch基础实践PyTorch基础安装PyTorch创建张量张量类型和大小张量操作索引,切片和连接张量和计算图CUDA张量练习Solutions总结PyTorch基础在本书中,我们广泛地使用PyTorch来实现我们的深度学习模型。PyTorch是一个开源、社区... 查看详情

深度学习理论与实战pytorch实现

课程目录:01.预备内容(入门)02.Python基础(入门)03.PyTorch基础(入门)04.神经网络(进阶)05.卷积神经网络(进阶)06.循环神经网络(进阶)07.生成对抗网络GAN(进阶)08.强化学习(进阶)09.毕业项目 下载地址:深度学习理... 查看详情

如何高效入门pytorch?深度学习框架是pytorch还是tensorflow?(代码片段)

PyTorch入门,着实入了不少坑。咱们来谈谈,如何选个合适的教程,避开它们。一、Tensorflow VS  PyTorch    在这之前,有一个问题肯定困惑大家很久了,2021年了,TensorFlow和PyTorch两个深度学习框架学哪个... 查看详情

深度学习——pytorch基础(代码片段)

深度学习(1)——Pytorch基础作者:夏风喃喃参考:《动手学深度学习第二版》李沐文章目录深度学习(1)——Pytorch基础一.数据操作二.数据预处理三.绘图四.自动求导五.概率论导入相关包:importtorch ... 查看详情

深度学习——pytorch基础(代码片段)

深度学习(1)——Pytorch基础作者:夏风喃喃参考:《动手学深度学习第二版》李沐文章目录深度学习(1)——Pytorch基础一.数据操作二.数据预处理三.绘图四.自动求导五.概率论导入相关包:importtorch ... 查看详情

(翻译)60分钟入门深度学习工具-pytorch(代码片段)

60分钟入门深度学习工具-PyTorch作者:SoumithChintala原文翻译自:一、Pytorch是什么?二、AUTOGRAD三、神经网络四、训练一个分类器五、数据并行他是一个基于Python的科学计算包,目标用户有两类为了使用GPU来替代numpy一个深度学习研... 查看详情