1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Auto Encoderを用いた異常検知 PART3 (学習)

Last updated at Posted at 2021-01-31

ライブラリのimport

import torch
import torch.utils.data
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
import pickle
from detection_model import autoencoder # 有料

データのロード

with open('normal_data.pkl', 'rb') as f:
	normal_data = pickle.load(f)
with open('anomaly_data.pkl', 'rb') as f:
	anomaly_data = pickle.load(f)

ハイパーパラメータ

Deep Learningのハイパーパラメータを下記のように設定します。

# ハイパーパラメータ
LEARNING_RATE = 0.0001
BATCH_SIZE = 10
EPOCHS = 50

Auto Encoderの訓練データの設定

Auto Encoderで訓練するデータを設定します。

train_data = normal_data[:900]

モデルの設定

model = autoencoder()

特徴表現.jpg

DataSet、DataLoaderの設定

class MyDataSet(torch.utils.data.Dataset):
	def __init__(self, data):

		self.data = data
		self.length = len(data)

	def __len__(self):

		return self.length

	def __getitem__(self, index):

		data = self.data[index]

		return data
		
trainset = MyDataSet(train_data)
trainloader = torch.utils.data.DataLoader(
	trainset, batch_size=BATCH_SIZE, shuffle=True)

損失関数、最適化手法の設定

criterion = nn.MSELoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=LEARNING_RATE)

学習

for epoch in range(EPOCHS):
	print(epoch)
	train_loss = 0
	total = 0
	model.train()
	# cnt = 0
	for data in trainloader:

		optimizer.zero_grad()

		output = model(data[0].float())
		target  = data[0].float()

		loss = criterion(output, target)

		train_loss += loss.item()

		total += data[1].size(0)

		loss.backward()
		optimizer.step()

	train_loss = train_loss / total
	print(f"{train_loss}")

モデルの保存

torch.save(model.state_dict(), "autoencoder.pth")

続き

この続きに興味のある方は、以下のリンクに続きがありますので、よろしくお願いします。
https://zenn.dev/deepblackinc/books/c2181d607d772b

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?