0
点赞
收藏
分享

微信扫一扫

qt判断当前日期的当月的最后一天是几号

进击的包籽 2023-10-13 阅读 10

一、说明

        深度学习是机器学习的一个分支,其中编写的算法模仿人脑的功能。深度学习中最常用的库是 Tensorflow 和 PyTorch。由于有各种可用的深度学习框架,人们可能想知道何时使用 PyTorch。以下是人们更喜欢使用 Pytorch 来完成特定任务的原因。

        Pytorch 是一个开源深度学习框架,提供 Python 和 C++ 接口。Pytorch 驻留在 torch 模块内。在 PyTorch 中,需要处理的数据以张量的形式输入。

二、安装 PyTorch

        如果您的系统中安装了 Anaconda Python 包管理器,则在终端中运行以下命令将安装 PyTorch: 

        此命令将安装最新的稳定版本的 PyTorch。Stable 代表当前经过最多测试和支持的 PyTorch 版本。Pytorch 的最新稳定版本是 1.12.1。如果您想使用 PyTorch 而不将其显式安装到本地计算机中,则可以使用 Google Colab。

三、PyTorch 张量

        Pytorch 用于处理张量。张量是多维数组,如 n 维 NumPy 数组。然而,张量也可以在 GPU 中使用,而 NumPy 数组则不然。PyTorch 具有各种内置函数,因此可以加速张量的科学计算。

向量是一维张量,矩阵是二维张量。C、C++ 和 Java 中使用的张量和多维数组之间的一个显着区别是张量在所有维度上应具有相同的列大小。此外,张量只能包含数字数据类型。

张量的两个基本属性是: 

  • 形状:指数组或矩阵的维数
  • Rank:指张量中存在的维数

代码:

  • Python3

# importing torch

import torch

 

# creating a tensors

t1=torch.tensor([1, 2, 3, 4])

t2=torch.tensor([[1, 2, 3, 4],

                 [5, 6, 7, 8],

                 [9, 10, 11, 12]])

 

# printing the tensors:

print("Tensor t1: \n", t1)

print("\nTensor t2: \n", t2)

 

# rank of tensors

print("\nRank of t1: ", len(t1.shape))

print("Rank of t2: ", len(t2.shape))

 

# shape of tensors

print("\nRank of t1: ", t1.shape)

print("Rank of t2: ", t2.shape)

 输出:

四、在 PyTorch 中创建张量

        在 PyTorch 中创建张量有多种方法。张量可以包含单一数据类型的元素。我们可以使用 python 列表或 NumPy 数组创建张量。Torch 有 10 种适用于 GPU 和 CPU 的张量变体。以下是定义张量的不同方法。
 

代码:

  • Python3

# importing torch module

import torch

import numpy as np

 

# list of values to be stored as tensor

data1 = [1, 2, 3, 4, 5, 6]

data2 = np.array([1.5, 3.4, 6.8,

                9.3, 7.0, 2.8])

 

# creating tensors and printing

t1 = torch.tensor(data1)

t2 = torch.Tensor(data1)

t3 = torch.as_tensor(data2)

t4 = torch.from_numpy(data2)

 

print("Tensor: ",t1, "Data type: ", t1.dtype,"\n")

print("Tensor: ",t2, "Data type: ", t2.dtype,"\n")

print("Tensor: ",t3, "Data type: ", t3.dtype,"\n")

print("Tensor: ",t4, "Data type: ", t4.dtype,"\n")

 
 输出:

 

五、在 Pytorch 中重构张量

        我们可以在 PyTorch 中根据需要修改张量的形状和大小。我们还可以创建 and 张量的转置。以下是根据需要更改张量结构的三种常见方法:

 

        2*3 矩阵已被重新整形并转置为 3*2。我们可以可视化这两种情况下张量中元素排列的变化。 

代码:

  • Python3

# import torch module

import torch

 

# defining tensor

t = torch.tensor([[1, 2, 3, 4],

                 [5, 6, 7, 8],

                 [9, 10, 11, 12]])

 

# reshaping the tensor

print("Reshaping")

print(t.reshape(6, 2))

 

# resizing the tensor

print("\nResizing")

print(t.resize(2, 6))

 

# transposing the tensor

print("\nTransposing")

print(t.transpose(1, 0))

 
 

六、PyTorch 中张量的数学运算

         我们可以使用 Pytorch 对张量执行各种数学运算。执行数学运算的代码与 NumPy 数组的情况相同。下面是在张量中执行四种基本运算的代码。

  • Python3

# import torch module

import torch

 

# defining two tensors

t1 = torch.tensor([1, 2, 3, 4])

t2 = torch.tensor([5, 6, 7, 8])

 

# adding two tensors

print("tensor2 + tensor1")

print(torch.add(t2, t1))

 

# subtracting two tensor

print("\ntensor2 - tensor1")

print(torch.sub(t2, t1))

 

# multiplying two tensors

print("\ntensor2 * tensor1")

print(torch.mul(t2, t1))

 

# diving two tensors

print("\ntensor2 / tensor1")

print(torch.div(t2, t1))

 输出:

 

 

要进一步深入了解使用 Pytorch 进行矩阵乘法,请参阅本文。
 

六、Pytorch 模块

        PyTorch 库模块对于创建和训练神经网络至关重要。三个主要的库模块是 Autograd、Optim 和 nn。
 

        # 1. Autograd 模块: autograd 提供了轻松计算梯度的功能,无需明确手动实现所有层的前向和后向传递。 

        为了训练任何神经网络,我们执行反向传播来计算梯度。通过调用 .backward() 函数,我们可以计算从根到叶子的每个梯度。 
 

代码:

  • Python3

# importing torch

import torch

 

# creating a tensor

t1=torch.tensor(1.0, requires_grad = True)

t2=torch.tensor(2.0, requires_grad = True)

 

# creating a variable and gradient

z=100 * t1 * t2

z.backward()

 

# printing gradient

print("dz/dt1 : ", t1.grad.data)

print("dz/dt2 : ", t2.grad.data)

 
 输出:

 

 

        # 2. Optim 模块: PyTorch Optium 模块有助于实现各种优化算法。该软件包包含最常用的算法,例如 Adam、SGD 和 RMS-Prop。要使用 torch.optim,我们首先需要构造一个 Optimizer 对象,它将保留参数并相应地更新它。首先,我们通过提供我们想要使用的优化器算法来定义优化器。我们在反向传播之前将梯度设置为零。然后为了更新参数,调用optimizer.step()。 

         # 3. nn 模块:这个包有助于构建神经网络。它用于构建层。 

为了创建单层模型,我们可以使用 nn.Sequential() 简单地定义它。

对于不在单个序列中的模型的实现,我们通过子类化 nn.Module 类来定义模型。 

 

  • Python3

class Model (nn.Module) :

 

         def __init__(self):

 

              super(Model, self).__init__()

 

              self.linear = torch.nn.Linear(1, 1

 

      def forward(self, x):

 

              y_pred = self.linear(x)

 

             return y_pred

 
 

 七、PyTorch 数据集和数据加载器

 

        torch.utils.data.Dataset 类包含所有自定义数据集。我们需要实现两个方法,__len__() 和 __get_item__(),来创建我们自己的数据集类。

        PyTorch Dataloader 具有一个惊人的功能,可以与自动批处理并行加载数据集。因此,它减少了顺序加载数据集的时间,从而提高了速度。  

         PyTorch DataLoader 支持两种类型的数据集:

  • 映射式数据集:数据项映射到索引。在这些数据集中, __get_item__() 方法用于检索每个项目的索引。
  • 可迭代式数据集:在这些数据集中实现了 __iter__() 协议。数据样本按顺序检索。 

请参阅《在 PyTorch 中使用 DataLoader》一文了解更多信息。
 

八、使用 PyTorch 构建神经网络

 

我们将在逐步实施中看到这一点:

  1. 数据集准备:由于PyTorch中的所有内容都以张量的形式表示,因此我们应该首先以张量表示。
  2. 构建模型:为了构建神经网络,我们首先定义输入层、隐藏层和输出层的数量。我们还需要定义初始权重。权重矩阵的值是使用torch.randn()随机选择的。Torch.randn() 返回一个由标准正态分布的随机数组成的张量。
  3. 前向传播:将数据输入神经网络,并在权重和输入之间执行矩阵乘法。这可以使用手电筒轻松完成。
  4. 损失计算: PyTorch.nn 函数有多个损失函数。损失函数用于衡量预测值与目标值之间的误差。
  5. 反向传播:用于优化权重。改变权重以使损失最小化。

 

        现在让我们从头开始构建一个神经网络: 

  • Python3

# importing torch

import torch

 

# training input(X) and output(y)

X = torch.Tensor([[1], [2], [3],

                [4], [5], [6]])

y = torch.Tensor([[5], [10], [15],

                  [20], [25], [30]])

 

class Model(torch.nn.Module):

 

    # defining layer

    def __init__(self):

        super(Model, self).__init__()

        self.linear = torch.nn.Linear(1, 1)

     

    # implementing forward pass

    def forward(self, x):

        y_pred = self.linear(x)

        return y_pred

 

model = torch.nn.Linear(1 , 1)

 

# defining loss function and optimizer

loss_fn = torch.nn.L1Loss()

optimizer = torch.optim.Adam(model.parameters(), lr = 0.01 )

 

for epoch in range(1000):

    

    # predicting y using initial weights

    y_pred = model(X.requires_grad_())

 

    # loss calculation

    loss = loss_fn(y_pred, y)

 

    # calculating gradients

    loss.backward()

 

    # updating weights

    optimizer.step()

 

    optimizer.zero_grad()

 

# testing on new data   

X = torch.Tensor([[7], [8]])

predicted = model(X)

print(predicted)

 

输出:

 

举报

相关推荐

0 条评论