使用pytorch实现前馈神经网络

使用pytorch实现前馈神经网络

前馈神经网络

前馈神经网络(feedforward neural network,FNN),简称前馈网络,是人工神经网络的一种。前馈神经网络采用一种单向多层结构。其中每一层包含若干个神经元。在此种神经网络中,各神经元可以接收前一层神经元的信号,并产生输出到下一层。第0层叫输入层,最后一层叫输出层,其他中间层叫做隐含层(或隐藏层、隐层)。隐层可以是一层。也可以是多层。
在这里插入图片描述
在这里插入图片描述

MNIST数据集

大多数示例使用手写数字的MNIST数据集[1]。该数据集包含60,000个用于训练的示例和10,000个用于测试的示例。这些数字已经过尺寸标准化并位于图像中心,图像是固定大小(28x28像素),其值为0到10。为简单起见,每个图像都被平展并转换为784(28 * 28)个特征的一维numpy数组。
在这里插入图片描述

代码实现

import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms

# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Hyper-parameters
input_size = 784
hidden_size = 500
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001

# MNIST dataset
train_dataset = torchvision.datasets.MNIST(root='../../data',
                                           train=True,
                                           transform=transforms.ToTensor(),
                                           download=True)

test_dataset = torchvision.datasets.MNIST(root='../../data',
                                          train=False,
                                          transform=transforms.ToTensor())

# Data loader
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=batch_size,
                                           shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
                                          batch_size=batch_size,
                                          shuffle=False)


# Fully connected neural network with one hidden layer
class NeuralNet(nn.Module):
    def __init__(self, input_size, hidden_size, num_classes):
        super(NeuralNet, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_size, num_classes)

    def forward(self, x):
        out = self.fc1(x)
        out = self.relu(out)
        out = self.fc2(out)
        return out


model = NeuralNet(input_size, hidden_size, num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        # Move tensors to the configured device
        images = images.reshape(-1, 28 * 28).to(device)
        labels = labels.to(device)

        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)

        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i + 1) % 100 == 0:
            print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
                  .format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))

# Test the model
# In test phase, we don't need to compute gradients (for memory efficiency)
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.reshape(-1, 28 * 28).to(device)
        labels = labels.to(device)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Accuracy of the network on the 10000 test images: {} %'.format(100 * correct / total))

# Save the model checkpoint
torch.save(model.state_dict(), 'model.ckpt')

结果显示

在这里插入图片描述

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是使用PyTorch实现前馈神经网络近似连续函数的示例代码: ```python import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt # 定义连续函数 def func(x): return np.sin(x) # 生成训练数据 x_train = np.linspace(0, 2*np.pi, 1000) y_train = func(x_train) # 将数据转换为张量 x_train = torch.Tensor(x_train).unsqueeze(1) y_train = torch.Tensor(y_train).unsqueeze(1) # 定义前馈神经网络模型 class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(1, 10) self.fc2 = nn.Linear(10, 10) self.fc3 = nn.Linear(10, 1) self.relu = nn.ReLU() def forward(self, x): x = self.relu(self.fc1(x)) x = self.relu(self.fc2(x)) x = self.fc3(x) return x # 定义训练函数 def train(model, optimizer, criterion, x_train, y_train, epochs): for epoch in range(epochs): optimizer.zero_grad() y_pred = model(x_train) loss = criterion(y_pred, y_train) loss.backward() optimizer.step() if epoch % 100 == 0: print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, epochs, loss.item())) # 初始化模型和优化器 model = Net() criterion = nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.01) # 开始训练 train(model, optimizer, criterion, x_train, y_train, 1000) # 绘制预测结果和原始函数图像 x_test = torch.Tensor(np.linspace(0, 2*np.pi, 1000)).unsqueeze(1) y_pred = model(x_test).detach().numpy() plt.plot(x_train.numpy(), y_train.numpy(), 'o') plt.plot(x_test.numpy(), y_pred, '-') plt.show() ``` 在这个示例中,我们首先定义了一个连续函数,然后使用它生成训练数据。接下来,我们将训练数据转换为PyTorch张量,并定义了一个包含3个全连接层的前馈神经网络模型。我们使用MSELoss作为损失函数,并使用Adam优化器进行优化。最后,我们训练模型,并使用matplotlib绘制了预测结果和原始函数图像。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

毛毛真nice

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值