LoginSignup
0
0

More than 3 years have passed since last update.

Tensorflowの用語集

Last updated at Posted at 2020-01-23

tensorflowの関数は説明してもわかりにくいので、使用例のみで解説します。

tf.Variable()

import tensorflow as tf
x = tf.Variable(10 , name="x")
y = x * 5
print(y)

出力
Tensor("mul_1:0", shape=(), dtype=int32)

上記のコードを見ると、出力が50のように思えますが、テンソルが出力されます。
では、次に、50が出力されるにはどのようにすればよいでしょうか。

x = tf.Variable(10 , name="x")
y = x * 5
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
sess.run(y)

出力50
tensorflowでは、tf.sessionを通じて計算グラフを構築して実行しなければいけません。tf.global_variables_initializer()は、計算グラフ内の変数の初期化の役割を果たします

tf.placeholder()

tf.placeholder(dtype, shape=None, name=None)

dtype: 変数に代入される型を代入します。
shape: 割り当てる変数のshape
name: 変数の名前

返り値
直接評価されない、feedされる変数のTensor

プログラム例

x = tf.placeholder(tf.int32)
y = tf.constant(1)
z = x + y
with tf.Session() as sess:
  print(sess.run(z, feed_dict={x: 2}))

出力
3
x=2を実行時に定義
次に、、tf.placeholderに配列を渡します。

x = tf.placeholder(tf.int32, shape=[2])
y = tf.placeholder(tf.int32, shape=[2])
z = x*y
with tf.Session() as sess:
  print(sess.run(z, feed_dict={x: [2, 1], y: [1, 2]}))

出力
[2 2]

tf.placeholder_with_default

tf.placeholder_with_defaultを使うことで、初期値を決められる、かつ、実行時に変更もできます。

x = tf.placeholder_with_default(1, shape=[])
y = tf.constant(1)
with tf.Session() as sess:
  print(sess.run(x + y))

出力
0

x = tf.placeholder_with_default(1, shape=[])
y = tf.constant(1)
with tf.Session() as sess:
  print(sess.run(x + y, feed_dict={x: -1}))

出力
2

tf.shape

tf.shapeは動的に変更されうるshapeに使用します。

x = tf.placeholder(tf.int32, shape=[None, 3])
size = tf.shape(x)[0]
sess = tf.Session()
sess.run(size, feed_dict={x: [[1, 2, 3], [1, 2, 3]]})

出力
2

.get_shape

.get_shapeは変更されないshapeに使用します。

x = tf.constant(1, shape=[2, 3, 4])
x.get_shape()[1]

出力
Dimension(3)

参考文献
Tensorflowで学ぶディープラーニング入門

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0