CS224d: TensorFlow Tutorial(TensorFlowチュートリアル)

その買うを、もっとハッピーに。|ハピタス

tensorflowを使う前に、tensorflowプログラミングを少し勉強する。tensorflowとnumpyにはそんなに違いがないらしく、基本的には、前者はGPUをサポートしている一方で、後者はしていないというのが一番の違いらしい。なので、GPUがある場合、前者を使うのが至極当然の選択のようである。

スポンサーリンク

TensorFlowとNumPy

簡単なNumPyのまとめ

import numpy as np
a = np.zeros((2,2)); b = np.ones((2,2))
np.sum(b, axis=1)
array([2., 2.])
a.shape
(2, 2)
np.reshape(a,(1,4))
array([[0., 0., 0., 0.]])

TensorFlowで書き換える

import tensorflow as tf
tf.InteractiveSession()
<tensorflow.python.client.session.InteractiveSession at 0x7ffa375a5278>
a = tf.zeros((2,2)); b = tf.ones((2,2))
tf.reduce_sum(b, reduction_indices=1).eval()
array([2., 2.], dtype=float32)
a.get_shape() # tensor.shapeはpythonのtupleのように振る舞う
TensorShape([Dimension(2), Dimension(2)])
tf.reshape(a,(1,4)).eval() 
array([[0., 0., 0., 0.]], dtype=float32)

このように簡単に書き換えられることが分かる。

スポンサーリンク

TensorFlow はeval()が必要!

a = np.zeros((2,2))
ta = tf.zeros((2,2))
print(a)
print(ta)
[[0. 0.]
 [0. 0.]]
Tensor("zeros_1:0", shape=(2, 2), dtype=float32)
print(ta.eval())
[[0. 0.]
 [0. 0.]]
スポンサーリンク

TensorFlowセッションオブジェクト

“A Session object encapsulates the environment in which Tensor objects are evaluated” – TensorFlow Docs
「セッションオブジェクトは、テンソルオブジェクトが計算される環境をカプセル化する。」

a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b
with tf.Session()as sess: # c.eval()は現在アクティブなセッション
    print(sess.run(c)) # sess.run(c)のsyntactic sugar(糖衣構文)
    print(c.eval())
30.0
30.0
  • tf.InteractiveSession() is just convenient syntactic sugar for keeping a default session open in ipython.
    tf.InteractiveSession()は、ipythonでデフォルトのセッションを開いたままにする便利な糖衣構文。
  • sess.run(c)is an example of a TensorFlow Fetch. Will say more on this soon.
    sess.run(c)は、TensorFlow Fetchの一例。
スポンサーリンク

Tensorflow計算グラフ

  • “TensorFlow programs are usually structured into a construction phase, that assembles a graph, and an execution phase that uses a session to execute ops in the graph.” – TensorFlow docs
    TensorFlowプログラムは、通常、グラフとグラフ中の演算を実行するのにセッションを使用する実行フェーズを構築する構築フェーズに構造化されている。
  • All computations add nodes to global default graph – docs
    全ての計算は、グローバルデフォルトグラフにノードを付け加える。
スポンサーリンク

TensorFlow Variables (1)

  • “When you train a model you use variables to hold and update parameters. Variables are in-memory buffers containing tensors” – TensorFlow Docs.
    モデルを訓練する時、パラメーターの保持・アプデに変数を用いる。変数は、テンソルを含むメモリ内バッファ。
  • All tensors we’ve used previously have been constant tensors, not variables.
    ここまで使ってきた全テンソルは、変数ではなく、定数テンソル。
スポンサーリンク

TensorFlow Variables (2)

W1 = tf.ones((2,2))
W2 = tf.Variable(tf.zeros((2,2)), name="weights")
with tf.Session()as sess:
    print(sess.run(W1))
    sess.run(tf.initialize_all_variables())
    print(sess.run(W2))
[[1. 1.]
 [1. 1.]]
WARNING:tensorflow:From /root/.pyenv/versions/miniconda3-4.3.30/envs/caffe2/lib/python3.6/site-packages/tensorflow/python/util/tf_should_use.py:118: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
[[0. 0.]
 [0. 0.]]
with tf.Session()as sess:
    print(sess.run(W1))
    sess.run(tf.global_variables_initializer())
    print(sess.run(W2))
[[1. 1.]
 [1. 1.]]
[[0. 0.]
 [0. 0.]]
スポンサーリンク

TensorFlow Variables (3)

TensorFlow variables must be initialized before they have values! Contrast with constant tensors.
TensorFlow variablesは、値を持つ前に初期化されなければならない。定数テンソルと比較対照する。

W = tf.Variable(tf.zeros((2,2)), name="weights")
R = tf.Variable(tf.random_normal((2,2)), name="random_weights")
with tf.Session()as sess:
    sess.run(tf.initialize_all_variables()) #特定値で全変数を初期化
    print(sess.run(W))
    print(sess.run(R))
[[0. 0.]
 [0. 0.]]
[[ 1.7426577  -0.90834767]
 [-0.82732046 -0.9022767 ]]
スポンサーリンク

Updating Variable State

state = tf.Variable(0, name="counter")
new_value = tf.add(state, tf.constant(1)) # 大体new_value = state + 1
update = tf.assign(state, new_value) # 大体state = new_value
with tf.Session()as sess:
    sess.run(tf.initialize_all_variables()) # 大体state = 0 
    print(sess.run(state))                  # print(state)
    for _ in range(3):                      # for _ in range(3):
        sess.run(update)                    # state = state + 1
        print(sess.run(state))              # print(state)
0
1
2
3
スポンサーリンク

Fetching Variable State

input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
intermed = tf.add(input2, input3)
mul = tf.mul(input1, intermed)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-43-c4d968c66d81> in <module>()
----> 1 mul = tf.mul(input1, intermed)

AttributeError: module 'tensorflow' has no attribute 'mul'
mul = tf.multiply(input1, intermed)
with tf.Session()as sess:
    result = sess.run([mul, intermed])
    print(result)
[21.0, 7.0]
参考サイトCS224d:TensorFlow Tutorial

スポンサーリンク
スポンサーリンク