AutoEncoder(自编码:以Mnist数据集为例)

本例以pytorch框架进行实验:

#coding = utf-8
import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import torch.optim as optim
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np
from torch.autograd import Variable

# torch.manual_seed(1)    # reproducible

# Hyper Parameters
EPOCH = 5
BATCH_SIZE = 64
LR = 0.001         # learning rate
DOWNLOAD_MNIST = True
N_TEST_IMG = 5

# Mnist digits dataset
train_data = torchvision.datasets.MNIST(
    root='./mnist_data/',
    train=True,                                     # this is training data
    transform=torchvision.transforms.ToTensor(),    # Converts a PIL.Image or numpy.ndarray to
                                                    # torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]
    download=DOWNLOAD_MNIST,                        # download it if
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用PyTorch实现自编码器提取数据集特征的示例代码: ```python import torch import torch.nn as nn from torch.utils.data import DataLoader from torchvision.datasets import MNIST from torchvision.transforms import ToTensor from tqdm import tqdm # 定义自编码器模型 class Autoencoder(nn.Module): def __init__(self): super(Autoencoder, self).__init__() # 编码器 self.encoder = nn.Sequential( nn.Conv2d(1, 16, 3, stride=3, padding=1), # 16x10x10 nn.ReLU(inplace=True), nn.Conv2d(16, 8, 3, stride=2, padding=1), # 8x5x5 nn.ReLU(inplace=True), nn.Conv2d(8, 4, 2, stride=1, padding=0), # 4x4x4 nn.ReLU(inplace=True), ) # 解码器 self.decoder = nn.Sequential( nn.ConvTranspose2d(4, 8, 2, stride=1, padding=0), # 8x5x5 nn.ReLU(inplace=True), nn.ConvTranspose2d(8, 16, 3, stride=2, padding=1, output_padding=1), # 16x10x10 nn.ReLU(inplace=True), nn.ConvTranspose2d(16, 1, 3, stride=3, padding=1), # 1x28x28 nn.Sigmoid(), ) def forward(self, x): x = self.encoder(x) x = self.decoder(x) return x # 加载MNIST数据集 train_dataset = MNIST(root='data/', train=True, transform=ToTensor(), download=True) train_loader = DataLoader(train_dataset, batch_size=128, shuffle=True) # 初始化自编码器模型 model = Autoencoder() # 定义优化器 optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) # 训练自编码器 num_epochs = 10 for epoch in range(num_epochs): for data in tqdm(train_loader): img, _ = data optimizer.zero_grad() output = model(img) loss = nn.MSELoss()(output, img) loss.backward() optimizer.step() # 提取特征 feature_extractor = nn.Sequential(model.encoder, nn.Flatten()) features = [] with torch.no_grad(): for data in tqdm(train_loader): img, _ = data feature = feature_extractor(img) features.append(feature) features = torch.cat(features, dim=0) ``` 这里使用了一个简单的自编码器作为特征提取器,将MNIST手写数字数据集的图像转换为4x4x4的特征向量。训练自编码器时使用均方误差损失函数,优化器为Adam。最后使用训练好的自编码器的编码器部分来提取特征,将特征向量展平为一维向量。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值