Skip to content

Caffe2 - 创建自定义网络

在本课程中,您将学习如何在 PyTorch 中定义一个简单的单层神经网络,并使用样本数据执行前向传播(forward pass)。我们将介绍 PyTorch 的 Tensor、Module 和 Linear 层。对神经网络概念(层、权重、偏置、前向传播)有基本了解会有帮助。

PyTorch 中基本的数据结构是 Tensor (torch.Tensor),它类似于 NumPy 数组,但增加了 GPU 加速和自动微分(Autograd)等功能。

我们来创建一些 Tensor:

import torch
# Create a tensor with random values (e.g., for input data)
# Shape: [batch_size, num_features]
input_data = torch.randn(2, 3) # Batch of 2 samples, 3 features each
print("Input Data Tensor:\n", input_data)
# Create tensors for weights and biases (these are usually managed by nn.Module)
# Example shapes for a layer mapping 3 input features to 5 output features
weights = torch.randn(5, 3) # Shape: [output_features, input_features]
biases = torch.ones(5) # Shape: [output_features]
print("\nExample Weights Tensor:\n", weights)
print("\nExample Biases Tensor:\n", biases)

我们想构建一个代表单个全连接(或称为 ‘Linear’)层的网络。在数学上,这计算的是:Y = X * W^T + b,其中 X 是输入,W 是权重矩阵,b 是偏置向量,Y 是输出。

在 PyTorch 中,网络层和模型通常通过继承 torch.nn.Module 来定义。这提供了结构并有助于管理参数(如权重和偏置)。

首先,导入必要的组件:

import torch.nn as nn

现在,定义网络类:

class SingleLayerFC(nn.Module):
def __init__(self, input_features, output_features):
super(SingleLayerFC, self).__init__() # Call parent class constructor
# Define the layer(s)
self.linear_layer = nn.Linear(input_features, output_features)
# nn.Linear automatically creates and initializes weight and bias tensors
def forward(self, x):
# Define the computation flow
output = self.linear_layer(x)
return output

我们来实例化这个网络。我们需要指定输入特征的数量(与我们的 input_data 匹配)以及期望的输出特征数量。

# Define dimensions
input_dim = 3
output_dim = 5
# Create an instance of the network
model = SingleLayerFC(input_dim, output_dim)
print("\nModel Structure:")
print(model)

打印模型会显示其结构,包括自动创建的 nn.Linear 层。

为了获得样本 input_data 的输出,我们只需像调用函数一样调用模型实例:

# Pass the input data through the model
output_data = model(input_data)
print("\nInput Data Shape:", input_data.shape)
print("Output Data Tensor:\n", output_data)
print("Output Data Shape:", output_data.shape)

输出 Tensor output_data 的形状将是 [batch_size, output_features],在本例中是 [2, 5]。这些值是使用 nn.Linear 层中随机初始化的权重和偏置计算得出的。

我们可以检查 nn.Module 自动跟踪的可学习参数(权重和偏置):

print("\nModel Parameters:")
for name, param in model.named_parameters():
if param.requires_grad:
print(f"Name: {name}")
print(f"Shape: {param.shape}")
print(f"Values:\n{param.data}") # Use .data to view tensor values

这将显示模型管理的 ‘linear_layer.weight’ 和 ‘linear_layer.bias’ Tensor。

您现在已经成功地在 PyTorch 中定义了一个简单的神经网络,将数据通过它进行处理,并检查了其参数。这为构建更复杂的模型奠定了基础。