にほんごのれんしゅう

日本語として伝えるための訓練を兼ねたテクログ

Python Theanoでのロジスティック回帰が簡単

Python Theanoでのロジスティック回帰が簡単

モチベーション

  • 今までC++でlbfgsbを実装するなど、速度重視、大容量処理を目指していた
  • C++の実装コストは高い。
  • Rではない、スクリプト言語による実装を探していた
  • Python Theanoというのがいい感じ

ロジスティック回帰を選択した理由

  • ある事象Yに対して素性Xnがどの程度影響しているのか定量的に見たかった
  • コスト関数の最小化の定義の仕方に、lbfgsbでは若干の不安があった(cをどのように最小化するのか、明示されていなかったような)
  • C++ではグラディエント行列作成の実装がこれまた大変であったので、余りやりたくない
  • Python TheanoはT.grad関数で微分をよろしくやってくれる

サンプルコードによる実装例

  • 以下はdeepleaning.netに記載されていたTheanoによるロジスティック回帰の例である
  • シンプルかつ簡潔で、bfsgsのような収束するかしないかはあんまり気にしていないようで、カルバックライブラー情報量を最小化することで最適な値に近づけている
# theanoはnumpyを必要とする
import numpy
import theano
import theano.tensor as T
rng = numpy.random
# サンプル数をNとする
N = 20
# サンプルを表現する素性数をfeatsとする
feats = 784 
# Dというデータ構造に feats0, feats1,...,featsN, resultという行列を作成する
D = (rng.randn(N, feats), rng.randint(size=N, low=0, high=2))
print(D)
# トレーニング回数を定義
training_steps = 10000
# theanoでロジスティック回帰に必要な変数x, y, w, bを定義する
x = T.matrix("x")
y = T.vector("y")
w = theano.shared(rng.randn(feats), name="w")
b = theano.shared(0., name="b")
print("Initial model:")
print( w.get_value() )
print( b.get_value() )
# クロスエントロピー損失関数(カルバックライブラー情報量)とwが大きくなり過ぎないようにコスト関数として適宜する
# カルバックライブラー情報力が最小化されれば、最適化されたとみなせる(新発見)
p_1 = 1 / (1 + T.exp(-T.dot(x, w) - b))   # Probability that target = 1
prediction = p_1 > 0.5                    # The prediction thresholded
xent = -y * T.log(p_1) - (1-y) * T.log(1-p_1) # Cross-entropy loss function
cost = xent.mean() + 0.01 * (w ** 2).sum()# The cost to minimize
gw, gb = T.grad(cost, [w, b])             # Compute the gradient of the cost
# トレーニング関数、予想関数をコンパイル
train = theano.function(
          inputs=[x,y],
          outputs=[prediction, xent],
          updates=((w, w - 0.1 * gw), (b, b - 0.1 * gb)))
predict = theano.function(inputs=[x], outputs=prediction)
# トレーニングする
for i in range(training_steps):
        pred, err = train(D[0], D[1])
# 結果を得る
print( "Final model:" )
print( w.get_value(), b.get_value() )
print( "target values for D:", D[1] )
print( "prediction on D:", predict(D[0]) )

まとめ

  • 計算結果としてwの値もわかるわけで、重要な素性の抽出も楽である
  • wがあまり大きくなりすぎない仕組みやカルバックライブラー情報量の最小化など、ニュートン法の延長ではちょっと気づかなかったかも
  • 僅かなコード量でここまで出来るtheanoすごい
  • R使わずにすんだよ
  • DeepLearning.netはウォッチしとかなきゃ
  • theano.sharedはスタティック変数なので、可視性が高い