AI 事始め7:ちょっと寄り道:tensorflow行列の表記とPythonのお勉強
tensorflow ハードウェア条件の確認をした時に、行列の表記と行列の掛け算が出現したので、整理して覚える。また、ついでに,shape=[2, 3]のa行列とshape=[3, 2]のb行列の掛け算 tf.matmul(a, b)のCPUのみでの計算速度を測定する。
まずは、表記を調べる。
# Constant 2-D tensor populated with scalar value -1.
tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]
[-1. -1. -1.]]
であるから、
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') => [ [1.0, 2.0, 3.0]
[4.0, 5.0, 6.0] ]
0行目が「[1.0, 2.0, 3.0]」、1行目が「[4.0, 5.0, 6.0]」となります。同様に、
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b') => [ [1.0, 2.0]
[3.0,4.0]
[5.0, 6.0] ]
0行目が「[1.0, 2.0]」、1行目が「[3.0,4.0]」、2行目が「[5.0, 6.0]」となります。
c = tf.matmul(a, b)は、これらの掛け算ですから、結果は2行2列になります。
[ [(1x1+2x3+3x5),(1x2+2x4+3x6)] => [ [22., 28.]
[(4x1+5x3+6x5),(4x2+5x4+6x6)] ] [49., 64.] ]
次に、Pythonのお勉強を兼ねて、tf.matmul(a, b)のCPUのみでの計算速度を測定するためのコード追加します。
tf.matmul(a, b)の計算を10000回実行する時間を、10回測定するコードにしました。
import datetime
import tensorflow as tf
# Creates a graph.
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
for j in range(10):
date_start = datetime.datetime.now()
for i in range(10000):
sess.run(c)
date_stop = datetime.datetime.now()
print(j+1,"th: ","Elapsed Time is ",date_stop - date_start)
実行結果は、下記でした。
1 th: Elapsed Time is 0:00:01.076265
2 th: Elapsed Time is 0:00:01.047991
3 th: Elapsed Time is 0:00:01.048166
4 th: Elapsed Time is 0:00:01.043658
5 th: Elapsed Time is 0:00:01.052522
6 th: Elapsed Time is 0:00:01.046874
7 th: Elapsed Time is 0:00:01.053725
8 th: Elapsed Time is 0:00:01.046891
9 th: Elapsed Time is 0:00:01.051101
10 th: Elapsed Time is 0:00:01.101507
約1秒というところでしょうか。
ここまでくると、上の計算は、シロウトがコードを書いた場合に比べてどの程度速いのかという興味が湧いてきます。VisualStudioは入っているし、C/C++の知識が残っていれば検討可能そうですが、最近のコンパイラは賢くなっているだろうし、下手なコードを書くと、最適化で所望の命令コードにならないかも。そして、どんどん脇道に逸れてしまい、AIの道に進めなくなりそうです。
当面は自粛しましょう。