NumPyでのニューラルネットワーク1の続きです。
前回は、ニューラルネットワークの学習済みパラメタ「重みとバイアス」を使って、その信憑性をテストしました。
今回は、パラメタ「重みとバイアス」をどのように作るか?(学習させるか)の内容です。
1エポック(epoch)で、すべての訓練データデータを参照したこと意味する単位である。 学習においては、この単位ごとに「バイアスと重み」の解を計算させる手法がよく使われる。
一般に、訓練データ,訓練ラベル(訓練用教師ラベル)を使って、パラメタ「重みとバイアス」を探します。
この方法が、最も重要なところですが、ここでは最も基本とされる「確率的勾配降下法(SGD:stochastic grandient descent)」を紹介します。
これは、無造作に選んだパラメタ「重みとバイアス」に対して予想させ、その予想値と訓練ラベルの差の勾配から、より差がなくなるように
パラメタ「重みとバイアス」を修正する繰り返しで行います。
その後、学習で得られたされたパラメタ「重みとバイアス」で、テストデータ,テストラベル(テスト用教師ラベル)を評価して、
前のページ で行ったような信憑性をテストします。
import numpy as np
import pickle
def sigmoid(x):# 活性関数として0から1の滑らかな曲線で活性化させるシグモイド関数の定義
return 1 / (1 + np.exp(-x))
def softmax(a):
c=np.max(a)
exp_a=np.exp(a-c) #オーバフロー対策
sum_exp_a = np.sum( exp_a )
y=exp_a/sum_exp_a
return y
class ForwardProc: # 順方向の伝搬(forward propagation)のニューラルネットワーク推論クラス
def __init__(self):
# 重みとバイアスのパラメタが学習済として、そのpickleで直列化したファイル('weight_bias_params_0.pkl')から復元
with open('weight_bias_params_0.pkl', mode='rb') as fr:
self.params = pickle.load( fr ) # 復元する
def predict(self,x): # 予測関数
W1,W2,W3=self.params['W1'],self.params['W2'],self.params['W3']
b1,b2,b3=self.params['b1'],self.params['b2'],self.params['b3']
a1=np.dot( x , W1 ) + b1
# print(a1.shape) # =============表示結果: (50,)
z1=sigmoid(a1)
a2=np.dot( z1 , W2 ) + b2
# print(a2.shape) # =============表示結果:(100,)
z2=sigmoid(a2)
a3=np.dot( z2 , W3 ) + b3
y = softmax(a3) # 出力層
return y
network=ForwardProc()
print("W1:" , network.params['W1'].shape) # =============表示結果: W1 (784, 50)
print("b1:" , network.params['b1'].shape) # =============表示結果: b1: (50,)
print("W2:" , network.params['W2'].shape) # =============表示結果: W2: (50.100)
print("b2:" , network.params['b2'].shape) # =============表示結果: b2: (100,)
print("W3:" , network.params['W3'].shape) # =============表示結果: W3: (100,10)
print("b3:" , network.params['b3'].shape) # =============表示結果: b3: (10,)
with open('x_train.pkl', mode='rb') as fr:
x_train = pickle.load( fr ) # 訓練用データのオブジェクトを復元する
with open('t_train_a.pkl', mode='rb') as fr:
t_train = pickle.load( fr ) # 訓練用ラベルのオブジェクトを復元する
y = network.predict( x_train[0] )
print("yの出力:", y)
print("tの正解:", t_train[0] )
訓練用データ x_train[0]で得られたyは、次のデータである。
yの出力: [ 1.06677078e-02 1.58301147e-04 4.30344051e-04 2.15528250e-01 5.69069698e-06 7.67599761e-01 3.01648834e-05 3.11577786e-03 1.66547787e-03 7.98536697e-04]上記データは、ソフトマックス関数の出力なので、10個の分類に対するそれぞれを予想する確率の値である。
tの正解: [ 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]この2つの配列から、どれだけ予想が合わないかの損失関数を求める訳です。
def mean_squared_error(y,t):
return 0.5 * np.sum((y-t)**2)
mean_squared_error( y, t_train[0] ) # 結果 0.05029471401664868
この値が小さいので、「重みとバイアスのパラメタ」の設定が適切! のような判定に使う訳です。
def cross_entropy_error(y,t):
delta = 1e-7
return -np.sum( t * np.log(y+delta) )
cross_entropy_error( y, t_train[0] ) # 結果 0.26448667049407959
目安として、出力の正解要素の確率が0.6で-log0.6=0.51、、出力の正解要素の確率が0.1と性能が悪い例で-log0.1=2.3となります。
def cross_entropy_error(y, t): # 交差エントロピー誤差取得
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
# 教師データが one-hot-vector の場合、正解ラベルのインデックスに変換
if t.size == y.size:
t = t.argmax(axis=1)
batch_size = y.shape[0]
return -np.sum(np.log(y[np.arange(batch_size), t])) / batch_size # バッチサイズは、グローバルで与える。
入力層の数、出力層の数、学習率用のハイパーパラメタを引数にして、「重みとバイアスのパラメタ」乱数を設定するコンストラクタ
predict: 上記交差エントロピー誤差を利用して、訓練データの入力のxに対して、,訓練ラベル(訓練用教師ラベル1)の損失を計算し、
import numpy as np
def numerical_gradient(f, x): # 関数fの勾配を、x の勾配を求める
h = 1e-4 # 0.0001
grad = np.zeros_like(x)
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
idx = it.multi_index
tmp_val = x[idx]
x[idx] = float(tmp_val) + h
fxh1 = f(x) # f(x+h)
x[idx] = tmp_val - h
fxh2 = f(x) # f(x-h)
grad[idx] = (fxh1 - fxh2) / (2*h)
x[idx] = tmp_val # 値を元に戻す
it.iternext()
return
# 上記は、TwoLayerNetのnumerical_gradientメソッド定義に使っていたが、高速版では使わない。
def sigmoid(x): # 活性関数として0から1の滑らかな曲線で活性化させるシグモイド関数の定義
return 1 / (1 + np.exp(-x))
def sigmoid_grad(x):
return (1.0 - sigmoid(x)) * sigmoid(x)
def softmax(x):
if x.ndim == 2: # バッチ処理の引数データか?
x = x.T # 転置行列を求る。
x = x - np.max(x, axis=0) # オーバーフロー対策
y = np.exp(x) / np.sum(np.exp(x), axis=0) # axis=0で、内部配列ごとに処理
return y.T
x = x - np.max(x) # オーバーフロー対策
return np.exp(x) / np.sum(np.exp(x))
def cross_entropy_error(y, t): # 交差エントロピー誤差取得
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
# 教師データが one-hot-vector の場合、正解ラベルのインデックスに変換
if t.size == y.size:
t = t.argmax(axis=1)
batch_size = y.shape[0]
return -np.sum(np.log(y[np.arange(batch_size), t])) / batch_size # バッチサイズは、グローバルで与える。
class TwoLayerNet:
# コンストラクタ
def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
# 重みの初期化
self.params = {}
self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)
self.params['b1'] = np.zeros(hidden_size)
self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size)
self.params['b2'] = np.zeros(output_size)
#
# 予測して、各出力層の確率を返す
def predict(self, x):
W1, W2 = self.params['W1'], self.params['W2']
b1, b2 = self.params['b1'], self.params['b2']
a1 = np.dot(x, W1) + b1
z1 = sigmoid(a1)
a2 = np.dot(z1, W2) + b2
y = softmax(a2)
return y
#
# x:入力データ, t:教師データ
def loss(self, x, t):
y = self.predict(x)
return cross_entropy_error(y, t)
#
def accuracy(self, x, t):
y = self.predict(x)
y = np.argmax(y, axis=1)
t = np.argmax(t, axis=1)
accuracy = np.sum(y == t) / float(x.shape[0])
return accuracy
#
# 次のメソッドはこのリンクで作成したnumerical_gradientを利用するもので、使っていない。
def numerical_gradient(self, x, t):# x:入力データ, t:教師データ 損失との勾配を求める。
loss_W = lambda W: self.loss(x, t)
grads = {}
grads['W1'] = numerical_gradient(loss_W, self.params['W1'])
grads['b1'] = numerical_gradient(loss_W, self.params['b1'])
grads['W2'] = numerical_gradient(loss_W, self.params['W2'])
grads['b2'] = numerical_gradient(loss_W, self.params['b2'])
return grads
# 以上は、下記高速版を作成する過程で作成したが、以降のソースでは削除の予定
#
def gradient(self, x, t): # x:入力データ, t:教師データ 損失との勾配を求める。(上記の処理を、このクラス専用で作った高速版)
W1, W2 = self.params['W1'], self.params['W2']
b1, b2 = self.params['b1'], self.params['b2']
grads = {}
batch_num = x.shape[0]
# forward
a1 = np.dot(x, W1) + b1
z1 = sigmoid(a1)
a2 = np.dot(z1, W2) + b2
y = softmax(a2)
# backward
dy = (y - t) / batch_num
grads['W2'] = np.dot(z1.T, dy)
grads['b2'] = np.sum(dy, axis=0)
#
da1 = np.dot(dy, W2.T)
dz1 = sigmoid_grad(a1) * da1
grads['W1'] = np.dot(x.T, dz1)
grads['b1'] = np.sum(dz1, axis=0)
return grads
import pickle
import numpy as np
import matplotlib.pyplot as plt
# 訓練用データの読み込み
with open('x_train.pkl', mode='rb') as fr: # 1つが[784]byteという入力データが、複数並ぶ訓練データを取得
x_train=pickle.load( fr)
with open('t_train_a.pkl', mode='rb') as fr: # 上記の並びに対応する教師ラベル(1つがone-hot表現で10個の出力)が、複数並ぶ訓練データを取得
t_train=pickle.load( fr)
train_size = x_train.shape[0] # 訓練データサイズ:60000
train_size = 10000
train_size = 1000
train_size = 100
network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)#学習用のニューラルネットワーク生成
batch_size = 100
batch_size = 10
learning_rate = 0.1 # 学習率
iters_num = 10000 # 勾配法の算出繰り返しの回数
iters_num = 1000 # 勾配法の算出繰り返しの回数
train_loss_list = [] #予測と(訓練用教師ラベル)の損失
for i in range(iters_num):
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask] # batch_maskの添え字群で指定される訓練データ群を抽出
t_batch = t_train[batch_mask] # batch_maskの添え字群で指定される訓練データ群の訓練ラベル(訓練用教師ラベル)を抽出
# 勾配の計算
# grad = network.numerical_gradient(x_batch, t_batch) # コメントアウトして、新たに作った次の高速版を使う
grad = network.gradient(x_batch, t_batch)
# 「重みとバイアスのパラメタ」を更新
for key in ('W1', 'b1', 'W2', 'b2'):
network.params[key] -= learning_rate * grad[key]
loss = network.loss(x_batch, t_batch)
print(i, ":", loss)
train_loss_list.append(loss)
plt.figure() # 2次元の図を初期化「1つshow()の前に必要」
plt.plot(np.arange(len(train_loss_list)),np.array(train_loss_list), label="回数")
print("訓練データ数:", train_size);
print("バッチ数:", batch_size);
print("計算回数:", iters_num);
plt.show()
import pickle
# データの読み込み
with open('x_train.pkl', mode='rb') as fr:
x_train=pickle.load( fr)
with open('t_train_a.pkl', mode='rb') as fr:
t_train=pickle.load( fr)
with open('x_test.pkl', mode='rb') as fr:
x_test=pickle.load( fr)
with open('t_test_a.pkl', mode='rb') as fr:
t_test=pickle.load( fr)
network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)
iters_num = 10000 # 繰り返しの回数を適宜設定する
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1
train_loss_list = []
train_acc_list = []
test_acc_list = []
iter_per_epoch = max(train_size / batch_size, 1)
for i in range(iters_num):
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask]
# 勾配の計算
#grad = network.numerical_gradient(x_batch, t_batch)
grad = network.gradient(x_batch, t_batch)
# パラメータの更新
for key in ('W1', 'b1', 'W2', 'b2'):
network.params[key] -= learning_rate * grad[key]
loss = network.loss(x_batch, t_batch)
train_loss_list.append(loss)
if i % iter_per_epoch == 0:
train_acc = network.accuracy(x_train, t_train)
test_acc = network.accuracy(x_test, t_test)
train_acc_list.append(train_acc)
test_acc_list.append(test_acc)
print("train acc, test acc | " + str(train_acc) + ", " + str(test_acc))
# グラフの描画
import matplotlib.pyplot as plt
markers = {'train': 'o', 'test': 's'}
x = np.arange(len(train_acc_list))
plt.plot(x, train_acc_list, label='train acc')
plt.plot(x, test_acc_list, label='test acc', linestyle='--')
plt.xlabel("epochs")
plt.ylabel("accuracy")
plt.ylim(0, 1.0)
plt.legend(loc='lower right')
plt.show()