首页 > 其他分享 >PyTorch实现堆叠自编码器

PyTorch实现堆叠自编码器

时间:2023-04-19 17:40:50浏览次数:35  
标签:编码器 self 堆叠 dims PyTorch test hidden data model

以下是一个使用PyTorch实现堆叠自编码器的示例代码,该代码包括三个自编码器和一些辅助函数,用于训练和测试堆叠自编码器。

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import numpy as np
import matplotlib.pyplot as plt

# Define the Stacked Autoencoder class
class StackedAutoencoder(nn.Module):
    def __init__(self, input_dim, hidden_dims):
        super(StackedAutoencoder, self).__init__()
        self.input_dim = input_dim
        self.hidden_dims = hidden_dims
        
        # Define the encoder layers
        self.encoder1 = nn.Linear(input_dim, hidden_dims[0])
        self.encoder2 = nn.Linear(hidden_dims[0], hidden_dims[1])
        self.encoder3 = nn.Linear(hidden_dims[1], hidden_dims[2])
        
        # Define the decoder layers
        self.decoder3 = nn.Linear(hidden_dims[2], hidden_dims[1])
        self.decoder2 = nn.Linear(hidden_dims[1], hidden_dims[0])
        self.decoder1 = nn.Linear(hidden_dims[0], input_dim)
        
        # Define the activation function
        self.activation = nn.ReLU()
        
    def encoder(self, x):
        z1 = self.activation(self.encoder1(x))
        z2 = self.activation(self.encoder2(z1))
        z3 = self.activation(self.encoder3(z2))
        return z3
    
    def decoder(self, z):
        xhat3 = self.activation(self.decoder3(z))
        xhat2 = self.activation(self.decoder2(xhat3))
        xhat1 = self.decoder1(xhat2)
        return xhat1
    
    def forward(self, x):
        z = self.encoder(x)
        xhat = self.decoder(z)
        return xhat
    
    def get_encoder_output(self, x):
        return self.encoder(x)

# Define the training function
def train(model, train_loader, num_epochs, learning_rate):
    # Define the loss function and optimizer
    criterion = nn.MSELoss()
    optimizer = optim.Adam(model.parameters(), lr=learning_rate)
    
    # Train the model
    for epoch in range(num_epochs):
        for data in train_loader:
            # Get the input data and target data
            inputs, targets = data
            inputs, targets = inputs.view(-1, 28*28), targets.view(-1, 28*28)
            
            # Zero the gradients
            optimizer.zero_grad()
            
            # Forward pass
            outputs = model(inputs)
            loss = criterion(outputs, targets)
            
            # Backward pass and optimization
            loss.backward()
            optimizer.step()
        
        # Print the loss after each epoch
        print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))

# Define the test function
def test(model, test_loader):
    # Define the loss function
    criterion = nn.MSELoss()
    
    # Evaluate the model
    test_loss = 0
    with torch.no_grad():
        for data in test_loader:
            # Get the input data and target data
            inputs, targets = data
            inputs, targets = inputs.view(-1, 28*28), targets.view(-1, 28*28)
            
            # Forward pass
            outputs = model(inputs)
            test_loss += criterion(outputs, targets).item()
    
    # Print the average test loss
    test_loss /= len(test_loader.dataset)
    print('Average Test Loss: {:.4f}'.format(test_loss))


主程序

# Define the main function
def main():
    # Set the device
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    
    # Set the hyperparameters
    input_dim = 28*28
    hidden_dims = [256, 128, 64]
    num_epochs = 10
    batch_size = 128
    learning_rate = 0.001
    
    # Download the MNIST dataset and create data loaders
    train_dataset = datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
    test_dataset = datasets.MNIST(root='./data', train=False, transform=transforms.ToTensor(), download=True)
    train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
    test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
    
    # Create the Stacked Autoencoder model and move it to the device
    model = StackedAutoencoder(input_dim, hidden_dims).to(device)
    
    # Train the model
    train(model, train_loader, num_epochs, learning_rate)
    
    # Test the model
    test(model, test_loader)
    
    # Generate a random image and its reconstruction
    with torch.no_grad():
        z = torch.randn(1, hidden_dims[-1]).to(device)
        xhat = model.decoder(z)
        xhat = xhat.view(28, 28).cpu().numpy()
        plt.imshow(xhat, cmap='gray')
        plt.show()

if __name__ == '__main__':
    main()

main() 函数中,首先设置了设备,然后定义了超参数,接着下载 MNIST 数据集并创建数据加载器。然后创建了堆叠自编码器模型,并将其移动到设备上。接下来调用 train() 函数进行训练,然后调用 test() 函数进行测试。最后生成一个随机图像并进行重构,然后显示出来。

train() 函数中,定义了损失函数和优化器,然后对模型进行了训练。在 test() 函数中,定义了损失函数,并对模型进行了测试。

test() 函数中,定义了损失函数,并对模型进行了测试。测试过程与训练过程类似,但是不需要进行梯度更新。最后返回测试损失的平均值。

标签:编码器,self,堆叠,dims,PyTorch,test,hidden,data,model
From: https://blog.51cto.com/guog/6207005

相关文章

  • PyTorch实现联邦学习堆叠自编码器
    联邦学习是一种用于训练分布在不同设备或地点的模型的技术,其中数据分布在不同的设备上,且不会离开设备。每个设备只训练其本地数据的模型,并将更新的模型参数传递给服务器,服务器对这些更新进行聚合以更新全局模型。由于不共享原始数据,因此联邦学习能够提供更好的数据隐私和安全性......
  • 深度学习-Pytorch常见的数据类型
    深度学习-Pytorch常见的数据类型数据类型认识首先,python与PyTorch中的数据类型pythonPyTorchintIntTensorfloatFloatTensorintarrayIntTensorsize[d1,d2,...]floatarrayFloatTensorsize[d1,d2,...]string无在PyTorch中表达String:one-hot即......
  • PyTorch 深度学习实用指南:1~5
    原文:PyTorchDeepLearningHands-On协议:CCBY-NC-SA4.0译者:飞龙本文来自【ApacheCN深度学习译文集】,采用译后编辑(MTPE)流程来尽可能提升效率。不要担心自己的形象,只关心如何实现目标。——《原则》,生活原则2.3.c一、深度学习演练和PyTorch简介目前,有数十种深度学习......
  • ffmpeg可支持的编码器、解码器、封装格式、网络协议
    {ffmpeg可支持的编码器./configure--list-encodersffmpeg可支持的解码器./configure--list-decodersffmpeg可支持的封装格式./configure--list-muxersffmpeg可支持的解封装格式./configure--list-demuxersffmpeg可支持的网络协议./configure--list-protocols查看......
  • pytorch
    pytorch环境配置CUDA版本查询打开NVIDIAControlPanel应用程序菜单栏-帮助-系统信息-组件在如图所示位置查看CUDA版本前置配件anacondaCUDAToolKit安装方法看官网即可(建议使用pip安装)更新中。。。......
  • Pytorch实现分类器
    本文实现两个分类器:softmax分类器和感知机分类器Softmax分类器Softmax分类是一种常用的多类别分类算法,它可以将输入数据映射到一个概率分布上。Softmax分类首先将输入数据通过线性变换得到一个向量,然后将向量中的每个元素进行指数函数运算,最后将指数运算结果归一化得到一个概......
  • 李宏毅机器学习——pytorch
    什么是pytorchpython机器学习框架,Facebook提出,主要有一下两个特点使用GPU加速高维矩阵的运算torch.cuda.is_available()x=x.to('cuda')可以很方便的实现梯度的计算requires_grad=True指定需要对变量x计算梯度z是x的函数,调用z.backward()反向传播计算梯度x.grad属性......
  • 深度学习Pytorch中组卷积的参数存储方式与剪枝的问题
    写这个主要是因为去年做项目的时候需要对网络进行剪枝普通卷积倒没问题涉及到组卷积通道的裁剪就对应不上当时没时间钻研现在再看pytorch钻研了一下仔细研究了一下卷积的weight.data的存储1.搭建网络这里先随便搭建一下网络放几个深度可分离卷积和普通卷积import......
  • 第二章(4)Pytorch安装和张量创建
    第二章(4)Pytorch安装和张量创建1.Pytorch基础PyTorch是一个基于Python的科学计算库,也是目前深度学习领域中最流行的深度学习框架之一。PyTorch的核心理念是张量计算,即将数据表示为张量,在计算时使用自动微分机制优化模型。在使用PyTorch进行深度学习时,了解张量的基础操作、类型、......
  • 25-组合逻辑集成电路-编码器
    编码器组合逻辑集成电路(MSI)组合电路使用小规模电路设计,描述清楚,用小规模的集成电路实现;小规模集成电路比较灵活常用的部件(译码器\编码器\比较器\选择器)都是事先做好,直接进行使用1.编码器概念及分类1.1编码器的概念编码器:使用一组二进制数表示一个数值或者是符号。例......