Constants and variables

Introduction to TensorFlow in Python

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

What is TensorFlow?

  • Open-source library for graph-based numerical computation
    • Developed by the Google Brain Team
  • Low and high level APIs
    • Addition, multiplication, differentiation
    • Machine learning models
  • Important changes in TensorFlow 2.0
    • Eager execution by default
    • Model building with Keras and Estimators
Introduction to TensorFlow in Python

What is a tensor?

  • Generalization of vectors and matrices
  • Collection of numbers
  • Specific shape
Introduction to TensorFlow in Python

What is a tensor?

The image shows a slice of bread, a slice of bread divided into 9 pieces, and a loaf of bread. Source: Public Domain Vectors

Introduction to TensorFlow in Python

Defining tensors in TensorFlow

import tensorflow as tf

# 0D Tensor
d0 = tf.ones((1,))
# 1D Tensor
d1 = tf.ones((2,))
# 2D Tensor
d2 = tf.ones((2, 2))
# 3D Tensor
d3 = tf.ones((2, 2, 2))
Introduction to TensorFlow in Python

Defining tensors in TensorFlow

# Print the 3D tensor
print(d3.numpy())
[[[1. 1.]
  [1. 1.]]

 [[1. 1.]
  [1. 1.]]]
Introduction to TensorFlow in Python

Defining constants in TensorFlow

  • A constant is the simplest category of tensor
    • Not trainable
    • Can have any dimension
from tensorflow import constant

# Define a 2x3 constant.
a = constant(3, shape=[2, 3])
# Define a 2x2 constant.
b = constant([1, 2, 3, 4], shape=[2, 2])
Introduction to TensorFlow in Python

Using convenience functions to define constants

Operation Example
tf.constant() constant([1, 2, 3])
tf.zeros() zeros([2, 2])
tf.zeros_like() zeros_like(input_tensor)
tf.ones() ones([2, 2])
tf.ones_like() ones_like(input_tensor)
tf.fill() fill([3, 3], 7)
Introduction to TensorFlow in Python

Defining and initializing variables

import tensorflow as tf

# Define a variable
a0 = tf.Variable([1, 2, 3, 4, 5, 6], dtype=tf.float32)
a1 = tf.Variable([1, 2, 3, 4, 5, 6], dtype=tf.int16)
# Define a constant
b = tf.constant(2, tf.float32)
# Compute their product
c0 = tf.multiply(a0, b)
c1 = a0*b
Introduction to TensorFlow in Python

Let's practice!

Introduction to TensorFlow in Python

Preparing Video For Download...