くじら公園

プログラミングなど学んだことについて書きます

Deep Learning Specialization(Coursera) - Course 2のメモ

CourseraDeep Learning Specializationの受講メモです。Deep Learning SpecializationはMachine Learningコースを提供するAndrew Ng氏、および氏が創設したdeeplearning.aiが提供する深層学習に関する一連の講義です。以下の5つのコースから構成されています。

  • COURSE 1: Neural Networks and Deep Learning
  • COURSE 2: Improving Deep Neural Networks: Hyperparameter tuning, Regularization and Optimizationw
  • COURSE 3: Structuring Machine Learning Projects
  • COURSE 4: Convolutional Neural Networks
  • COURSE 5: Sequence Models

今回はCOURSE 2、Improving Deep Neural Networks: Hyperparameter tuning, Regularization and Optimizationwを受講した際の備忘録的なメモです。Deep Learning Specialization全体を受講したうえでのまとめは別途記載する予定です。


COURSE 2: Improving Deep Neural Networks: Hyperparameter tuning, Regularization and Optimizationw

COURSE 2はニューラルネットワークの各種正則化手法や最適化手法、ハイパーパラメーターチューニングなど学習を効率的に行うための手法とその理解が主な内容でした。Week 1で過学習とこれを避けるための正則化手法―L2正則化ドロップアウトや勾配爆発・消失問題について学び、続いてmomentum、RMSProp、Adam optimizationなど最適化手法を理解・実装し(Week 2)、最終週で落ち葉拾いとしてハイパーパラメーターチューニング、バッチ正則化、多クラス分類について学んだあと、以降のCOURSEで使用することになるTensorflowの基本について学ぶ(Week 3)のが大まかな流れとなります。

受講期間の公式の見積もりは"3 weeks, 3-6 hours per week"となっており、実際に要した時間は凡そ12時間でした。

COURSE 2は深層学習の初心者、および(私のような)普段TensorflowやChainerなどフレームワークを通してのみ正則化や最適化手法を利用している人間が、それらの直感的な理解をビデオを通して学び、またProgramming Assignmentsを通して実際に手を動かして体験できるようになっていました。

COURSE 1から引き続き一貫してモデル改善のイテレーション-Idea→Code→Experimentを効率的に回すことが成功への近道という主張が繰り返し提示され、COURSE 2はそのための各種手法を、ビデオ抗議で直感的に理解し、Programming Assignmentsで自分で実装し目で見てさらに理解を深めるという形式でした。

個人的には指数加重移動平均を学んだ後に、これをパラメーターの更新に適用するmomentum、momentumを拡張したRMSProp、momentumのアイデアとRMSPropのアイデアを合わせたAdam optimizerという一連の最適化手法の説明がわかりやすく面白かったです。また、RMSPropの生い立ちに言及しているときのAndrew先生の笑顔がみていてうれしかった:

One fan fact about RMSprop, it was actually first proposed not in on academic research paper, but in a Coursera course that Jeff Hinton had taught on Coursera many years ago.

また(これは私が不勉強なだけですが)最近の潮流として、学習時に問題となるのはlocal optimaではなくsaddle pointsを抜け出すのに時間がかかることと考えられていることや、ハイパーパラメーターの探索時はグリッド探索よりrandom samplingが有効であるなど、本COURSEが割と新鮮(公開が3ヶ月前)であるがゆえに新しく学ぶことが多かったです。

以下メモです(ただメモを張り付けているだけなので、体裁が崩れていたらすみません…):

Week 1

2017/10/09

ビデオ+クイズで3時間。Programming Assignmentsで2時間

内容

ビデオ
  • Train / Dev / Test sets
    • Intuiton from one domain or from one application area often do not transfer to other application areas.

    • devset: たくさんの異なるモデルの中でどれが手元のdevsetに対し最も良いパフォーマンスを呈するか検証するために用いる
    • testset: 最終的なモデルを評価する、手元のアルゴリズムがどれくらい上手く機能するかunbiasedな見積もりを得るために用いる
  • Biase / Variance
    • high bias: under fitting
      • より大きなネットワークを用いる
      • もう少し長く学習する
      • (別のNNアーキテクチャを模索する)
    • high variance: overfitting
  • Regularization
    • L2 Regularization
      • ロジスティック回帰の場合
        • 正則化項: lambd / (2m) \norm{w}_22 = lambd / (2m) WTW
      • Neural Networksの場合
        • 正則化項: lambd / (2m) \sum_{l=1}^L \norm{w^[l]}^2
          • \norm{w^[l]}^2はForbenius normと呼ばれる
          • wは(n^[l], n^[l-1])だから\norm{w^[l]}^2 = \sum{i=1}^{n^[l-1]} \sum{i=j}^{n^[l-1]} (w_{ij}^[l])2
          • 逆伝播のときは正則化項の微分を忘れずに
      • 正則化項は、wが大きくなりすぎることに対しペナルティを課す
        • lambdを大きくすると更新後のwは0に近づく
        • 直感的には、正則化することでより小さなネットワークとなる
        • もう一つの直感的な捉え方として、活性化関数にtanhを仮定する、tanhは0付近で勾配が線形に近づく→underfittingされる
  • Dropout
    • inverted dropout
      • keep_probの確率でランダムにユニットをzero outした上で、残ったユニットをkeep_probで除算する
        • 例えば a3 /= keep_prob
        • to keep exptected values of a3.

        • これをしとかないとtestデータに対する予測をするときに苦労することになる
          • 「学習時はkeep_probでdropoutしたけどtest時はdropoutしないのでaの値をスケールして…」とか悩まないために
    • Why dose dropout work?
      • Can't rely on any one feature, so have to spread out weights

  • Other regularization methods
    • Data augumentation
    • Early stopping
      • 初期値はwは0に近い、学習が進むとwは大きな値となる、この間で学習を止める
      • Orthogonalization
        • early stoppingはoptimizationとnot overfitの2つを別個に考慮することができない
  • Normarizing inputs
    • 平均ひいて、分散で除する
  • Vanishing / exploding gradiendts
    • a very deep neural network your derivatives of your slopes can sometimes get either very big or small.

    • w > I(単位行列)→深いネットワークでは活性化関数の結果が爆発してしまう→勾配も爆発
  • Weight initialization
    • Vanishing / exploding gradiendtsに対処するための手段の一つ
    • z1 = w_1x_1 + w_2x_2 + \cdots + w_nx_n(nはユニット数)
    • var(w_i) = 1/nだと嬉しい
    • なので、w^[l] = np.random.randn(shape) * np.sqrt(1 / n^[l-1])
      • l-1なのは入力される特徴量(ユニット数)でスケールしたいから
      • ReLUだと、np.sqrt(2 / n^[l-1])が良いらしい
      • Xavier initialization: np.sqrt(1 / n^[l-1])
  • Numerical approximation
  • Gradient check
Programming Assignments

所感

  • inverted dropoutの名前と理由は始めてしった
  • Programming Assignmentsが、実際に各手法を実装して結果を見比べるという内容で理解しやすかった

Week 2 - Optimization algorithms

2017/10/13 ビデオ2時間

2017/10/16 ビデオ+クイズ1時間、Programming Assignment 0.5時間

内容

ビデオ
  • Mini batch gradient descent
    • You can get a faster algorithm if you let gradient descent start to make some progress before you finish processing your entire examples.

    • Epoch: A single pass through the training set.
  • Understanding mini-batch gradient descent
    • Batch gradient descentの学習曲線は、イテレーション毎にコストが必ず減少していく
    • mini-batch gradient descentの学習曲線は、減少傾向にあるけれどノイズが含まれる
    • Choosing your mini-batch size
      • mini-batch size m: Batch gradient descentと同じ
        • too long / iteration
      • mini-batch size 1: Stochastic gradient descent
        • Lose speedup from vectorization
      • 2つの間をmini-batch sizeとして選択する
      • Because of the way computer memory is layed out and accessed, sometimes your code run faster if your mini-batch size is power of 2.

  • Exponentially weighted averages
    • v_t = \beta v_{t-1} + (1 - \beta) \theta_t
      • beta = 0.9のとき、1/(1-0.9) = 10、10回分を通して平均している
      • betaを大きくするとより平滑化される
    • \theta_tのプロットに、exponentially decayng functionをかけ合わせる
    • 実装時はv(v_{\theta})を使いまわす
      • v is computing exponentially weighted average over the parameter theta

  • Bias correction in exponentially weighted averages
    • v_t = \beta v_{t-1} + (1 - \beta) \theta_t、tが小さい範囲で本来の値との剥離が大きい
    • 対策としてv_tを1-\betatで除した値を用いる
  • Gradient descent with momentum
    • The basic idea is to compute an exponentially weighted decay of your gradients, and then use that gradient to update your weights instead.

    • v{dw} = \beta v{dw} + (1 - \beta) dW
    • W := W - \alpha v_{db}
    • smooth out the steps of gradient descent

  • RMSprop; root mean square prop
    • s{dw} = \beta s{dw} + (1 - \beta) dW2
    • W := W - \alpha (dW / s_{dw}^{1/2} + \epsilon)
    • One fan fact about RMSprop, it was actually first proposed not in on academic research paper, but in a Coursera course that Jeff Hinton had taught on Coursera many years ago.

  • Adam optimization: Adaptive momentum estimation
    • v{dw} = \beta_1 v{dw} + (1 - \beta_1) dW; momentumと一緒
    • s{dw} = \beta_2 s{dw} + (1 - \beta_2) dW2; RMSpropと一緒
    • v^{corrected}{dw} = v{dw} / (1 - \beta_12); bias correction of v_{dw}
    • s^{corrected}{dw} = s{dw} / (1 - \beta_22); bias correction of s_{dw}
    • W := W - \alpha (v^{corrected}{dw} / s^{corrected}{dw}^{1/2} + \epsilon)
  • Learning rate decay
    • Slowly reduce your learning rate over time

    • \alpha = 1 / (1 + decay_rate * epoch_num) * \alph_0
  • The problem of local optima
    • Most points of zero gradients are not local optima

    • Most points of zero gradients in a cost function are saddle points.

    • 最近は、次元数が大きい場合、local optimaのような箇所はむしろ稀であり、saddle pointsのような箇所が多く在ると考えられている
    • One of the lessons we learned in history of deep learning is that a lot of our intuitions about low-dimensional spaces, they really don't transfer to the very high dimensional spaces that any other algorithms are operating over.

    • It turns out that plateaus can really slow down learning and plateua is a region where the derivative is close to zero for a long time.

Programming Assignments
  • mini-batchを実装
  • momentumを実装
  • adamを実装
  • 上記3つを比較、adamは明らかにmini-batchとmomentumを凌ぐ

所感

  • momentum、RMSprop、Adamの一連の説明が分かりやすかった
  • AdamやRMSpropは普段tensorflow等を通して利用しているだけなので、今回始めて実装してみて勉強になった

Week 3 - Hyperparameter Tuning, Batch Normalization, Multi-class Classification, Introduction to programming frameworks

2017/10/17 ビデオ2時間40分、Programming assignment 40分

内容

ビデオ
  • Hyperparameter tuning
    • how to systematically organize your hyperparameter tuning process.

    • 重要度: \alpha > \beta, #hidden units, #mini batch size > #layers, learning rate decay > \beta_1, \beta_2, \epislon(Adam)
    • Try random value. Don't use grid
      • it's difficult to know in advance which hyper parameters are going to be the most important for your problem. And some hyperparameters are actually much more important than others.

      • sampling at random rather than in the grid shows that you are more richly exploring set of possible values for the most important hyperparameters, whatever they turn out to be.

    • Corse to fine sampling schema
      • ランダムにパラメーターを選択して学習して、よりものについてズームインしてもう一度探索する
    • Using an appropriate scale to pick hyperparameters
      • layers: uniform sampling

      • learning rate \alpha: log scale sampling
        • 0.0001~0.001、0.001~0.01の間についての探索に同等のリソースを割く
      • exponentially weighted decay \beta: log scale sampling
        • when beta is close to 1, the sensitivity of the results you get changes even with very small changes to beta.

    • Hyperparameters tuning in practice: Pandas vs Caviar
    • cross-fertilization: 画像の領域で開発されたResNetがSpeech等でも良い成績を達成するようなことを言う
    • hyperparameters, i've seen that intuitions do get stale. * 同様のことはhyperparametersの探索では稀

    • Babysitting one model: 学習が複数実に渡る場合、日毎に学習経過に合わせてパラメーターを返る探索の仕方
      • データが大きい、リソースが少ない時の手法
      • パンダ、子供一匹を大事に育てる
    • Training many models in parallel
      • キャビア、子供いっぱいを一度に育てる、どれかがうまくいく
  • Batch Normalization
    • BN makes your hyperparameter search problem much easier, BN makes the neural network much robust to the choice of hyperparameters and enables you to much more easily train even very deep network.

    • inputの正規化は学習を高速化する
      • 正規化する前と正規化した後の2パラメーターの等高線の図
    • can we normalieze a^[l-1] so as to train W^[l], b^[l] faster? * inputの正規化の考えを隠れ層に適用する

    • Implementing Batch Normalization
      • Given some intermediate values in NN z^{(1)}, z^{(2)}, ..., z^{(m)}
        • \mu = \sum_i z^{(i)} / m
        • \sigma2 = \sum_i (z^{(i)} - \mu)2
        • z^{(i)}_{norm} = (z^{(i)} - \mu) / sqrt(\sigma2 + \epsilon)
        • \tild{z^{(i)}} = \gamma z^{(i)}_{norm} + \beta
      • \gammaと\betaは学習するパラメーター
        • 平均0、分散1が常に裁量とは限らない
      • BNだとb^[l]は要らない
        • BN zeros out the means of z^[l] values in the layer there's no point having this parameter b^[l] and instead is sort of replaced by \beta-[l].

    • Why dose BN work?
      • covariate shift: 学習時と予測時のデータの分布が異なると予測はうまくいかない
      • if the distribution of X changes, then you might need to retrain your learning algorithm.

      • 5層ネットワークを想定して、3番目の層の視点で考えてみる
        • job of the third hidden layers is to take these values(a[2]) and find a way to map them to \hat{y}. The network also adapting parameters W^[2], b^[2], W^[1], b^[1] and so as these parameters change, the values a^[2]also change.

        • a^[2]は毎回変化する→3層目がcovariate shift problemを被る
        • so what BN dose, it reduce, the amount that the distribution of these hidden unit values shifted around.

        • But really don't turn to BN as regularization. Use it as a way to normalize your hidden unit activations and therefore speed up learning.

    • BN at test time
      • testするときはexampleの数は1、\muと\sigma2はどのような値を用いる?
        • estimate using exponentially weighted average across mini-batch; \mu^{{1}[l]}
  • Multi class Classification
    • Softmax regression: generalization of logistic regression
    • C: #classes, output layerのunit数
      • what is the probability of each of these c classes; P(C = c|X)

      • t = exp(z^[l])
      • a^[l] = exp(z^[l]) / \sum_j t_j
    • hardmaxは要素が一つだけ1になっているベクトルを出力する処理
Programming Assignments
  • tensorflowの基本

所感

  • 最近はGrid探索よりランダムにサンプリングしたhyperparameterの組み合わせでtuningするらしい
    • Week 2のThe problem of local optima-最近は学習を遅延させる原因はlocal optimaではなくsaddle pointsにあると考えられている、と同様に最近のNN界隈の理解が学べるのが楽しい
  • 入力の正規化と対比させて説明されるBNがわかりやすい