AutoEncoder 自編碼

AutoEncoder是極為重要的一類神經(jīng)網(wǎng)絡(luò),可用于優(yōu)化搜索引擎,數(shù)據(jù)分類,語(yǔ)義識(shí)別等多種任務(wù),本文開(kāi)始學(xué)習(xí)這一神經(jīng)網(wǎng)絡(luò)

1. 準(zhǔn)備數(shù)據(jù)和超參數(shù)

import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np


# torch.manual_seed(1)    # reproducible

# Hyper Parameters
EPOCH = 10
BATCH_SIZE = 64
LR = 0.005         # learning rate
DOWNLOAD_MNIST = False
N_TEST_IMG = 5

# Mnist digits dataset
train_data = torchvision.datasets.MNIST(
    root='./mnist/',
    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 you don't have it
)

2. 預(yù)覽和裝載數(shù)據(jù)

# plot one example
print(train_data.train_data.size())     # (60000, 28, 28)
print(train_data.train_labels.size())   # (60000)
plt.imshow(train_data.train_data[2].numpy(), cmap='gray')
plt.title('%i' % train_data.train_labels[2])
plt.show()

# DataLoader for easy mini-batch return in training the image batch shape will be (50, 1, 28, 28)
train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)

3. 構(gòu)建自編碼器

class AutoEncoder(nn.Module):
    def __init__(self):
        super(AutoEncoder, self).__init__()

        self.encoder = nn.Sequential(
            nn.Linear(28*28, 128),
            nn.Tanh(),
            nn.Linear(128, 64),
            nn.Tanh(),
            nn.Linear(64, 12),
            nn.Tanh(),
            nn.Linear(12, 3),   # compress to 3 features which can be visualized in plt
        )
        self.decoder = nn.Sequential(
            nn.Linear(3, 12),
            nn.Tanh(),
            nn.Linear(12, 64),
            nn.Tanh(),
            nn.Linear(64, 128),
            nn.Tanh(),
            nn.Linear(128, 28*28),
            nn.Sigmoid(),       # compress to a range (0, 1)
        )

    def forward(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return encoded, decoded


autoencoder = AutoEncoder()

注:

  1. AutoEncoder是通過(guò)多層全連接網(wǎng)絡(luò)和激活函數(shù)將輸入結(jié)果轉(zhuǎn)變?yōu)榈途S變量,再通過(guò)反向過(guò)程將該變量轉(zhuǎn)化為高維結(jié)果,而中間的低維變量即為編碼結(jié)果
  2. 構(gòu)建前向傳播過(guò)程時(shí),需要連接編碼和解碼過(guò)程

4. 選擇優(yōu)化器和損失函數(shù)

optimizer = torch.optim.Adam(autoencoder.parameters(), lr=LR)
loss_func = nn.MSELoss()

5. 初始化plt圖像

# initialize figure
f, a = plt.subplots(2, N_TEST_IMG, figsize=(5, 2))
plt.ion()   # continuously plot

# original data (first row) for viewing
view_data = train_data.train_data[:N_TEST_IMG].view(-1, 28*28).type(torch.FloatTensor)/255.
for i in range(N_TEST_IMG):
    a[0][i].imshow(np.reshape(view_data.data.numpy()[i], (28, 28)), cmap='gray'); a[0][i].set_xticks(()); a[0][i].set_yticks(())

6. 訓(xùn)練和優(yōu)化

for epoch in range(EPOCH):
    for step, (x, b_label) in enumerate(train_loader):
        b_x = x.view(-1, 28*28)   # batch x, shape (batch, 28*28)
        b_y = x.view(-1, 28*28)   # batch y, shape (batch, 28*28)

        encoded, decoded = autoencoder(b_x)

        loss = loss_func(decoded, b_y)      # mean square error
        optimizer.zero_grad()               # clear gradients for this training step
        loss.backward()                     # backpropagation, compute gradients
        optimizer.step()                    # apply gradients

7. 可視化訓(xùn)練過(guò)程與結(jié)果

        if step % 100 == 0:
            print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy())

            # plotting decoded image (second row)
            _, decoded_data = autoencoder(view_data)
            for i in range(N_TEST_IMG):
                a[1][i].clear()
                a[1][i].imshow(np.reshape(decoded_data.data.numpy()[i], (28, 28)), cmap='gray')
                a[1][i].set_xticks(()); a[1][i].set_yticks(())
            plt.draw(); plt.pause(0.05)

plt.ioff()
plt.show()

# visualize in 3D plot
view_data = train_data.train_data[:200].view(-1, 28*28).type(torch.FloatTensor)/255.
encoded_data, _ = autoencoder(view_data)
fig = plt.figure(2); ax = Axes3D(fig)
X, Y, Z = encoded_data.data[:, 0].numpy(), encoded_data.data[:, 1].numpy(), encoded_data.data[:, 2].numpy()
values = train_data.train_labels[:200].numpy()
for x, y, z, s in zip(X, Y, Z, values):
    c = cm.rainbow(int(255*s/9)); ax.text(x, y, z, s, backgroundcolor=c)
ax.set_xlim(X.min(), X.max()); ax.set_ylim(Y.min(), Y.max()); ax.set_zlim(Z.min(), Z.max())
plt.show()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 今天讓我們來(lái)看一下深度學(xué)習(xí)與神經(jīng)網(wǎng)絡(luò)里邊的自編碼. 其實(shí)自編碼嚴(yán)格來(lái)說(shuō)不能算作是深度學(xué)習(xí)的內(nèi)容,我們?cè)谥暗臋C(jī)器學(xué)...
    云時(shí)之間閱讀 8,583評(píng)論 1 5
  • 自編碼,簡(jiǎn)單來(lái)說(shuō)就是把輸入數(shù)據(jù)進(jìn)行一個(gè)壓縮和解壓縮的過(guò)程。 原來(lái)有很多 Feature,壓縮成幾個(gè)來(lái)代表原來(lái)的數(shù)據(jù)...
    Ledestin閱讀 1,717評(píng)論 0 0
  • TensorFlow上實(shí)踐基于自編碼的One Class Learning 異常檢測(cè)算法--Isolation F...
    jiandanjinxin閱讀 7,116評(píng)論 0 10
  • “大雨磅礴的路上只有我一個(gè)人一邊慢吞吞地走 一邊聽(tīng)歌 嘩啦嘩啦 車燈照亮馬路上閃爍的一大片水花 像星星揉碎了落到地...
    滕y閱讀 145評(píng)論 0 0
  • 蜜 春天來(lái)了 蜜蜂 又開(kāi)始 在花朵和蜂巢間 飛來(lái)飛去 是啊 我們也有過(guò) 那樣的日子 你來(lái)找我 我來(lái)找你 帶...
    喜馬ma閱讀 196評(píng)論 0 6

友情鏈接更多精彩內(nèi)容