Introduction to TensorFlow in Python
Isaiah Hull
Visiting Associate Professor of Finance, BI Norwegian Business School
#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]])
# Perform tensor addition with add()
C0 = add(A0, B0)
C1 = add(A1, B1)
C2 = add(A2, B2)
The add()
operation performs element-wise addition with two tensors
Element-wise addition requires both tensors to have the same shape:
The add()
operator is overloaded
Element-wise multiplication performed using multiply()
operation
Matrix multiplication performed with matmul()
operator
matmul(A,B)
operation multiplies A by B# 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)
, and multiply(A34, A34)
matmul(A43, A34
), but not matmul(A43, A43)
reduce_sum()
operator sums over the dimensions of a tensorreduce_sum(A)
sums over all dimensions of Areduce_sum(A, i)
sums over dimension i# Import operations from tensorflow
from tensorflow import ones, reduce_sum
# Define a 2x3x4 tensor of ones
A = ones([2, 3, 4])
# 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