Successfully reported this slideshow.
Your SlideShare is downloading. ×

TensorFlowの使い方(in Japanese)

Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Loading in …3
×

Check these out next

1 of 35 Ad

More Related Content

Slideshows for you (20)

Similar to TensorFlowの使い方(in Japanese) (20)

Advertisement

More from Toshihiko Yamakami (20)

Recently uploaded (20)

Advertisement

TensorFlowの使い方(in Japanese)

  1. 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TensorFlow の使い方 Toshihiko.Yamakami@access-company.com 山上俊彦 IoT 事業本部, ACCESS 2017/01 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 1 / 35
  2. 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TensorFlow Google が Apache 2.0 ライセンスで公開した機械学習ライブラリ C, Python の API を持つ 現在のバージョンは 0.12 (20170123) 利点 モデル設計が簡単でコード記述も簡潔に書ける 商用フリーのライセンスであるため、機械学習システム導入のコス トを抑えられる 学習がし易い 導入しやすい 欠点 ほとんどの処理がブラックボックスである: 関数の処理フローが明 確でない。エラーを動作原理まで遡って特定することができない (報告例: ReLU 関数を引数で渡すとエラーになるが等価な関数で書 くと動く)。 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 2 / 35
  3. 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TensorFlow コード記述の 3 つの部分 部分 推論処理部 損失定義部 訓練部 概要 予測のためのネットワ ークを前方向に実行す るために必要な推論グ ラフを構築。出力予測を 含むテンソルを返す。 推論グラフに損失を生 成するために必要な処 理の定義を加える。損失 を返す。 勾配を計算して適用す るために必要な処理の 定義を加える。 利用 損失定義部の入力とし て使われる 推論処理部で定義した テンソルを入力として 損失を返し、この結果を 訓練部が利用する 損失とハイパーパラメ ータ (学習率) を入力す る # loss ( 損 失 と し て 別 に 定 義 ) inference( 推 論 グ ラ フ と し て 別 に 定 義 ) with tf.Graph().as_default(): images_placeholder , labels_placeholder = placeholder_inputs( FLAGS.batch_size) logits = mnist.inference(images_placeholder , FLAGS.hidden1 , FLAGS.hidden2) loss = mnist.loss(logits, labels_placeholder) train_op = mnist.training(loss, FLAGS.learning_rate) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 3 / 35
  4. 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 推論部の例 I def inference(images , hidden1_units , hidden2_units): """Build the MNIST model Args: images: Images placeholder , from inputs(). hidden1_units: Size of the first hidden layer. hidden2_units: Size of the second hidden layer. Returns: softmax_linear: Output tensor with the computed logits. """ # Hidden 1 with tf.name_scope('hidden1 '): weights = tf.Variable( tf.truncated_normal([IMAGE_PIXELS , hidden1_units], stddev=1.0 / math.sqrt(float(IMAGE_PIXELS))), name='weights ') biases = tf.Variable(tf.zeros([hidden1_units]), name='biases ') hidden1 = tf.nn.relu(tf.matmul(images, weights) + biases) # Hidden 2 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 4 / 35
  5. 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 推論部の例 II with tf.name_scope('hidden2 '): weights = tf.Variable( tf.truncated_normal([hidden1_units , hidden2_units], stddev=1.0 / math.sqrt(float(hidden1_units))), name='weights ') biases = tf.Variable(tf.zeros([hidden2_units]), name='biases ') hidden2 = tf.nn.relu(tf.matmul(hidden1 , weights) + biases) # Linear with tf.name_scope('softmax_linear '): weights = tf.Variable( tf.truncated_normal([hidden2_units , NUM_CLASSES], stddev=1.0 / math.sqrt(float(hidden2_units))), name='weights ') biases = tf.Variable(tf.zeros([NUM_CLASSES]), name='biases ') logits = tf.matmul(hidden2 , weights) + biases return logits 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 5 / 35
  6. 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TensorFlow を書く時の注意 コードは Python だが、あくまでもループなどに見えてもリンク関 係を定義しているだけ。実際の実行は TensforFlow の中で独自に行 われる。途中に print をいれて内部状態を見るとかはできない。 記述だけをする理由: numpy などの外部数値計算ライブラリをいち いち呼ぶと遅いので、定義だけ書いてから全部外で実行させている ため グラフの書き方の基本は「入力値 x に重み W をかけバイアス b を足して活性化関数を通したあとに次の層に渡す」。これをつなげ る。 実行は Python で書いた TensorFlow コードを Python で実行する だけ。 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 6 / 35
  7. 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TensorFlow playground TensorFlow playground については別資料があるのでここでは説明 しない 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 7 / 35
  8. 8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 用語 shape: TensorFlow が処理するテンソルの形状(次元)。通常固定だ が reshape することもできる name_scope: 視覚化環境の TensorBoard で表示するものをまとめ る logit: ロジット。認識の対数オッズ。ロジット関数はロジスティッ ク関数の逆関数であり、特に確率論と統計学で多く用いられる。 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 8 / 35
  9. 9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 初歩 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 9 / 35
  10. 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 注意 そもそも重回帰分析や SVM で解けるならそのほうが高速 TensorFlow は Google みたいに何千万個もデータもっている会社 の大規模分散処理 普通は PC に GPU 積むくらいで十分 変に GPU マシンを複数並べてもうまくやらないとかえって遅い 実際に master, worker  プロセスをつくって分散処理をさせるの はそれなりに面倒 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 10 / 35
  11. 11. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TensorFlow の利用準備 TensorFlow をインストールする Python の環境構築から TensorFlow インストール http://qiita.com/bohemian916/items/4f0736dcea932a162d9e (2016 年 6 月) データを持ってくるのが課題 (末尾に TensorFlow の例を示す) MNIST: http://yann.lecun.com/exdb/mnist/ 自分のデータなら、学習用に前処理することが必要 from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf flags = tf.app.flags FLAGS = flags.FLAG flags.DEFINIE_string('data_dir ', '/tmp/data', 'Directory for storing data') mnist = input_data.read_data_sets(FLAGS.data_dir , one_hot=True) sess = tf.InteractiveSessions() 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 11 / 35
  12. 12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Python から動くことを確認する例 (文字列表示と加算) >>> import tensorflow as tf >>> hello = tf.constant('Hello, TensorFlow!') >>> sess = tf.Session() >>> print sess.run(hello) Hello, TensorFlow! >>> a = tf.constant(10) >>> b = tf.constant(32) >>> print sess.run(a+b) 42 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 12 / 35
  13. 13. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . モデルを記述するためのデータ構造 入力層: 入力データの配列 (28 ∗ 28 = 784 次元のデータならそれだ けの配列) 重み変数: 入力データ数次元の重みベクトル(隠れ層ノードの数) バイアス変数: 隠れ層ノードの数の配列 出力層: 出力データの配列と出力用活性化関数の定義 (識別ならソ フトマックス関数) x = tf.placeholder(tf.float21 , [None, 784]) W = tf.Variable(tf.zeros([784, 10] b = tf.Variable(tf.zero([10]) y = tf.nn.softmax(tf.matmul(x, W)+b) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 13 / 35
  14. 14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 誤差関連処理 交差エントロピー、誤差伝搬型関数 (学習率も) の定義 y_ = tf.placeholder(tf.float32 , [None, 10]) corss_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 14 / 35
  15. 15. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 学習(訓練)を行う # 初 期 化 す る tf.initialize_all_variables().run() # 1000 回 繰 り 返 す for i in range(1000): # 訓 練 デ ー タ を 100 個選択 batch_xs , batch_ys = mnist.train.next_batch(100) train_step.run({x: batch_xs , y_: batch_ys}) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 15 / 35
  16. 16. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 学習結果の検証 検証用データで試験 正答率を出す correct_prediction=tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) # True,False を0,1 に 変 換 し 平 均 を と る accuracy = tf.reduce_mean(tf.cast(correct_prediction , tf.float32)) # 精 度 を 表 示 print(accuracy.eval({x:mnist.test.images, y_:mnist.test.labels})) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 16 / 35
  17. 17. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ハイパーパラメータの調整 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 17 / 35
  18. 18. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 変数の初期化と重みの初期化関数の定義 # 変 数 の 初 期 化 sess.run(tf.initialize_all_variables()) # 重 み を 標 準 偏 差 0.1 の 正 規 分 布 で 初 期 化 def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) # バ イ ア ス を 標 準 偏 差 0.1 の 正 規 分 布 で 初 期 化 def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 18 / 35
  19. 19. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 補足:ランダムやゼロで初期化する例 # 正 規 分 布 で 初 期 化 w_h = tf.Variable(tf.random_normal([784, 625], mean=0.0, stddev=0.05)) w_o = tf.Variable(tf.random_normal([625, 10], mean=0.0, stddev=0.05)) # ゼ ロ で 初 期 化 b_h = tf.Variable(tf.zeros([625])) b_o = tf.Variable(tf.zeros([10])) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 19 / 35
  20. 20. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 畳み込みのストライドとプーリングの設定 # 畳 み 込 み 層 の 作 成 def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') # プ ー リ ン グ 層 の 作 成 def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 20 / 35
  21. 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 活性化関数 (例では ReLU 関数) とプーリング実施 (定義済) W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) # 入力を 28x28x1 に変形 x_image = tf.reshape(x, [-1,28,28,1]) # 畳 み 込 み 層 1を ReLU 関 数 で 設 定 h_conv1 = tf.nn.relu(conv2d(x_image , W_conv1) + b_conv1) # Max プ ー リ ン グ を 設 定 h_pool1 = max_pool_2x2(h_conv1) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 21 / 35
  22. 22. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 つの畳み込み層の高密度結合層の実現 W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2 , [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat , W_fc1) + b_fc1) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 22 / 35
  23. 23. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . オンオフできるドロップアウト keep_prob = tf.placeholder(tf.float32) # ド ロ ッ プ ア ウ ト h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 23 / 35
  24. 24. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ソフトマックスは既出だが 2 隠れ層の例 W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop , W_fc2) + b_fc2) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 24 / 35
  25. 25. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . セッションを走らせる前にオプティマイザ (例は Adam) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_hypo ,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction , "float")) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 25 / 35
  26. 26. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . L2 正則化の例 # Regularization terms (weight decay) L2_sqr = tf.nn.l2_loss(w_h) + tf.nn.l2_loss(w_o) lambda_2 = 0.01 # 損失に L2 正 則 化 を 適 用 loss = cross_entropy + lambda_2 * L2_sqr train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 26 / 35
  27. 27. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 補足: 損失関数の中で疎なラベルを 0–1 の小数に変換の例 concated = tf.concat(1, [indices , labels]) onehot_labels = tf.sparse_to_dense( concated , tf.pack([batch_size , NUM_CLASSES]), 1.0, 0.0) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 27 / 35
  28. 28. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . モデルの記述 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 28 / 35
  29. 29. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . モデルの記述例 隠れ層は,入力層の値から線形予測子を計算し,それをシグモイド関数に入れて算出 出力層は,隠れ層の値から線形予測子を求め,それをソフトマックス関数に入れて算出 コスト関数は自分のモデルの値 y_hypo を計算,さらに訓練データのラベル y_ と合わせ て cross entropy 値を求める # モ デ ル を 作 成 def model(X, w_h, b_h, w_o, b_o): h = tf.sigmoid(tf.matmul(X, w_h) + b_h) pyx = tf.nn.softmax(tf.matmul(h, w_o) + b_o) return pyx y_hypo = model(x, w_h, b_h, w_o, b_o) # コ ス ト 関 数 と し て 交 差 エ ン ト ロ ピ ー を 設 定 cross_entropy = -tf.reduce_sum(y_*tf.log(y_hypo)) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 29 / 35
  30. 30. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ハイパーパラメータ以外の調整や操作 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 30 / 35
  31. 31. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . デバイスの指定 (GPU) with tf.Session() as sess: # デ バ イ ス の 指 定 with tf.device("/gpu:1"): matrix1 = tf.constant([[3., 3.]]) matrix2 = tf.constant([[2.],[2.]]) product = tf.matmul(matrix1 , matrix2) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 31 / 35
  32. 32. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 学習パラメータの保存と回復 tf.train.Saver() はその時点で存在するパラメータに対する保存を 定義。すべて終ってから呼ばないと想定通り保存されない # 学 習 し た パ ラ メ ー タ の 保 存 と 読 み 込 み に は 、 tf.train.Saver を使用 saver = tf.train.Saver() な ん ら か の 処 理 # 保存 ( あ と で 比 較 す る た め ) saver.save(sess, "model.ckpt") # 回復 saver.restore(sess, "model.ckpt") 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 32 / 35
  33. 33. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 学習後、手書き文字を書いて試験 saver = tf.train.Saver() ckpt = tf.train.get_checkpoint_state('./') if ckpt: last_model = ckpt.model_checkpoint_path print "load " + last_model saver.restore(sess, last_model) from PIL import Image import numpy as np new_img = Image.open('./new_data_2.png').convert('L') new_img = 1.0 - np.asarray(new_img, dtype="float32") / 255 new_img = new_img.reshape((1,784)) prediction = tf.argmax(y_conv ,1) print("result: %g"%prediction.eval(feed_dict={x: new_img, keep_prob: 1.0}, session=sess)) else: # 学習 saver.save(sess, "model.ckpt") 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 33 / 35
  34. 34. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 参考資料 I TensorFlow のチュートリアルを通して、人工知能の原理について学習する  http://qiita.com/jintaka1989/items/3b70b5c5541620536fa2 (2016 年 12 月) TensorFlow を使った機械学習ことはじめ (GDG 京都機械学習勉強会) http://www.slideshare.net/ToruUenoyama/tensorflow-gdg (2016 年 2 月) R で L1 / L2 正則化を実践する http://tjo.hatenablog.com/entry/2015/03/03/190000 (2015 年 3 月) 深層学習と TensorFlow 入門 http://www.slideshare.net/tak9029/tensorflow-67483532 (2016 年 10 月) TensorFlow : MNIST データ・ダウンロード (コード解説) http://tensorflow.classcat.com/2016/03/09/tensorflow-cc-mnist-data-download/ 中学生にも分かる TensorFlow 入門 その1 テンソルとはなにか  http://qiita.com/EtsuroHONDA/items/02635dc3026e29f3cb41   (2016 年 5 月) 中学生にも分かる TensorFlow 入門 その 4  プログラムの解説・フローチャート http://qiita.com/EtsuroHONDA/items/79844b78655ccb3a7ae6 (2016 年 5 月) Python の環境構築から TensorFlow インストール  http://qiita.com/bohemian916/items/4f0736dcea932a162d9e (2016 年 6 月) TensorFlow チュートリアル - ML 初心者のための MNIST(翻訳) http://qiita.com/KojiOhki/items/ff6ae04d6cf02f1b6edf 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 34 / 35
  35. 35. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 参考資料 II TensorFlow チュートリアル - 熟練者のためのディープ MNIST(翻訳) http://qiita.com/KojiOhki/items/64a2ee54214b01a411c7 落ちこぼれないための TensorFlow Tutorial コード http://qiita.com/TomokIshii/items/92a266b805d7eee02b1d (2016 年 4 月) TensorFlow でアニメゆるゆりの制作会社を識別する http://kivantium.hateblo.jp/entry/2015/11/18/233834 (2015 年 11 月) [TF]Tensorflow の学習パラメータの保存と読み込み方法 http://qiita.com/supersaiakujin/items/fc400fc6fa58b3809619 (2016 年 4 月) TensorFlow : How To : 変数: 作成、初期化、保存そしてロード http://tensorflow.classcat.com/2016/02/09/tensorflow-how-tos-variables/ (2016 年 2 月) TensorFlow で学習済みモデルを使用する (Deep MNIST for Experts の応用) http://walkingmask.hatenablog.com/entry/2016/08/27/032400 (2016 年 8 月) TensorBoard で処理を可視化する  http://www.mwsoft.jp/programming/tensor/tutorial_tensorboad.html (2016 年 5 月) TensorFlow : 全結合モデル for MNIST (コード解説) http://tensorflow.classcat.com/2016/03/11/tensorflow-cc-mechanics-101/ (2016 年 3 月) Tensorflow_in_ROS のコードを解説する http://qiita.com/shunchan0677/items/60f8f567359fbbbf9321 (2016 年 11 月) TensorFlow : CNN – 畳み込みニューラルネットワーク for CIFAR-10 (コード解説)  http://tensorflow.classcat.com/2016/03/12/tensorflow-cc-convolutional-neural-networks/ (2016 年 3 月) 山上俊彦 (ACCESS Confidential) TensorFlow の使い方 2017/01 35 / 35

×