覚え書きブログ

tensor flowの覚え書き(よく使う関数のサンプルコード)

以下、よく使うtensorflowの関数のリファレンスと、サンプルコードを簡単にまとめておく。

  • tf.shape & tf.unstack:各次元の大きさを取得

サンプルコード:

x = tf.constant([[1,2,3],[4,5,6]])
z= tf.shape(x)
z1,z2=tf.unstack(tf.shape(x))
out = sess.run([z1,z2,z])

実行結果:

>>> out[0]
2
>>> out[1]
3
>>> out[2]
array([2, 3], dtype=int32)

https://www.tensorflow.org/api_docs/python/tf/reduce_all

サンプルコード:

import tensorflow as tf

x = tf.constant([[True,  True], [False, False]])
z1 = tf.identity(x)
z2 = tf.reduce_all(x)
z3 = tf.reduce_all(x,0)
z4 = tf.reduce_all(x,1)

sess = tf.Session()
out = sess.run([z1,z2,z3,z4])

実行結果:

>>> out[0]
array([[ True,  True],
       [False, False]], dtype=bool)
>>> out[1]
False
>>> out[2]
array([False, False], dtype=bool)
>>> out[3]
array([ True, False], dtype=bool)
  • tf.cond

https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/cond

サンプルコード: cond.py

import tensorflow as tf

x = tf.placeholder(tf.int32)
y = tf.placeholder(tf.int32)
z = tf.cond(x > y, lambda: tf.mutiply(x,y), lambda: tf.add(x,y))

sess = tf.Session()

sess.run(r, feed_dict={x:10,y:8})
sess.run(r, feed_dict={x:8,y:10})

実行結果:

> python cond.py
80
18
  • tf.one_hot

https://www.tensorflow.org/api_docs/python/tf/one_hot

サンプルコード:one_hot.py(https://tyfkda.github.io/blog/2016/09/03/one-hot.htmlを参照)

import tensorflow as tf

label = tf.placeholder(tf.int32,[None])
y = tf.one_hot(label, depth=3,dtype=tf.float32)

with tf.Session() as sess:
	sess.run(tf.global_variables_initializer())
	labelData = [1,0,2]
	
	print(sess.run(y,feed_dict={label:labelData}))

実行結果:

> python one_hot.py
[[ 0.  1.  0.]
 [ 1.  0.  0.]
 [ 0.  0.  1.]]
  • tf.reshape

https://www.tensorflow.org/api_docs/python/tf/reshape

サンプルコード:reshape.py

import tensorflow as tf
import numpy as np
import pdb

mat = tf.placeholder(tf.int32,[2,2])
horVec = tf.reshape(mat,[1,-1])
verVec = tf.reshape(mat,[-1,1])

with tf.Session() as sess:
	sess.run(tf.global_variables_initializer())
	matData = np.array([[1,2],[3,4]])
	
	print(sess.run(horVec,feed_dict={mat:matData}))
	print(sess.run(verVec,feed_dict={mat:matData}))
	

実行結果:

> python reshape.py
[[1 2 3 4]]
[[1]
 [2]
 [3]
 [4]]
  • control_flow_ops.while_loop

https://www.tensorflow.org/api_docs/python/tf/while_loop

サンプルコード:while_loop.py

import tensorflow as tf
from tensorflow.python.ops import control_flow_ops

condition = lambda x: tf.less(x,10)
body = lambda x: tf.add(x,1)
result = tf.while_loop(condition,body,loop_vars=[tf.constant(0)])

with tf.Session() as sess:
	print(sess.run(result))

実行結果:

> python while_loop.py
10
  • tf.reduce_sum

https://www.tensorflow.org/api_docs/python/tf/reduce_sum

サンプルコード:reduce_sum.py

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32,[2,2])
res = tf.reduce_sum(x)
res0 = tf.reduce_sum(x,0)
res1 = tf.reduce_sum(x,1)

xData = np.array([[1,2],[3,4]])
print(xData)

with tf.Session() as sess:
	print(sess.run(res,feed_dict={x:xData}))
	print(sess.run(res0,feed_dict={x:xData}))
	print(sess.run(res1,feed_dict={x:xData}))

実行結果:

> python reduce_sum.py
10.0
[ 4.  6.]
[ 3.  7.]
  • tf.multinomial

https://www.tensorflow.org/api_docs/python/tf/multinomial

サンプルコード

>>> samples = tf.multinomial([[10.,10.,10.,10.],[10,5,1,2]],100)
>>> data = tf.Session().run(samples)
array([[3, 2, 1, 2, 1, 3, 2, 0, 3, 2, 2, 2, 3, 0, 3, 2, 0, 2, 3, 0, 1, 3,
        2, 1, 0, 1, 2, 3, 3, 0, 0, 1, 2, 2, 1, 3, 1, 1, 3, 2, 1, 2, 0, 0,
        0, 2, 2, 2, 3, 1, 2, 2, 1, 3, 2, 2, 3, 0, 0, 2, 0, 3, 2, 1, 1, 0,
        2, 2, 2, 1, 3, 0, 3, 3, 0, 0, 1, 1, 1, 2, 3, 0, 1, 0, 2, 0, 1, 0,
        3, 3, 0, 2, 0, 1, 3, 2, 1, 1, 3, 1],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int64)
>>> data.shape
(2, 100)
  • tf.cast

https://www.tensorflow.org/api_docs/python/tf/cast

サンプルコード

>>> x=tf.cast([3.5],tf.int32)
>>> tf.Session().run(x)
array([3])
  • tf.nn.softmax, tf.log

サンプルコード

>>> x=tf.nn.softmax([3.,5.,8.])
>>> y=tf.log(x)
>>> tf.Session().run(x)
array([ 0.00637746,  0.04712342,  0.94649917], dtype=float32)
>>> tf.Session().run(y)
array([-5.05498505, -3.05498528, -0.05498519], dtype=float32)
  • TensorArray.write, TensorArray.stack

https://www.tensorflow.org/api_docs/python/tf/TensorArray

サンプルコード:write.py

import tensorflow as tf
import numpy as np
from tensorflow.python.ops import tensor_array_ops

x = tensor_array_ops.TensorArray(tf.float32, size=1, dynamic_size=True)
x = x.write(0,[1.,2.,3.])
x = x.write(1,[4.,5.,6.])
x_stack = x.stack()

with tf.Session() as sess:
	print(sess.run(x_stack))

実行結果:

> python write.py
[[ 1.  2.  3.]
 [ 4.  5.  6.]]
  • tf.nn.embedding_lookup

https://www.tensorflow.org/api_docs/python/tf/nn/embedding_lookup
https://qiita.com/kzmssk/items/ddf2c0f956a5d26e992a


サンプルコード: embedding_lookup.py

import tensorflow as tf

mat = tf.Variable(tf.random_normal([10,2]))
row = tf.placeholder(tf.int32)
vec = tf.nn.embedding_lookup(mat,row)

with tf.Session() as sess:
	sess.run(tf.global_variables_initializer())
	print(sess.run(mat))
	print('\n')
	print(sess.run(vec,feed_dict={row:0}))
	print(sess.run(vec,feed_dict={row:1}))
	print(sess.run(vec,feed_dict={row:2}))

実行結果:

> python embedding_lookup.py
[[ 0.30621392  0.98398387]
 [ 0.01169056  1.02503967]
 [ 0.1355008  -0.9375686 ]
 [ 1.43193841 -0.41342837]
 [ 0.14761457 -0.68711025]
 [-1.2051816   0.83872139]
 [ 0.31514356 -1.93323302]
 [-0.24086781  0.74751008]
 [ 0.08549079  1.30425262]
 [ 0.802674    1.22546017]]


[ 0.30621392  0.98398387]
[ 0.01169056  1.02503967]
[ 0.1355008 -0.9375686]
  • tf.unstack

https://www.tensorflow.org/api_docs/python/tf/unstack

サンプルコード:unstack.py

import tensorflow as tf
import numpy as np
import pdb

rows = 2
colmns = 3
batch_size = 5 # number of data in minibatch

# unstack x
x = tf.placeholder("float",[batch_size,rows,colmns])
unstack_x = tf.unstack(x)
unstack_rows_x = tf.unstack(x,rows,1)
unstack_colmns_x = tf.unstack(x,colmns,2)

# random data
data = np.random.normal(size=(batch_size, rows, colmns))
unstack_data=tf.Session().run(unstack_x, feed_dict={x:data})
unstack_rows_data=tf.Session().run(unstack_rows_x, feed_dict={x:data})
unstack_colmns_data=tf.Session().run(unstack_colmns_x, feed_dict={x:data})

unstack_data_array=np.array(unstack_data)
unstack_rows_data_array=np.array(unstack_rows_data)
unstack_colmns_data_array=np.array(unstack_colmns_data)

print('--- original data ---')
print(data.shape)
print(data)

print('--- unstack data ---')
print(unstack_data_array.shape)
print(unstack_data)

print('--- unstack row data ---')
print(unstack_rows_data_array.shape)
print(unstack_rows_data)

print('--- unstack colmns data ---')
print(unstack_colmns_data_array.shape)
print(unstack_colmns_data)

実行結果:

> python unstack.py
(5, 2, 3)
[[[ 0.36747729 -0.03858983  1.61786109]
  [ 0.80340371  0.20084246  0.66172545]]

 [[-1.1942069  -1.53454667  0.4149904 ]
  [-0.22525373  1.23734216  1.05743829]]

 [[-0.64167119 -0.79556116  0.03724453]
  [-1.15122393 -0.3460297  -0.15911808]]

 [[ 0.72109669 -1.5225345  -0.13874245]
  [-0.78036678  0.34260593 -0.01245939]]

 [[-0.74638409  0.03377243 -0.27415972]
  [ 1.11680802 -0.80291297  0.46227411]]]
--- unstack data ---
(5, 2, 3)
[array([[ 0.3674773 , -0.03858983,  1.61786103],
       [ 0.80340374,  0.20084246,  0.66172546]], dtype=float32),
 array([[-1.19420695, -1.53454661,  0.4149904 ],
       [-0.22525373,  1.23734212,  1.05743825]], dtype=float32),
 array([[-0.64167118, -0.79556113,  0.03724453],
       [-1.1512239 , -0.3460297 , -0.15911809]], dtype=float32),
 array([[ 0.72109669, -1.52253449, -0.13874245],
       [-0.78036678,  0.34260592, -0.01245939]], dtype=float32),
 array([[-0.74638408,  0.03377243, -0.27415973],
       [ 1.11680806, -0.80291295,  0.4622741 ]], dtype=float32)]
--- unstack row data ---
(2, 5, 3)
[array([[ 0.3674773 , -0.03858983,  1.61786103],
       [-1.19420695, -1.53454661,  0.4149904 ],
       [-0.64167118, -0.79556113,  0.03724453],
       [ 0.72109669, -1.52253449, -0.13874245],
       [-0.74638408,  0.03377243, -0.27415973]], dtype=float32),
 array([[ 0.80340374,  0.20084246,  0.66172546],
       [-0.22525373,  1.23734212,  1.05743825],
       [-1.1512239 , -0.3460297 , -0.15911809],
       [-0.78036678,  0.34260592, -0.01245939],
       [ 1.11680806, -0.80291295,  0.4622741 ]], dtype=float32)]
--- unstack colmns data ---
(3, 5, 2)
[array([[ 0.3674773 ,  0.80340374],
       [-1.19420695, -0.22525373],
       [-0.64167118, -1.1512239 ],
       [ 0.72109669, -0.78036678],
       [-0.74638408,  1.11680806]], dtype=float32),
 array([[-0.03858983,  0.20084246],
       [-1.53454661,  1.23734212],
       [-0.79556113, -0.3460297 ],
       [-1.52253449,  0.34260592],
       [ 0.03377243, -0.80291295]], dtype=float32),
 array([[ 1.61786103,  0.66172546],
       [ 0.4149904 ,  1.05743825],
       [ 0.03724453, -0.15911809],
       [-0.13874245, -0.01245939],
       [-0.27415973,  0.4622741 ]], dtype=float32)]
  • tf.identity

https://www.tensorflow.org/api_docs/python/tf/identity

サンプルコード:identity.py

import tensorflow as tf
import numpy as np

x = tf.placeholder('float',[2,2])
y = tf.identity(x)

data = np.random.normal(size=(2,2))
print("data:",data)
print("y:",tf.Session().run(y,feed_dict={x:data}))

実行結果:

> python identity.py
data: [[ 0.0106412  -0.63326245]
 [ 2.09857942 -0.50383664]]
y: [[ 0.0106412  -0.63326246]
 [ 2.09857941 -0.50383663]]]