TensorFlow

【TensorFlow】Tensorの行列積を計算する方法

【TensorFlow】Tensorの行列積を計算する方法

Googleによって開発されている機械学習ライブラリであるTensorFlowで、Tenosorの行列積を計算する方法を解説します。

Tensorの行列積

ディープラーニング等の機械学習の実装ではよく行列積を計算します。本記事では、Tensorの行列積を計算する方法を紹介します。

tf.matmulによる行列積の計算

tf.matmulの使用方法

Tensorの行列積を計算するには、以下のようにtf.matmulを使用します。以降の例は簡単な例として同じTensor同士をかけていますが、もちろん異なるTensor同士でも問題ありません。

import tensorflow as tf

tensor = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=tf.float16)
print(tensor, "\n")

# Tensor同士の行列積を計算する tf.matmul
result = tf.matmul(tensor, tensor)
print(result)
【実行結果】
tf.Tensor(
[[1. 2. 3.]
 [4. 5. 6.]
 [7. 8. 9.]], shape=(3, 3), dtype=float16) 

tf.Tensor(
[[ 30.  36.  42.]
 [ 66.  81.  96.]
 [102. 126. 150.]], shape=(3, 3), dtype=float16)

行列積ではTensorの形状に注意

行列積では、形状に注意しましょう。例えば、以下のように形状が(3, 2)×(3, 2)のような掛け算をしてしまうとエラーとなります。

import tensorflow as tf

tensor = tf.constant([[1, 2], [3, 4], [5, 6]], dtype=tf.float16)
print(tensor, "\n")

# Tensorの形状に注意 以下はエラー
result = tf.matmul(tensor, tensor)
print(result)
【実行結果】
tensorflow.python.framework.errors_impl.InvalidArgumentError: Matrix size-incompatible: In[0]: [3,2], In[1]: [3,2] [Op:MatMul]

行列積では、形状が(3, 2)×(2, 3)や(2, 3)×(3, 2)のように内側の数字が一致している必要があります。また、計算結果は(3, 2)×(2, 3)→(3, 3)のように外側の数字が形状となるような計算結果となります。

必要に応じて転置して計算

必要に応じて以下のように行列を転置して行列積を計算するようにしましょう。転置では、tf.transposeを使用します。tf.transposeについては「Tensorを転置する方法」で紹介していますので興味があれば参考にしてください。

import tensorflow as tf

tensor = tf.constant([[1, 2], [3, 4], [5, 6]], dtype=tf.float16)
print(tensor, "\n")

# Tensorの形状に注意 必要に応じて転置をして計算
result = tf.matmul(tensor, tf.transpose(tensor))
print(result, "\n")

result = tf.matmul(tf.transpose(tensor), tensor)
print(result)
【実行結果】
tf.Tensor(
[[1. 2.]
 [3. 4.]
 [5. 6.]], shape=(3, 2), dtype=float16) 

tf.Tensor(
[[ 5. 11. 17.]
 [11. 25. 39.]
 [17. 39. 61.]], shape=(3, 3), dtype=float16) 

tf.Tensor(
[[35. 44.]
 [44. 56.]], shape=(2, 2), dtype=float16)

@演算子によるtf.matmulの実行 

Python3.5から@演算子(PEP 465)がサポートされていますが、TensorFlowのtf.matmulでも以下のように@演算子を用いて計算することができます。

import tensorflow as tf

tensor = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=tf.float16)
print(tensor, "\n")

# Tensor同士の行列積を計算する @演算子
result = tensor @ tensor
print(result)
【実行結果】
tf.Tensor(
[[1. 2. 3.]
 [4. 5. 6.]
 [7. 8. 9.]], shape=(3, 3), dtype=float16) 

tf.Tensor(
[[ 30.  36.  42.]
 [ 66.  81.  96.]
 [102. 126. 150.]], shape=(3, 3), dtype=float16)

以上のように@演算子でもtf.matmulを呼び出した場合と同じ結果となることが分かるかと思います。

Note

tf.matmulの公式ドキュメントはこちらを参照してください。正確には、tf.matmulは、tf.linalg.matmulのエイリアス(別名)となっています。

まとめ

Googleによって開発されている機械学習ライブラリであるTensorFlowで、Tenosorの行列積を計算する方法を解説しました。

Tensor同士の行列積を計算する際にはtf.matmulを使用します。また、Python3.5以降で使えるようになった@演算子でも計算することが可能です。

ディープラーニングをはじめとした機械学習では行列積は色々なところで出てきますので、使い方をしっかり覚えておくとよいかと思います。

Pythonによるディープラーニング」はTensorFlow/Kerasの中~上級者向けの本ですが非常におすすめできる書籍です。CNN, RNN, Transformer, GAN等高度なモデルも扱っており面白く、TensorFlow/Kerasの実装力をつけることができますので是非読んでみてもらえるといいと思います。