Osomaki67のブログ

個人的な備忘録兼日記にしたいと思います。

AI 事始め16:CS231n:Module 1: Neural Networksの例題

 

 

 

 

Putting it together: Minimal Neural Network Case Study

minimal 2D toy data example : see https://cs231n.github.io/neural-networks-case-study/

自分が理解できるようにコメントを追加していきます。

In [1]:
# A bit of setup
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline
                  # magic command:To enable the inline backend for usage with the IPython Notebook:
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
                  #figsize : tuple of integers, optional, default: None
                  #width, height in inches. If not provided, defaults to rcParams["figure.figsize"] = [6.4, 4.8].
plt.rcParams['image.interpolation'] = 'nearest'
                  #補間の方法を指定します。
                  #   see https://matplotlib.org/gallery/images_contours_and_fields/interpolation_methods.html
                  #   see  http://cyanatlas.hatenablog.com/entry/2018/06/20/144937
plt.rcParams['image.cmap'] = 'gray'   # grayの諧調で表現する
                  #see  https://jp.mathworks.com/help/matlab/ref/colormap.html
                  #https://matplotlib.org/tutorials/colors/colormaps.html?highlight=colormap%20name
# for auto-reloading extenrnal modules
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
                  # magic command:Load an IPython extension by its module name.
%autoreload 2
                  # magic command:Reload all modules (except those excluded by %aimport) 
                  #     every time before executing the Python code typed.
 

線形に分離できない分類データセットを生成します。私たちの好きな例は、次のように生成できるスパイラルデータセットです。

玩具のスパイラルデータは、線形に分離できない3つのクラス(青、赤、黄)で構成されています。

In [2]:
np.random.seed(0)
N = 100 # number of points per class
D = 2   # dimensionality
K = 3   # number of classes
X = np.zeros((N*K,D))
y = np.zeros(N*K, dtype='uint8')
for j in xrange(K):
  ix = range(N*j,N*(j+1))   #サンプル番号 Class0:0-99, class1:100-199, class2:200-299
  r = np.linspace(0.0,1,N) # radius;numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None)
                           # 0から1までを100個に等分した数列を作成する。
  t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta
                           # Class0:0-3, class1:4-7, class2:8-11 を100個に等分し、乱数を加えた数列
  X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]   #多次元配列の結合を行うオブジェクト
  y[ix] = j                #ラベル(正解)
fig = plt.figure()         # Figureのインスタンスを生成
sc=plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)   # 散布図 (Scatter plot) を描く 
                                                                    #色はラベル(正解)の値を使用
          #    x   ,   y    ,色  ,サイズ,カラーマップ
          #                  色0:   色1:   色2: は自動的にアサインされるようだ。カラーマップを表示してみた。  
          #                  カラーマップ       
plt.xlim([-1,1])  # グラフの横軸、縦軸を調整する。
plt.ylim([-1,1])  # グラフの横軸、縦軸を調整する。
plt.colorbar(sc)             #カラーマップを表示してみた。  
#fig.savefig('spiral_raw.png')
Out[2]:
<matplotlib.colorbar.Colorbar at 0xe26c978>
 
 

Softmax線形分類器のトレーニン

次に、これは線形分類器なので、すべてのクラススコアを単一の行列乗算と非常に簡単に並列に計算できます。線形分類器のパラメータは、各クラスの重み行列W、およびバイアスベクトルbです。この例では300の2次元点があるので、この乗算の後に配列のscoresサイズは[300 x 3]になります。各行は3つのクラス(青、赤、黄)に対応するクラススコアを示します。

\( f(x_i,W,b) = Wx_i + b \) ⇒ scores = np.dot(X, W) + b

2番目に重要な要素は、損失関数です。この例ではSoftmax分類器に関連するクロスエントロピー損失を使用できます。

$$L_i=-\log\frac{\mathrm{e}^{f_{y_i}}}{\sum_{j} \mathrm{e}^{f_j}}$$

\( \mathrm{e}^{f_{y_i}} \) ⇒ exp_scores = np.exp(scores) 

\( {\sum_{j} \mathrm{e}^{f_j}} \) ⇒ np.sum(exp_scores, axis=1, keepdims=True)
probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K]

\( L_i \) ⇒ corect_logprobs

Softmax分類器の完全な損失は、トレーニング例と正規化との平均クロスエントロピー損失として定義されることを想起してください。
$$L=\frac{1}{N}\sum_{j}L_i + \frac{1}{2}\lambda\sum_{k}\sum_{l}W_{k,l}^2$$   

\( \frac{1}{N}\sum_{j}L_i \) ⇒ data_loss = np.sum(corect_logprobs)/num_examples

\( \frac{1}{2}\lambda\sum_{k}\sum_{l}W_{k,l}^2 \) ⇒ reg_loss = 0.5*reg*np.sum(W*W)
loss = data_loss + reg_loss
このlossを小さくするために、先に定義したprobsを変数 \(p \) にコピーして、微分値を求める。
$$p_k = \frac{\mathrm{e}^{f_k}}{\sum_j\mathrm{e}^{f_j}} \quad\quad\quad L_i = -\log(p_{y_j})$$


probs ⇒ dscores ⇒ \( p \)     

\( \frac{\partial L_i}{\partial f_k}=p_k - 1\quad(y_i=k) \)      ⇒ dscores[range(num_examples),y] -= 1     

 

 

In [3]:
#Train a Linear Classifier

# initialize parameters randomly
W = 0.01 * np.random.randn(D,K)   # Wのサイズは、(2,3)
b = np.zeros((1,K))               # bのサイズは、(1,3)
     #  X = np.zeros((N*K,D))       Xのサイズは、(1,2)が300個
# some hyperparameters
step_size = 1e-0
reg = 1e-3 # regularization strength; In this code, the regularization strength λ is stored inside the reg. 
           # 正則化過学習を抑えるための重要な手法です。
# gradient descent loop
num_examples = X.shape[0]   # 配列の大きさ
for i in xrange(200):
  
  # evaluate class scores, [N x K] この例では300の2次元点があるので、
  #この乗算の後に配列のscoresサイズは[300 x 3]になります。
  #各行は3つのクラス(青、赤、黄)に対応するクラススコアを示します
  scores = np.dot(X, W) + b #
  
  # compute the class probabilities
  exp_scores = np.exp(scores)
  probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K]
                                         ## axis=1 Compute sum of each row;
    #keepdims=True
    #If this is set to True, the axes which are reduced are left in the result as 
    #dimensions with size one. 
    #With this option, the result will broadcast correctly against the input array.
  # compute the loss: average cross-entropy loss and regularization
  corect_logprobs = -np.log(probs[range(num_examples),y])
  data_loss = np.sum(corect_logprobs)/num_examples
  reg_loss = 0.5*reg*np.sum(W*W)
  loss = data_loss + reg_loss
  if i % 10 == 0:
    print "iteration %d: loss %f" % (i, loss)
  
  # compute the gradient on scores
  dscores = probs
  dscores[range(num_examples),y] -= 1
  dscores /= num_examples
  
  # backpropate the gradient to the parameters (W,b)
  dW = np.dot(X.T, dscores)      #転置行列は行列にTをつけるだけ
  db = np.sum(dscores, axis=0, keepdims=True)
                       # axis=0 Compute sum of each column
  dW += reg*W # regularization gradient
  
  # perform a parameter update
  W += -step_size * dW
  b += -step_size * db
 
iteration 0: loss 1.096919
iteration 10: loss 0.917310
iteration 20: loss 0.851535
iteration 30: loss 0.822352
iteration 40: loss 0.807594
iteration 50: loss 0.799452
iteration 60: loss 0.794683
iteration 70: loss 0.791765
iteration 80: loss 0.789921
iteration 90: loss 0.788726
iteration 100: loss 0.787937
iteration 110: loss 0.787408
iteration 120: loss 0.787049
iteration 130: loss 0.786803
iteration 140: loss 0.786633
iteration 150: loss 0.786514
iteration 160: loss 0.786431
iteration 170: loss 0.786373
iteration 180: loss 0.786331
iteration 190: loss 0.786302
In [4]:
W
Out[4]:
array([[ 1.03370118,  1.10345865, -2.13524878],
       [-2.32943088,  2.71627529, -0.39072902]])
In [5]:
b
In [6]:
# evaluate training set accuracy
scores = np.dot(X, W) + b
predicted_class = np.argmax(scores, axis=1)
               #Returns the indices of the maximum values along an axis.
print 'training accuracy: %.2f' % (np.mean(predicted_class == y))
               #Compute the arithmetic mean along the specified axis.
 
training accuracy: 0.49
In [7]:
# plot the resulting classifier
h = 0.02
         # numpy.ndarray.min(axis = None, out = None)
         # (最小値を求めたい配列).min()の形で使います。
         #  X[:, 0]は、[(先頭から最後まで), 0]       
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
         # numpy.arange([start, ]stop, [step, ]dtype=None)
         # Return evenly spaced values within a given interval.
         # np.arange(x_min, x_max, h)→.....-1.5,-1.48,-1.46......1.46,1.48,1.5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                     np.arange(y_min, y_max, h))
         # Return coordinate matrices from coordinate vectors.
         #     
W
Out[7]:
array([[ 1.03370118,  1.10345865, -2.13524878],
       [-2.32943088,  2.71627529, -0.39072902]])
In [8]:
b
In [9]:
Z = np.dot(np.c_[xx.ravel(), yy.ravel()], W) + b  # xxもyyも描画面をすべて含む巨大な配列なので
         # 一次元のメッシュ配列に並びかえて、
         # メッシュの要素をデータとしてスコアを計算する
Z = np.argmax(Z, axis=1)  #計算したスコアで最大のものを、そのメッシュのクラスにする。
Z = Z.reshape(xx.shape)  # 配列を描画面に合わせて並び替える
fig = plt.figure()
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8) # 等高線と塗りつぶし輪郭を 描きます。
         # contour([X, Y,] Z, [levels], **kwargs)
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)# 散布図 (Scatter plot) を描く 
plt.xlim(xx.min(), xx.max())  # グラフの横軸、縦軸を調整する。
plt.ylim(yy.min(), yy.max())  # グラフの横軸、縦軸を調整する。
plt.colorbar(sc)             #カラーマップを表示してみた。  
#fig.savefig('spiral_linear.png')
Out[9]:
<matplotlib.colorbar.Colorbar at 0xe5f5b38>
 
 

ニューラルネットワークのトレーニング 

#

明らかに、線形分類器はこのデータセットには不十分であり、ニューラルネットワークを使用したいと考えています。このおもちゃのデータには、もう1つの隠れた層で十分です。隠れ層のニューロン数は100個とします。

重要なのは、非線形性を追加したことです。隠れ層のアクティベーションをゼロにする簡単なReLUです。

他のすべては同じままです。私たちは前と同じようにスコアに基づいて損失を計算し、前とdscores同じようにスコアの勾配を取得します。しかし、その勾配をモデルパラメータに逆伝播させる方法は、当然変更します。

まず、ニューラルネットワークの2番目のレイヤーをバックプロパゲーションします。これはSoftmax分類子のコードと同じですが、X(生データ)をhidden_layer変数に置き換えています。 しかし、これまでとは違って、まだ完了していません。hidden_layerは、それ自体が他のパラメータやデータの関数なのですから!この変数を使ってバックプロパゲーションを続ける必要があります。その勾配は次のように計算できます。
dhidden = np.dot(dscores, W2.T)

次に、ReLUの非線形性をバックプロパゲーションする必要があります。これは、後方伝搬中のReLUが実質的にスイッチであるため、容易であることが分かります。

\( r = max(0,x)  \)であるから、その微分は\( \quad\quad\quad \frac{dr}{dx} = 1 (x>0)  \)となります。

チェーンルールと組み合わせると、フォワードパスでのReLUユニットは、入力が0より大きい場合にはグラジエントパスを通り、変更せずに通過しますが、入力がゼロ未満の場合には出力を殺します。したがって、ReLUを単に以下のように後方伝搬することができます。
dhidden[hidden_layer <= 0] = 0  この記述がわかりません。

In [15]:
# initialize parameters randomly
h = 100 # size of hidden layer   # 隠れ層のニューロン数は100個とします。
W = 0.01 * np.random.randn(D,h)  # サイズがニューロンの数(最終クラスの数ではない)
b = np.zeros((1,h))
W2 = 0.01 * np.random.randn(h,K) # 入力はニューロンの数で、出力サイズが最終クラスの数
b2 = np.zeros((1,K))

# some hyperparameters
step_size = 1e-0
reg = 1e-3 # regularization strength

# gradient descent loop
num_examples = X.shape[0]
for i in xrange(10000):        # 繰り返し数がけた違いに大きいです。
  
  # evaluate class scores, [N x K]
  hidden_layer = np.maximum(0, np.dot(X, W) + b) # note, ReLU activation
  scores = np.dot(hidden_layer, W2) + b2
  
  # compute the class probabilities
  exp_scores = np.exp(scores)
  probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K]
  
  # compute the loss: average cross-entropy loss and regularization
  corect_logprobs = -np.log(probs[range(num_examples),y])
  data_loss = np.sum(corect_logprobs)/num_examples
  reg_loss = 0.5*reg*np.sum(W*W) + 0.5*reg*np.sum(W2*W2)  # W2の項を追加します。
  loss = data_loss + reg_loss
  if i % 1000 == 0:
    print "iteration %d: loss %f" % (i, loss)
  
  # compute the gradient on scores
  dscores = probs
  dscores[range(num_examples),y] -= 1
  dscores /= num_examples
  
  # backpropate the gradient to the parameters
  # first backprop into parameters W2 and b2
  dW2 = np.dot(hidden_layer.T, dscores)
  db2 = np.sum(dscores, axis=0, keepdims=True)
  # しかし、これまでとは違って、まだ完了していない。
  # hidden_layerは、それ自体が他のパラメータやデータの関数なのですから!
  # この変数を使ってバックプロパゲーションを続ける必要があります。
  # next backprop into hidden layer
  dhidden = np.dot(dscores, W2.T)   #compute the gradient on dscores
  # 次に、ReLUの非線形性をバックプロパゲーションする必要があります。
  # これは、逆方向パス中のReLUが実質的にスイッチであるため、容易であることが分かる。  
  # backprop the ReLU non-linearity
  dhidden[hidden_layer <= 0] = 0
  # finally into W,b
  dW = np.dot(X.T, dhidden)
  db = np.sum(dhidden, axis=0, keepdims=True)
  
  # add regularization gradient contribution
  dW2 += reg * W2
  dW += reg * W
  
  # perform a parameter update
  W += -step_size * dW
  b += -step_size * db
  W2 += -step_size * dW2
  b2 += -step_size * db2
# dscores = probs
# dhidden
#hidden_layer
hidden_layer.shape
 
iteration 0: loss 1.098513
iteration 1000: loss 0.303631
iteration 2000: loss 0.266166
iteration 3000: loss 0.262572
iteration 4000: loss 0.251706
iteration 5000: loss 0.257814
iteration 6000: loss 1.925122
iteration 7000: loss 0.250567
iteration 8000: loss 0.250313
iteration 9000: loss 0.250620
Out[15]:
(300L, 100L)
In [11]:
# evaluate training set accuracy
hidden_layer = np.maximum(0, np.dot(X, W) + b)
scores = np.dot(hidden_layer, W2) + b2
predicted_class = np.argmax(scores, axis=1)
print 'training accuracy: %.2f' % (np.mean(predicted_class == y))
 
training accuracy: 0.98
In [12]:
# plot the resulting classifier
h = 0.02
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                     np.arange(y_min, y_max, h))
Z = np.dot(np.maximum(0, np.dot(np.c_[xx.ravel(), yy.ravel()], W) + b), W2) + b2
Z = np.argmax(Z, axis=1)
Z = Z.reshape(xx.shape)
fig = plt.figure()
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8)
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.colorbar() 
#fig.savefig('spiral_net.png')
Out[12]:
<matplotlib.colorbar.Colorbar at 0xe3c6ac8>