基本演算

Introduction to TensorFlow in Python

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

TensorFlow の演算とは?

画像は TensorBoard が描画した TensorFlow グラフの演算とテンソルを示します。2組の行列が add で結合され、その和が乗算されます。

Introduction to TensorFlow in Python

TensorFlow の演算とは?

画像は TensorBoard が描画した TensorFlow グラフの演算とテンソルを示します。1つの add 演算が表示されています。

Introduction to TensorFlow in Python

TensorFlow の演算とは?

画像は TensorBoard が描画した TensorFlow グラフの演算とテンソルを示します。2つの add 演算が表示されています。

Introduction to TensorFlow in Python

TensorFlow の演算とは?

画像は TensorBoard が描画した TensorFlow グラフの演算とテンソルを示します。2組の行列が add で結合され、その和が乗算されます。

Introduction to TensorFlow in Python

加算演算子の適用

#Import constant and add from tensorflow
from tensorflow import constant, add

# Define 0-dimensional tensors
A0 = constant([1])
B0 = constant([2])
# Define 1-dimensional tensors
A1 = constant([1, 2])
B1 = constant([3, 4])
# Define 2-dimensional tensors
A2 = constant([[1, 2], [3, 4]])
B2 = constant([[5, 6], [7, 8]])
Introduction to TensorFlow in Python

加算演算子の適用

# Perform tensor addition with add()
C0 = add(A0, B0)
C1 = add(A1, B1)
C2 = add(A2, B2)
Introduction to TensorFlow in Python

テンソルの加算を行う

  • add() は2つのテンソルの要素ごとの加算を行います

  • 要素ごとの加算には同じ形状が必要です:

    • スカラー加算: $1+2=3$
    • ベクトル加算: $[1,2]+[3,4]=[4,6]$
    • 行列加算: $\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} + \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix} = \begin{bmatrix} 6 & 8 \\ 10 & 12 \end{bmatrix}$
  • add() 演算子はオーバーロードされています

Introduction to TensorFlow in Python

TensorFlowでの乗算の実行方法

  • 要素ごとの乗算は multiply() を使用

    • 乗算するテンソルは同じ形状が必要
    • 例: [1,2,3] と [3,4,5]、または [1,2] と [3,4]
  • 行列乗算は matmul() を使用

    • matmul(A,B) は A に B を右から掛けます
    • A の列数は B の行数と等しい必要があります
Introduction to TensorFlow in Python

乗算演算子の適用

# Import operators from tensorflow
from tensorflow import ones, matmul, multiply

# Define tensors
A0 = ones(1)
A31 = ones([3, 1])
A34 = ones([3, 4])
A43 = ones([4, 3])

  • どの操作が有効ですか?
    • multiply(A0, A0)、multiply(A31, A31)、multiply(A34, A34)
    • matmul(A43, A34) は可、matmul(A43, A43) は不可
Introduction to TensorFlow in Python

次元に沿った総和の計算

  • reduce_sum() はテンソルの次元に沿って総和を取ります
    • reduce_sum(A) は A の全次元で総和
    • reduce_sum(A, i) は次元 i で総和
# Import operations from tensorflow
from tensorflow import ones, reduce_sum

# Define a 2x3x4 tensor of ones
A = ones([2, 3, 4])
Introduction to TensorFlow in Python

次元に沿った総和の計算

# Sum over all dimensions
B = reduce_sum(A)

# Sum over dimensions 0, 1, and 2
B0 = reduce_sum(A, 0)
B1 = reduce_sum(A, 1)
B2 = reduce_sum(A, 2)
Introduction to TensorFlow in Python

Let's practice!

Introduction to TensorFlow in Python

Preparing Video For Download...