LoginSignup
23
16

More than 5 years have passed since last update.

TensorFlowのRank, Shapeについて

Posted at

TensorFlowのRank, Shapeについて以下を参考にして説明します。
(詳しくは本家サイトへ)

Tensor Ranks, Shapes, and Types
https://www.tensorflow.org/versions/r0.8/resources/dims_types.html

tensorの生成

tensorとは行列のようなもので以下のように宣言します。
[1, 2, 3]

コードにすると

tf_01.py
import tensorflow as tf
x = tf.constant([1,2,3])
print x      #tensor情報の出力

sess = tf.Session()
print sess.run(x) #tensor自体の出力

 

実行結果
$ python tf_01.py
Tensor("Const:0", shape=(3,), dtype=int32)
[1 2 3]

x = tf.constant([1,2,3])
この行にtensorを指定します。いろいろ試してみてください

x = tf.constant([[1,2,3], [4,5,6], [7,8,9,], [0,2,3]])
とすると

実行結果
Tensor("Const:0", shape=(4, 3), dtype=int32)
[[1 2 3]
 [4 5 6]
 [7 8 9]
 [0 2 3]]

x = tf.constant([[1,2,3], [4,5,6], [7,8,9,], [0,2,3], [9,8]])
のように中途半端なtensorはエラーになるので、どのような場合にエラーになるかならないか色々調べるのも良いでしょう。

rank

tensorにはrankという概念があります。数学でもrank(階数)が出てきますが、数学のそれとは少し異なります。
[ ]のネストの数がrankです。つまり

rank = 1
x = tf.constant([1,2,3])

rank = 2
x = tf.constant([[1,2,3], [4,5,6], [7,8,9,], [0,2,3]])

rank = 3
x = tf.constant([ [[1,2], [3,4]], [[5,6], [7,8]] ]
x = tf.constant([[[1]]]) これも3段入れ子なのでrank = 3

[ ]のネスト(入れ子)が何段になっているか数えます。
tf_01.pyの最後にprint sess.run(tf.rank(x))を追加するとrankも計算してくれます。

shape

最後にshapeです。shapeはtensorの形を示します。

先ほどの実行結果にこのようなものがありましたね。
shape=(4, 3)がまさにshapeを表しています。
行列のように考えるとこれは4x3なのでshape=(4, 3)です。

また2段目の[ ]が4つ、その中に要素が3つあるのでshape=(4, 3)と考える事もできます。

実行結果
Tensor("Const:0", shape=(4, 3), dtype=int32)
[[1 2 3]
 [4 5 6]
 [7 8 9]
 [0 2 3]]

1次元目の要素数、2次元目の要素数、n次元目の要素数と数えます。
外側から[ ]の数を数えていき、最終的には[ ]の中身の要素数を数える事もできます。

もう1つ例です。

tf_02.py
import tensorflow as tf
x = tf.constant([ [[1,2], [3,4], [5,6]], [[7,8], [9,10], [11, 12]]])
print x

sess = tf.Session()
print sess.run(x)
print sess.run(tf.rank(x))

 

実行結果
Tensor("Const:0", shape=(2, 3, 2), dtype=int32)
[[[ 1  2]
  [ 3  4]
  [ 5  6]]

 [[ 7  8]
  [ 9 10]
  [11 12]]]
3

1次元目の要素数 = 2  //2段目[ ]が何個あるか
2次元目の要素数 = 3   //3段目[ ]が何個あるか
3次元目の要素数 = 2   //3段目[ ]内の要素数

tensorflowは現在勉強中で間違い等あるかもしれません。
以上

23
16
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
23
16