SlideShare a Scribd company logo
Robert John
GDE (GCP, ML)
@robert_thas
TensorFlow
What is TensorFlow and why do we use it?
TensorFlow is a numerical
computation library. It lets us
perform mathematical and
statistical operations on our
data.
Example
Predict the selling price of a house given the number of rooms
What is TensorFlow and why do we use it
What is TensorFlow and why do we use it
What is TensorFlow and why do we use it
● Medv => y
● Rooms => x
● Constant => b
● Gradients => w
Formulate a Hypothesis
This hypothesis is called a model
Without TensorFlow
import pandas as pd
import numpy as np
train_df = pd.read_csv('/content/gdrive/My
Drive/boston/train.csv', index_col='ID')
train_df.head()
What is TensorFlow and why do we use it
train_df[['rm', 'medv']].head()
y = train_df['medv'].values
train_df['constant'] = 1
columns = ['constant', 'rm']
x = train_df[columns].values
w = np.zeros((x.shape[1], 1))
y_pred = np.dot(x, w)
error = y - y_pred
print(error.shape)
squared_error = np.power(error, 2)
root_mean_squared_error = sqrt(squared_error.sum()) /
y_pred.shape[0]
print(root_mean_squared_error)
Training
costs = []
w_0_s = []
w_1_s = []
learning_rate = 1e-3
steps = 20
for a in range(steps):
w_0 = w[0][0]
w_1 = w[1][0]
# make prediction
y_pred = np.dot(x, w)
error = y - y_pred
error_squared = np.power(error, 2)
# cost function is Least Mean Squares
LMS = error_squared.sum() / (2 * y.shape[0])
costs.append(LMS)
w_0_s.append(w_0)
w_1_s.append(w_1)
# update
w_0 = w_0 + learning_rate/y.shape[0] * error.sum()
w_1 = w_1 + learning_rate/y.shape[0] * (error * x[1]).sum()
w[0][0] = w_0
w[1][0] = w_1
cost_df = pd.DataFrame({'cost': pd.Series(costs),
'w_0': pd.Series(w_0_s), 'w_1': pd.Series(w_1_s)})
cost_df['cost'].plot()
How good are the
predictions?
_w = [w_0, w_1]
_w = np.asarray(_w)
_x = train_df[['constant', 'rm']].values
y_pred = np.dot(_x, _w)
_p = pd.DataFrame(dict(actual=train_df['medv'].values,
predicted=y_pred.reshape(-1)))
_p.head()
What is TensorFlow and why do we use it
How is TensorFlow different?
class Model(object):
def __init__(self):
self.W = None
self.b = None
def __call__(self, x):
if self.W == None:
self.W = tf.Variable(tf.random.normal(shape=(1, x.shape[1])))
if self.b == None:
self.b = tf.Variable(tf.random.normal(shape=(x.shape[0], 1)))
return tf.matmul(x, self.W, transpose_b=True) + self.b
model = Model()
output = model(tf.constant([3.0, 3.1, 1.9, 2.0, 2.5, 2.9],
shape=(3,2)))
print(output)
@tf.function
def loss(y_pred, y):
return tf.reduce_mean(tf.square(y-y_pred))
def train(model, x, y, alpha):
x = tf.convert_to_tensor(x, np.float32)
y = tf.convert_to_tensor(y, np.float32)
with tf.GradientTape() as t:
t.watch(x)
current_loss = loss(model(x), y)
#print(current_loss)
dW, db = t.gradient(current_loss, [model.W, model.b])
#print(dW, db)
model.W.assign_sub(alpha * dW)
model.b.assign_sub(alpha * db)
train_df = df.sample(frac=0.8,random_state=0)
test_df = df.drop(train_df.index)
columns = ['nox', 'rm', 'chas', 'dis', 'ptratio', 'lstat', 'rad']
X_train = train_df[columns].values
X_test = test_df[columns].values
y_train = train_df[['medv']].values
y_test = test_df[['medv']].values
epochs = 10
model = Model()
for i in range(epochs):
train(model, X_train, y_train, alpha=0.1)
print(model.W)
● Vectors & Matrices
● Matrix Dot Products
● Differentiation
What was all that?
We got introduced to
● Learning Rates
● Gradient Descent
● Training Epochs
All of that was Linear Regression. How
about Neural Networks?
import tensorflow as tf
from tensorflow import keras
model = keras.Sequential([
keras.layers.Dense(50, input_shape=(7,), activation='relu'),
keras.layers.Dense(50, activation='relu'),
keras.layers.Dense(50, activation='relu'),
keras.layers.Dropout(0.5),
keras.layers.Dense(1)
])
print(model.summary())
What is TensorFlow and why do we use it
adam = keras.optimizers.Adam(0.001)
model.compile(optimizer=adam, loss='mse')
model.fit(X_train, y_train, epochs=2000, validation_split=0.1)
● Optimized operations
● Hardware acceleration
● Multiple languages/platforms
Benefits of using TensorFlow
● Layers
● Optimizers
● Loss Functions
● Feature Engineering
● Hyperparameter Tuning
● Model Optimization
● Transfer Learning
● Keras Preprocessing Layers
● Recommendations
● New features in tf.data
● Experimental Numpy support
What’s New in TensorFlow
● API Types (Keras, Estimators, etc)
● Originally graph-based vs. “pythonic”
Differences Between TensorFlow and Others
Learn More
Neural Networks and Deep Learning
http://neuralnetworksanddeeplearning.com/
Machine Learning Crash Course
https://developers.google.com/machine-learning/crash-course
TensorFlow
https://www.tensorflow.org/
Robert John
GDE (GCP, ML)
@robert_thas
Thank You!

More Related Content

PDF
Baby Steps to Machine Learning at DevFest Lagos 2019
PPTX
Python object oriented programming (lab2) (2)
PPTX
Introduction to TensorFlow
PDF
【AI実装4】TensorFlowのプログラムを読む2 非線形回帰
PPTX
Font classification with 5 deep learning models using tensor flow
PPTX
USE OF PRINT IN PYTHON PART 2
PDF
Traversals for all ocasions
PPTX
Exam Prediction Machine Learning Algorithm
Baby Steps to Machine Learning at DevFest Lagos 2019
Python object oriented programming (lab2) (2)
Introduction to TensorFlow
【AI実装4】TensorFlowのプログラムを読む2 非線形回帰
Font classification with 5 deep learning models using tensor flow
USE OF PRINT IN PYTHON PART 2
Traversals for all ocasions
Exam Prediction Machine Learning Algorithm

What's hot (19)

PDF
SupportVectorRegression
PPTX
Print input-presentation
PDF
Python programming : Standard Input and Output
PPTX
Graph Plots in Matlab
DOCX
Recursion in C
PDF
PPTX
Programming Assignment Help
PPTX
Matlab Visualizing Data
PDF
C++ extension methods
DOCX
PYTHON. AM CALL Pricing Trees
DOCX
Computer graphics
PDF
Computer graphics lab manual
PDF
Gentle Introduction to Functional Programming
DOCX
PDF
Day 4b iteration and functions for-loops.pptx
TXT
Gauss seidal Matlab Code
PDF
Project2
DOCX
Monte-carlo sim pricing EU call
SupportVectorRegression
Print input-presentation
Python programming : Standard Input and Output
Graph Plots in Matlab
Recursion in C
Programming Assignment Help
Matlab Visualizing Data
C++ extension methods
PYTHON. AM CALL Pricing Trees
Computer graphics
Computer graphics lab manual
Gentle Introduction to Functional Programming
Day 4b iteration and functions for-loops.pptx
Gauss seidal Matlab Code
Project2
Monte-carlo sim pricing EU call
Ad

Similar to What is TensorFlow and why do we use it (20)

PPTX
Introduction to Neural Networks and Deep Learning from Scratch
PPTX
TensorFlow for IITians
PDF
maXbox starter65 machinelearning3
PDF
The TensorFlow dance craze
PDF
Neural networks with python
PDF
Python + Tensorflow: how to earn money in the Stock Exchange with Deep Learni...
PDF
Gentlest Introduction to Tensorflow - Part 2
PDF
Gentlest Introduction to Tensorflow
PDF
Neural networks using tensor flow in amazon deep learning server
PDF
Theano vs TensorFlow | Edureka
PPTX
Machine Learning - Introduction to Tensorflow
DOCX
LSTM Framework For Univariate Time series
PPTX
Introduction to Tensorflow
PPTX
TensorFlow in Practice
PDF
Tensor flow description of ML Lab. document
PPTX
Machine Learning Essentials Demystified part2 | Big Data Demystified
PPTX
NeuralNets_DLbootcamp_Finaldayofseptember
PDF
Gradient Descent, Back Propagation, and Auto Differentiation - Advanced Spark...
PDF
Assignment 5.2.pdf
PDF
Introduction to Tensor Flow for Optical Character Recognition (OCR)
Introduction to Neural Networks and Deep Learning from Scratch
TensorFlow for IITians
maXbox starter65 machinelearning3
The TensorFlow dance craze
Neural networks with python
Python + Tensorflow: how to earn money in the Stock Exchange with Deep Learni...
Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow
Neural networks using tensor flow in amazon deep learning server
Theano vs TensorFlow | Edureka
Machine Learning - Introduction to Tensorflow
LSTM Framework For Univariate Time series
Introduction to Tensorflow
TensorFlow in Practice
Tensor flow description of ML Lab. document
Machine Learning Essentials Demystified part2 | Big Data Demystified
NeuralNets_DLbootcamp_Finaldayofseptember
Gradient Descent, Back Propagation, and Auto Differentiation - Advanced Spark...
Assignment 5.2.pdf
Introduction to Tensor Flow for Optical Character Recognition (OCR)
Ad

More from Robert John (7)

PPTX
DevFest 2022 Nairobi - Considerations for Deploying ML Models on Edge Devices...
PPTX
DevFest 2022 - Nairobi ML Keynote.pptx
PPTX
Arduino Certification
PDF
Fundamentals of cloud computing
PDF
What is Google Cloud Good For at DevFestInspire 2021
PDF
TinyML at DevFestLagos21
PDF
TinyML: Machine Learning for Microcontrollers
DevFest 2022 Nairobi - Considerations for Deploying ML Models on Edge Devices...
DevFest 2022 - Nairobi ML Keynote.pptx
Arduino Certification
Fundamentals of cloud computing
What is Google Cloud Good For at DevFestInspire 2021
TinyML at DevFestLagos21
TinyML: Machine Learning for Microcontrollers

Recently uploaded (20)

PPTX
Market Analysis -202507- Wind-Solar+Hybrid+Street+Lights+for+the+North+Amer...
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked 2025}
PDF
Business Analytics and business intelligence.pdf
PPTX
Leprosy and NLEP programme community medicine
PPTX
Managing Community Partner Relationships
PDF
[EN] Industrial Machine Downtime Prediction
PPT
DATA COLLECTION METHODS-ppt for nursing research
PPTX
Qualitative Qantitative and Mixed Methods.pptx
PPTX
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
PPT
Predictive modeling basics in data cleaning process
PPTX
A Complete Guide to Streamlining Business Processes
PPTX
Data_Analytics_and_PowerBI_Presentation.pptx
PDF
Mega Projects Data Mega Projects Data
PPTX
Acceptance and paychological effects of mandatory extra coach I classes.pptx
PDF
Galatica Smart Energy Infrastructure Startup Pitch Deck
PPTX
STERILIZATION AND DISINFECTION-1.ppthhhbx
PDF
Lecture1 pattern recognition............
PPTX
SAP 2 completion done . PRESENTATION.pptx
PDF
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
PPTX
CEE 2 REPORT G7.pptxbdbshjdgsgjgsjfiuhsd
Market Analysis -202507- Wind-Solar+Hybrid+Street+Lights+for+the+North+Amer...
Capcut Pro Crack For PC Latest Version {Fully Unlocked 2025}
Business Analytics and business intelligence.pdf
Leprosy and NLEP programme community medicine
Managing Community Partner Relationships
[EN] Industrial Machine Downtime Prediction
DATA COLLECTION METHODS-ppt for nursing research
Qualitative Qantitative and Mixed Methods.pptx
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
Predictive modeling basics in data cleaning process
A Complete Guide to Streamlining Business Processes
Data_Analytics_and_PowerBI_Presentation.pptx
Mega Projects Data Mega Projects Data
Acceptance and paychological effects of mandatory extra coach I classes.pptx
Galatica Smart Energy Infrastructure Startup Pitch Deck
STERILIZATION AND DISINFECTION-1.ppthhhbx
Lecture1 pattern recognition............
SAP 2 completion done . PRESENTATION.pptx
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
CEE 2 REPORT G7.pptxbdbshjdgsgjgsjfiuhsd

What is TensorFlow and why do we use it

  • 1. Robert John GDE (GCP, ML) @robert_thas TensorFlow What is TensorFlow and why do we use it?
  • 2. TensorFlow is a numerical computation library. It lets us perform mathematical and statistical operations on our data.
  • 3. Example Predict the selling price of a house given the number of rooms
  • 7. ● Medv => y ● Rooms => x ● Constant => b ● Gradients => w Formulate a Hypothesis This hypothesis is called a model
  • 9. import pandas as pd import numpy as np train_df = pd.read_csv('/content/gdrive/My Drive/boston/train.csv', index_col='ID') train_df.head()
  • 12. y = train_df['medv'].values train_df['constant'] = 1 columns = ['constant', 'rm'] x = train_df[columns].values w = np.zeros((x.shape[1], 1)) y_pred = np.dot(x, w)
  • 13. error = y - y_pred print(error.shape) squared_error = np.power(error, 2) root_mean_squared_error = sqrt(squared_error.sum()) / y_pred.shape[0] print(root_mean_squared_error)
  • 15. costs = [] w_0_s = [] w_1_s = [] learning_rate = 1e-3 steps = 20
  • 16. for a in range(steps): w_0 = w[0][0] w_1 = w[1][0] # make prediction y_pred = np.dot(x, w) error = y - y_pred error_squared = np.power(error, 2)
  • 17. # cost function is Least Mean Squares LMS = error_squared.sum() / (2 * y.shape[0]) costs.append(LMS) w_0_s.append(w_0) w_1_s.append(w_1) # update w_0 = w_0 + learning_rate/y.shape[0] * error.sum() w_1 = w_1 + learning_rate/y.shape[0] * (error * x[1]).sum() w[0][0] = w_0 w[1][0] = w_1
  • 18. cost_df = pd.DataFrame({'cost': pd.Series(costs), 'w_0': pd.Series(w_0_s), 'w_1': pd.Series(w_1_s)}) cost_df['cost'].plot()
  • 19. How good are the predictions?
  • 20. _w = [w_0, w_1] _w = np.asarray(_w) _x = train_df[['constant', 'rm']].values y_pred = np.dot(_x, _w) _p = pd.DataFrame(dict(actual=train_df['medv'].values, predicted=y_pred.reshape(-1))) _p.head()
  • 22. How is TensorFlow different?
  • 23. class Model(object): def __init__(self): self.W = None self.b = None def __call__(self, x): if self.W == None: self.W = tf.Variable(tf.random.normal(shape=(1, x.shape[1]))) if self.b == None: self.b = tf.Variable(tf.random.normal(shape=(x.shape[0], 1))) return tf.matmul(x, self.W, transpose_b=True) + self.b
  • 24. model = Model() output = model(tf.constant([3.0, 3.1, 1.9, 2.0, 2.5, 2.9], shape=(3,2))) print(output)
  • 25. @tf.function def loss(y_pred, y): return tf.reduce_mean(tf.square(y-y_pred))
  • 26. def train(model, x, y, alpha): x = tf.convert_to_tensor(x, np.float32) y = tf.convert_to_tensor(y, np.float32) with tf.GradientTape() as t: t.watch(x) current_loss = loss(model(x), y) #print(current_loss) dW, db = t.gradient(current_loss, [model.W, model.b]) #print(dW, db) model.W.assign_sub(alpha * dW) model.b.assign_sub(alpha * db)
  • 27. train_df = df.sample(frac=0.8,random_state=0) test_df = df.drop(train_df.index) columns = ['nox', 'rm', 'chas', 'dis', 'ptratio', 'lstat', 'rad'] X_train = train_df[columns].values X_test = test_df[columns].values y_train = train_df[['medv']].values y_test = test_df[['medv']].values
  • 28. epochs = 10 model = Model() for i in range(epochs): train(model, X_train, y_train, alpha=0.1) print(model.W)
  • 29. ● Vectors & Matrices ● Matrix Dot Products ● Differentiation What was all that? We got introduced to ● Learning Rates ● Gradient Descent ● Training Epochs
  • 30. All of that was Linear Regression. How about Neural Networks?
  • 31. import tensorflow as tf from tensorflow import keras model = keras.Sequential([ keras.layers.Dense(50, input_shape=(7,), activation='relu'), keras.layers.Dense(50, activation='relu'), keras.layers.Dense(50, activation='relu'), keras.layers.Dropout(0.5), keras.layers.Dense(1) ]) print(model.summary())
  • 33. adam = keras.optimizers.Adam(0.001) model.compile(optimizer=adam, loss='mse') model.fit(X_train, y_train, epochs=2000, validation_split=0.1)
  • 34. ● Optimized operations ● Hardware acceleration ● Multiple languages/platforms Benefits of using TensorFlow ● Layers ● Optimizers ● Loss Functions ● Feature Engineering ● Hyperparameter Tuning ● Model Optimization ● Transfer Learning
  • 35. ● Keras Preprocessing Layers ● Recommendations ● New features in tf.data ● Experimental Numpy support What’s New in TensorFlow
  • 36. ● API Types (Keras, Estimators, etc) ● Originally graph-based vs. “pythonic” Differences Between TensorFlow and Others
  • 37. Learn More Neural Networks and Deep Learning http://neuralnetworksanddeeplearning.com/ Machine Learning Crash Course https://developers.google.com/machine-learning/crash-course TensorFlow https://www.tensorflow.org/
  • 38. Robert John GDE (GCP, ML) @robert_thas Thank You!