TensorFlow 触りはじめ
◆tensorflow動作テスト用のプログラム
(1)”Hello World!”を表示させる
import tensorflow as tf hello = tf.constant('hello World!') sess = tf.Session() print(sess.run(hello))
(2)単純な行列計算をするプログラム
# XとYの積を求めるプログラム import tensorflow as tf X = tf.constant([[3.,3.]]) Y = tf.constant([[2.],[2.]]) # XとYの積を計算するノードを作成 node = tf.matmul(X, Y) # 実行する sess = tf.Session() result = sess.run(node) print(result) # [[12.]]
(3)mnistデータからランダムに10個取り出し、表示する
# tensorflowでmnistデータをさわる、10個ランダム抽出、表示 import numpy as np import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) # 10個のデータを取り出す、変数mnistのメソッド images, labels = mnist.train.next_batch(10) # 1つ目のデータ内容を表示、ラベル&中身 print(labels[0]) print(images[0]) # 取り出した10個を画像として表示 fig = plt.figure(figsize=(8,4)) for c, (image, label) in enumerate(zip(images, labels)): subplot = fig.add_subplot(2,5,c+1) subplot.set_xticks([]) subplot.set_yticks([]) subplot.set_title('%d' % np.argmax(label)) subplot.imshow(image.reshape((28,28)), vmin=0,vmax=1, cmap=plt.cm.gray_r, interpolation="nearest") plt.show() # Extracting /tmp/data/train-images-idx3-ubyte.gz # Extracting /tmp/data/train-labels-idx1-ubyte.gz # Extracting /tmp/data/t10k-images-idx3-ubyte.gz # Extracting /tmp/data/t10k-labels-idx1-ubyte.gz # [ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.] # [ 0. 0. 0. 0. 0. 0. 0.
・”imshow”メソッド・・・画像を表示
・”cmap=plt.cm.gray_r”・・・グレースケールで表示
・”vmin””vmax”・・・濃度の最大値/最小値、濃淡を適切に調整
・”interpolation="nearest"”・・・画像を滑らかに表示する機能を無効化
◆メモ1
・mnistの分類アルゴリズムについて・・・数学的に言えば784次元のベクトルであり、784次元空間の1つの点(x1,x2,,,x784)に対応することになる。784次元は絵では示せないが、その空間を10個の領域に分割して、分類を行うという意味では、二次元平面の分類と類似。
◆メモ2(API、計算)
☞ tf.Session()・・・処理を実行するためのクラス
☞ with句・・・セッションを記述。
☞ fetch・・・グラフから演算結果を取り出す。
☞ tf.constant・・・定数。定数の行列要素を生成。
☞ input_data・・・外部データを読み込む関数(cf.mnist)
☞ placeholder・・・データが格納される予定地。
・Noneにしておくと可変サイズに対応可
☞ tf.assign・・・変数に値を代入。
◆TensorFlow
・グラフ(エッジ+ノード)という処理概念を使っている。
・グラフを実行するためには、sessionを作りrunメソッドをコール。
・約1000のAPIが公開。
◆インストール(mac)
・公式ページを参考
・conda インストール(python 3.6)
◆参考サイト
・TF参考
TensorFlowで学ぶディープラーニング入門備忘録【第2章】 - ハードウェアエンジニアの備忘録