人間は「猫の写真」を見て「猫」と認識するのは簡単ですが、それを計算機に教えるのは大変です。「そういう感覚的に当たり前だけど説明するのは難しい」ということを示せたのがディープラーニングだと私は理解しています。
人間の感覚にとっては当たり前のことも、客観的に示すのが難しいことは世の中いっぱいあると思います。今回の「オシロいるの?いらないの?」問題もそんな「問い」だと思います。というわけでRNNがうまく答えを出してくれたんじゃないかと思っています。
コードはこちら(時間ありで学習するコード)
# ゼロから作る Deep Learning2のP216、第5章「5.5.3 RNNLMの学習コード」でコード全体が見えるようにできるだけ「import」を外した
# オシロいるの?いらないの?検討用コード
# coding: utf-8
# import sys
# sys.path.append('C:\\...\\')
import matplotlib.pyplot as plt
import numpy as np
# from common.optimizer import SGD
# from dataset import ptb # このimportを有効にするには上記パス設定「sys.path.append('C:\\kojin\\AI関連\\・・・」が必要!
# from simple_rnnlm import SimpleRnnlm
np.random.seed(seed=256) # 発生する乱数を固定する(256)
# ハイパーパラメータの設定
batch_size = 8
time_size = 4 # Truncated BPTTの展開する時間サイズ
n_in = 5 # 入力層のニューロン数
n_mid = 30 # 中間層のニューロン数
n_out = 1 # 出力層のニューロン数
# できるだけオリジナルのコードに変更を加えないため、既存の変数に代入する
vocab_size = n_out
wordvec_size = n_in
hidden_size = n_mid
lr = 0.005
max_epoch = 101
# 学習データの読み込み
# -------------------PANDASのインポートとCSVファイルの読み込み------------------------------------
import pandas as pd # PANDASのインポート
df = pd.read_csv("D:\\kojin\\資料\\AI関連\\DATA\\DATA_for_OSC_check.csv") # CSVファイルの読み込み
xcol = ['Time','DATA_A', 'DATA_B', 'DATA_C', 'DATA_D'] # 時間をパラメータに加えることが重要
tcol = ['DATA_E']
# -- 訓練データの作成 --
x_data = np.array(df[xcol])
t_data = np.array(df[tcol])
#------------------------------------------------------------------------------------------------
xs = x_data[:-1] # 入力
ts = t_data[1:] # 出力(教師ラベル)
data_size = len(xs)
#///////////////////RNNに対応した「time_size」行列の学習用データを作成 開始部分/////////////////////////
x_time = np.empty((data_size - time_size, time_size, wordvec_size), dtype='f')
t_time = np.empty((data_size - time_size, time_size, vocab_size), dtype='f')
for i in range(data_size - time_size):
for j in range(time_size):
x_time[i, j, :] = xs[i + j]
t_time[i, j, :] = ts[i + j]
#///////////////////RNNに対応した「time_size」行列の学習用データを作成 終了部分/////////////////////////
# 学習時に使用する変数
# max_iters = data_size // (batch_size * time_size)
max_iters = data_size // batch_size # SIN波学習のデータ量として、「time_size」で割ってしまうと足りなくなる
time_idx = 0
total_loss = 0
loss_count = 0
ppl_list = []
# ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# できるだけimportを外すため、classをコピペした箇所の「開始」部分
# ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# GPUを定義しておく(コードのどこかでこの定義を参照しているらしいけど、PCにNVIDIA無いので、下記定義をするだけ)
GPU = False
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# optimizer.py の抜粋「開始」部分
# ---------------------------------------------------------------------------------------------------------------------------
class SGD:
'''
確率的勾配降下法(Stochastic Gradient Descent)
'''
def __init__(self, lr=0.01):
self.lr = lr
def update(self, params, grads):
for i in range(len(params)):
params[i] -= self.lr * grads[i]
# ---------------------------------------------------------------------------------------------------------------------------
# optimizer.py の抜粋「終了」部分
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# time_layers.py の抜粋「開始」部分
# ---------------------------------------------------------------------------------------------------------------------------
class TimeAffine:
def __init__(self, W, b):
self.params = [W, b]
self.grads = [np.zeros_like(W), np.zeros_like(b)]
self.x = None
def forward(self, x):
N, T, D = x.shape
W, b = self.params
rx = x.reshape(N*T, -1)
out = np.dot(rx, W) + b
self.x = x
return out.reshape(N, T, -1)
def backward(self, dout):
x = self.x
N, T, D = x.shape
W, b = self.params
dout = dout.reshape(N*T, -1)
rx = x.reshape(N*T, -1)
db = np.sum(dout, axis=0)
dW = np.dot(rx.T, dout)
dx = np.dot(dout, W.T)
dx = dx.reshape(*x.shape)
self.grads[0][...] = dW
self.grads[1][...] = db
return dx
class RNN:
def __init__(self, Wx, Wh, b):
self.params = [Wx, Wh, b]
self.grads = [np.zeros_like(Wx), np.zeros_like(Wh), np.zeros_like(b)]
self.cache = None
def forward(self, x, h_prev):
Wx, Wh, b = self.params
t = np.dot(h_prev, Wh) + np.dot(x, Wx) + b
h_next = np.tanh(t)
self.cache = (x, h_prev, h_next)
return h_next
def backward(self, dh_next):
Wx, Wh, b = self.params
x, h_prev, h_next = self.cache
dt = dh_next * (1 - h_next ** 2)
db = np.sum(dt, axis=0)
dWh = np.dot(h_prev.T, dt)
dh_prev = np.dot(dt, Wh.T)
dWx = np.dot(x.T, dt)
dx = np.dot(dt, Wx.T)
self.grads[0][...] = dWx
self.grads[1][...] = dWh
self.grads[2][...] = db
return dx, dh_prev
class TimeRNN:
def __init__(self, Wx, Wh, b, stateful=False):
self.params = [Wx, Wh, b]
self.grads = [np.zeros_like(Wx), np.zeros_like(Wh), np.zeros_like(b)]
self.layers = None
self.h, self.dh = None, None
self.stateful = stateful
def forward(self, xs):
Wx, Wh, b = self.params
N, T, D = xs.shape
D, H = Wx.shape
self.layers = []
hs = np.empty((N, T, H), dtype='f')
if not self.stateful or self.h is None:
self.h = np.zeros((N, H), dtype='f')
for t in range(T):
layer = RNN(*self.params)
self.h = layer.forward(xs[:, t, :], self.h)
hs[:, t, :] = self.h
self.layers.append(layer)
return hs
def backward(self, dhs):
Wx, Wh, b = self.params
N, T, H = dhs.shape
D, H = Wx.shape
dxs = np.empty((N, T, D), dtype='f')
dh = 0
grads = [0, 0, 0]
for t in reversed(range(T)):
layer = self.layers[t]
dx, dh = layer.backward(dhs[:, t, :] + dh)
dxs[:, t, :] = dx
for i, grad in enumerate(layer.grads):
grads[i] += grad
for i, grad in enumerate(grads):
self.grads[i][...] = grad
self.dh = dh
return dxs
def set_state(self, h):
self.h = h
def reset_state(self):
self.h = None
class TimeOutputWithLoss:
# このコードは「class TimeSoftmaxWithLoss」の代わりに実装する
def __init__(self):
self.cache = None
def forward(self, xs, ts):
N, T, D = xs.shape # ここでDは1
# RNNのタイプに合わせて「#1」か「#2」を選択する
# # ------------------RNN many to many start---------------#1
# loss = 0.5 * np.sum((xs - ts)**2) #1
# loss /= N # 1データ分での誤差 #1
# # -------------------RNN many to many end----------------#1
# ------------------RNN many to one start----------------#2
loss = 0.5 * np.sum((xs[:, T-1, :] - ts[:, T-1, :])**2) #2
loss /= N # 1データ分での誤差 #2
# -------------------RNN many to one end-----------------#2
self.cache = (ts, xs, (N, T, D))
return loss
def backward(self, dout=1):
ts, xs, (N, T, D) = self.cache
# RNNのタイプに合わせて「#1」か「#2」を選択する
# # ------------------RNN many to many start---------------#1
# dout = xs - ts #1
# dout /= N #1
# # -------------------RNN many to many end----------------#1
# ------------------RNN many to one start----------------#2
dout = np.zeros([N, T, D], dtype='float') #2
dout[:, T-1, :] = xs[:, T-1, :] - ts[:, T-1, :] #2
# -------------------RNN many to one end-----------------#2
return dout
# ---------------------------------------------------------------------------------------------------------------------------
# time_layers.py の抜粋「終了」部分
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# simple_rnnlm.py の抜粋「開始」部分
# ---------------------------------------------------------------------------------------------------------------------------
class SimpleRnnlm:
def __init__(self, vocab_size, wordvec_size, hidden_size):
V, D, H = vocab_size, wordvec_size, hidden_size
rn = np.random.randn
# 重みの初期化
# embed_W = (rn(V, D) / 100).astype('f') # embedingレイヤは無効にする
rnn_Wx = (rn(D, H) / np.sqrt(D)).astype('f')
rnn_Wh = (rn(H, H) / np.sqrt(H)).astype('f')
rnn_b = np.zeros(H).astype('f')
affine_W = (rn(H, V) / np.sqrt(H)).astype('f')
affine_b = np.zeros(V).astype('f')
# レイヤの生成
self.layers = [
# TimeEmbedding(embed_W), # embedingレイヤは無効にする
TimeRNN(rnn_Wx, rnn_Wh, rnn_b, stateful=True),
TimeAffine(affine_W, affine_b)
# Simple_TimeAffine(affine_W, affine_b)
]
# self.loss_layer = TimeSoftmaxWithLoss() # TimeSoftmaxWithLossレイヤは無効にする
self.loss_layer = TimeOutputWithLoss()
self.rnn_layer = self.layers[0] # 「TimeEmbedding」を外したので「TimeRNN」を「self.rnn_layer」にするため「self.layers[1]」を「self.layers[0]」にした
# すべての重みと勾配をリストにまとめる
self.params, self.grads = [], []
for layer in self.layers:
self.params += layer.params
self.grads += layer.grads
#------オリジナルコードに予測(predict)が無いので、LSTMのコードから持ってくる------
def predict(self, xs):
for layer in self.layers:
xs = layer.forward(xs)
return xs
def forward(self, xs, ts):
for layer in self.layers:
xs = layer.forward(xs)
loss = self.loss_layer.forward(xs, ts)
return loss
def backward(self, dout=1):
dout = self.loss_layer.backward(dout)
for layer in reversed(self.layers):
dout = layer.backward(dout)
return dout
def reset_state(self):
self.rnn_layer.reset_state()
# ---------------------------------------------------------------------------------------------------------------------------
# simple_rnnlm.py の抜粋「終了」部分
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# できるだけimportを外すため、classをコピペした箇所の「終了」部分
# ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# モデルの生成
model = SimpleRnnlm(vocab_size, wordvec_size, hidden_size)
optimizer = SGD(lr)
# ミニバッチの各サンプルの読み込み開始位置を計算
# jump = (corpus_size - 1) // batch_size
# offset = [i * jump for i in range(batch_size)]
for epoch in range(max_epoch):
#---「common」の「trainer.py」から「class Trainer」よりデータをシャッフルする部分を抜粋---
time_idx = 0 # インデックス追加部分
# シャッフル
idx = np.random.permutation(np.arange(data_size - time_size))
x_shuffle = x_time[idx, ]
t_shuffle = t_time[idx, ]
#-----------------------------------------------------------------------------------
# /////////////////////////////////////////////////////////////////////////////////////////////////////////
for iter in range(max_iters - 1):
# ミニバッチの取得
batch_x = np.empty((batch_size, time_size, wordvec_size), dtype='f')
batch_t = np.empty((batch_size, time_size, vocab_size), dtype='f')
for i in range(batch_size):
batch_x[i, :, :] = x_shuffle[time_idx + i, ]
batch_t[i, :, :] = t_shuffle[time_idx + i, ]
time_idx += batch_size
# /////////////////////////////////////////////////////////////////////////////////////////////////////////
# 勾配を求め、パラメータを更新
loss = model.forward(batch_x, batch_t)
model.backward()
optimizer.update(model.params, model.grads)
total_loss += loss
loss_count += 1
# エポックごとにパープレキシティの評価 「パープレキシティ」はここでは「ロス」として扱う
# ppl = np.exp(total_loss / loss_count)
ppl = total_loss
# print('| epoch %d | perplexity %.2f'
# % (epoch+1, ppl))
ppl_list.append(float(ppl))
total_loss, loss_count = 0, 0
#----------------予測部分開始-------------------------------------
# -- 予測 --
# 順伝播 RNN層
x_predicted = np.empty((data_size - time_size, vocab_size), dtype='f')
x_predict = xs[:]
y_predict = np.empty((batch_size, time_size, vocab_size), dtype='f')
pred_batch_x = np.empty((batch_size, time_size, wordvec_size), dtype='f')
# batch_x = np.empty((batch_size, time_size, wordvec_size), dtype='f')
# 「batch_size」 ありきでコードが組まれているので、入力データを「batch_size」分、重複させて作る
for j in range(data_size - time_size):
for t in range(time_size):
for i in range(batch_size):
pred_batch_x[i, t, :] = x_predict[j + t, ] # データは時系列に作成、「batch_size」分、重複させている
y_predict = model.predict(pred_batch_x)
x_predicted[j] = y_predict[0, time_size-1, 0]
#-----------------予測部分終了------------------------------------
# グラフの描画 誤差の表示部分
x = np.arange(len(ppl_list))
plt.plot(x, ppl_list, label='train')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.show()
# グラフの描画 学習結果の波形パターンの一致度合いを表示
td = ts.reshape(-1)
x = np.arange(len(td))
plt.plot(x, td, x_predicted, label='train')
plt.xlabel('epochs')
plt.ylabel('DATA_E')
plt.show()
時間なしで学習するコードは、上の時間あり学習コードで、下のこの部分を入れ替えてください
n_in = 4 # 入力層のニューロン数
n_mid = 30 # 中間層のニューロン数
n_out = 1 # 出力層のニューロン数
# できるだけオリジナルのコードに変更を加えないため、既存の変数に代入する
vocab_size = n_out
wordvec_size = n_in
hidden_size = n_mid
lr = 0.005
max_epoch = 101
# 学習データの読み込み
# -------------------PANDASのインポートとCSVファイルの読み込み------------------------------------
import pandas as pd # PANDASのインポート
df = pd.read_csv("D:\\kojin\\資料\\AI関連\\DATA\\DATA_for_OSC_check.csv") # CSVファイルの読み込み
xcol = ['DATA_A', 'DATA_B', 'DATA_C', 'DATA_D'] # 時間をパラメータに加えることが重要
tcol = ['DATA_E']
書き換えるところは2行だけなのですが、この方が分かりやすいですよね?
CSVファイルのパスは試してみたい方のPC環境に合わせてください。
またCSVファイル自体は
ここから取得してください。
中身はこんな感じになっています。
ディープラーニングの活用事例はほとんど企業のもので、
ヘビーなものばっかり!
個人じゃとてもまねできません!
といった感じのものがほとんどじゃないかと感じています。個人の活用事例は、いまのところ見つけられていません。
なので、こんな活用事例もちょっと面白くないですか?
RNNに関しては一応ここまでです。次はLSTMについてです。
以上です。
コメント
コメントを投稿