Codementor Events

Tensorflow basics

Published Feb 12, 2020Last updated Aug 26, 2021
Tensorflow basics

Machine learning might be frightening for beginners.

So let's learn something extremely simple so you could feel the ground.

Preface

The easiest way to play with tensorflow - is to use Google Colab notebook
Screenshot 2020-01-31 at 19.37.12.png

Important !

Lets make 2 initial steps

import tensorflow as tf
tf.enable_eager_execution() # for tensorflow 1.x

Constants and Variables

In machine learning everything is represented in numbers. Images, music, just simple tables - all of it is represented in numbers. In mathematics there is a beautiful term for it - Tensor. So tensor - is just a set of numbers.

Sensor could be a single number - 1 or 2 or 100500
In TF you can define it as

d0 = tf.ones((1,))
d0.numpy()

# result
# array([1.], dtype=float32)

tf.ones - create a tensor where every number inside of is 1. Parameters which you pass inside of it - is dimentions.

d0 = tf.ones((5,))
d0.numpy()

# result
# array([1., 1., 1., 1., 1.], dtype=float32)
d0 = tf.ones((5,5))
d0.numpy()

# result
# array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]], dtype=float32)
d0 = tf.ones((5,5,5))
d0.numpy()

# result
# array([[[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]],

       [[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]],

       [[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]],

       [[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]],

       [[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]]], dtype=float32

Do display tensor as a table - use method numpy()
It's working only when Eager Execution mode is enabled (We did it in the very beginning). What is eager mode I'll explain in futher tutorials.

Constants

Constant - just takes any values and make it immutable. You can pass almost any value

from tensorflow import constant

credit_constant = constant(15)
# <tf.Tensor: id=18, shape=(), dtype=int32, numpy=1>

credit_constant = constant([13,4])
# <tf.Tensor: id=19, shape=(), dtype=int32, numpy=1>

So there are 2 methods available for constant dtype and shape

credit_constant.dtype
# tf.int64

credit_constant.shape
# TensorShape([Dimension(2)])

Variables

A1 = Variable([1, 2, 3, 4])
# <tf.Variable 'Variable:0' shape=(4,) dtype=int32, numpy=array([1, 2, 3, 4], dtype=int32)>
#cool, right?

#So then we can convert it to numpy array 
B1 = A1.numpy()

#array([1, 2, 3, 4], dtype=int32)

Funny fact

Whatever you set up - variable or constant - it's all tensors.

Follow me in twitter
@alexpolymath

Discover and read more posts from Alex Polymath
get started