SlideShare a Scribd company logo
1 of 40
Download to read offline
Baby Steps to Machine Learning
With TensorFlow 2.0
What is Machine Learning?
Machine Learning is learning from examples.
Formulate a hypothesis
Goal
We need data ...
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()
train_df[['rm', 'medv']].head()
Life without TF 2.0
y = train_df['medv'].values
train_df['constant'] = 1
columns = ['constant', 'rm', 'zn', 'indus']
x = train_df[columns].values
w = np.zeros((x.shape[1], 1))
y_pred = np.dot(x, w)
Measure the quality of
prediction
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)
Improve prediction quality
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()
Did the model improve?
_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()
That was a lot of work for
something basic
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))
This is the interesting part
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)
Could it be simpler?
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())
adam = keras.optimizers.Adam(0.001)
model.compile(optimizer=adam, loss='mse')
model.fit(X_train, y_train, epochs=2000, validation_split=0.1)
Let’s Engineer More Features
# we need a new way of getting data into the model
def df_to_dataset(df, columns, shuffle=True, batch_size=64):
df = df.copy()
labels = df.pop('medv')
features_df = df[columns]
ds = tf.data.Dataset.from_tensor_slices( (dict(features_df), labels) )
if shuffle:
ds = ds.shuffle(buffer_size=len(df))
ds = ds.batch(batch_size)
return ds
from sklearn.model_selection import train_test_split
train, val = train_test_split(df, test_size=0.1)
train_ds = df_to_dataset(train, columns)
val_ds = df_to_dataset(val, columns)
feature_columns = []
# numeric columns
for _col in columns:
feature_columns.append(tf.feature_column.numeric_column(_col))
# bucketize number of rooms
rm_buckets =
tf.feature_column.bucketized_column(tf.feature_column.numeric_column('rm
'), boundaries=[1, 2, 3, 4, 5, 6, 7, 8, 9])
rad_buckets =
tf.feature_column.bucketized_column(tf.feature_column.numeric_column('rad
'), boundaries=[1, 5, 10])
nox_buckets =
tf.feature_column.bucketized_column(tf.feature_column.numeric_column('nox
'), boundaries=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
feature_columns.append(rm_buckets)
feature_columns.append(rad_buckets)
feature_columns.append(nox_buckets)
featuresLayer = keras.layers.DenseFeatures(feature_columns)
model = keras.Sequential([
featuresLayer,
keras.layers.Dense(50, activation='relu'),
keras.layers.Dense(50, activation='relu'),
keras.layers.Dropout(0.5),
keras.layers.Dense(1)
])
model.compile(optimizer='adam', loss='mse')
model.fit(train_ds, epochs=50, validation_data=val_ds)
Neural Networks and Deep Learning
http://neuralnetworksanddeeplearning.com/
Learn More
Machine Learning Crash Course
https://developers.google.com/machine-lear
ning/crash-course
TensorFlow
https://www.tensorflow.org/
Robert John
@robert_thas
GDE: ML & Cloud
Baby Steps to Machine Learning

More Related Content

What's hot (19)

Traversals for all ocasions
Traversals for all ocasionsTraversals for all ocasions
Traversals for all ocasions
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
 
Application of partial derivatives with two variables
Application of partial derivatives with two variablesApplication of partial derivatives with two variables
Application of partial derivatives with two variables
 
Exam Prediction Machine Learning Algorithm
Exam Prediction Machine Learning Algorithm Exam Prediction Machine Learning Algorithm
Exam Prediction Machine Learning Algorithm
 
Cgm Lab Manual
Cgm Lab ManualCgm Lab Manual
Cgm Lab Manual
 
Graph Plots in Matlab
Graph Plots in MatlabGraph Plots in Matlab
Graph Plots in Matlab
 
Lr5
Lr5Lr5
Lr5
 
Programming Assignment Help
Programming Assignment HelpProgramming Assignment Help
Programming Assignment Help
 
Computer graphics
Computer graphics Computer graphics
Computer graphics
 
Matlab Visualizing Data
Matlab Visualizing DataMatlab Visualizing Data
Matlab Visualizing Data
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methods
 
Recursion in C
Recursion in CRecursion in C
Recursion in C
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
PYTHON. AM CALL Pricing Trees
PYTHON. AM CALL Pricing TreesPYTHON. AM CALL Pricing Trees
PYTHON. AM CALL Pricing Trees
 
Arrays
ArraysArrays
Arrays
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
 
Basics of Computer graphics lab
Basics of Computer graphics labBasics of Computer graphics lab
Basics of Computer graphics lab
 

Similar to Baby Steps ML TensorFlow 2.0

TensorFlow Dev Summit 2018 Extended: TensorFlow Eager Execution
TensorFlow Dev Summit 2018 Extended: TensorFlow Eager ExecutionTensorFlow Dev Summit 2018 Extended: TensorFlow Eager Execution
TensorFlow Dev Summit 2018 Extended: TensorFlow Eager ExecutionTaegyun Jeon
 
TensorFlow for IITians
TensorFlow for IITiansTensorFlow for IITians
TensorFlow for IITiansAshish Bansal
 
ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions Dr. Volkan OBAN
 
pandas dataframe notes.pdf
pandas dataframe notes.pdfpandas dataframe notes.pdf
pandas dataframe notes.pdfAjeshSurejan2
 
fds Practicle 1to 6 program.pdf
fds Practicle 1to 6 program.pdffds Practicle 1to 6 program.pdf
fds Practicle 1to 6 program.pdfGaneshPawar819187
 
Need help filling out the missing sections of this code- the sections.docx
Need help filling out the missing sections of this code- the sections.docxNeed help filling out the missing sections of this code- the sections.docx
Need help filling out the missing sections of this code- the sections.docxlauracallander
 
TensorFlow in Practice
TensorFlow in PracticeTensorFlow in Practice
TensorFlow in Practiceindico data
 
wk5ppt1_Titanic
wk5ppt1_Titanicwk5ppt1_Titanic
wk5ppt1_TitanicAliciaWei1
 
Help with implementing the four function the first is an exampleth.pdf
Help with implementing the four function the first is an exampleth.pdfHelp with implementing the four function the first is an exampleth.pdf
Help with implementing the four function the first is an exampleth.pdfaroraenterprisesmbd
 
support vector regression
support vector regressionsupport vector regression
support vector regressionAkhilesh Joshi
 
ML Assignment help.pptx
ML Assignment help.pptxML Assignment help.pptx
ML Assignment help.pptxRobinjk
 
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...Codemotion
 
From Tensorflow Graph to Tensorflow Eager
From Tensorflow Graph to Tensorflow EagerFrom Tensorflow Graph to Tensorflow Eager
From Tensorflow Graph to Tensorflow EagerGuy Hadash
 
Generic Functional Programming with Type Classes
Generic Functional Programming with Type ClassesGeneric Functional Programming with Type Classes
Generic Functional Programming with Type ClassesTapio Rautonen
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingTip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingPatrick Viafore
 
Introduction to Tensorflow
Introduction to TensorflowIntroduction to Tensorflow
Introduction to TensorflowTzar Umang
 
Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2Khor SoonHin
 

Similar to Baby Steps ML TensorFlow 2.0 (20)

Google TensorFlow Tutorial
Google TensorFlow TutorialGoogle TensorFlow Tutorial
Google TensorFlow Tutorial
 
TensorFlow Dev Summit 2018 Extended: TensorFlow Eager Execution
TensorFlow Dev Summit 2018 Extended: TensorFlow Eager ExecutionTensorFlow Dev Summit 2018 Extended: TensorFlow Eager Execution
TensorFlow Dev Summit 2018 Extended: TensorFlow Eager Execution
 
TensorFlow for IITians
TensorFlow for IITiansTensorFlow for IITians
TensorFlow for IITians
 
Practicle 1.docx
Practicle 1.docxPracticle 1.docx
Practicle 1.docx
 
ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions
 
pandas dataframe notes.pdf
pandas dataframe notes.pdfpandas dataframe notes.pdf
pandas dataframe notes.pdf
 
fds Practicle 1to 6 program.pdf
fds Practicle 1to 6 program.pdffds Practicle 1to 6 program.pdf
fds Practicle 1to 6 program.pdf
 
Need help filling out the missing sections of this code- the sections.docx
Need help filling out the missing sections of this code- the sections.docxNeed help filling out the missing sections of this code- the sections.docx
Need help filling out the missing sections of this code- the sections.docx
 
TensorFlow in Practice
TensorFlow in PracticeTensorFlow in Practice
TensorFlow in Practice
 
Ml all programs
Ml all programsMl all programs
Ml all programs
 
wk5ppt1_Titanic
wk5ppt1_Titanicwk5ppt1_Titanic
wk5ppt1_Titanic
 
Help with implementing the four function the first is an exampleth.pdf
Help with implementing the four function the first is an exampleth.pdfHelp with implementing the four function the first is an exampleth.pdf
Help with implementing the four function the first is an exampleth.pdf
 
support vector regression
support vector regressionsupport vector regression
support vector regression
 
ML Assignment help.pptx
ML Assignment help.pptxML Assignment help.pptx
ML Assignment help.pptx
 
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
 
From Tensorflow Graph to Tensorflow Eager
From Tensorflow Graph to Tensorflow EagerFrom Tensorflow Graph to Tensorflow Eager
From Tensorflow Graph to Tensorflow Eager
 
Generic Functional Programming with Type Classes
Generic Functional Programming with Type ClassesGeneric Functional Programming with Type Classes
Generic Functional Programming with Type Classes
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingTip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python Typing
 
Introduction to Tensorflow
Introduction to TensorflowIntroduction to Tensorflow
Introduction to Tensorflow
 
Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2
 

More from Robert John

DevFest 2022 Nairobi - Considerations for Deploying ML Models on Edge Devices...
DevFest 2022 Nairobi - Considerations for Deploying ML Models on Edge Devices...DevFest 2022 Nairobi - Considerations for Deploying ML Models on Edge Devices...
DevFest 2022 Nairobi - Considerations for Deploying ML Models on Edge Devices...Robert John
 
DevFest 2022 - Nairobi ML Keynote.pptx
DevFest 2022 - Nairobi ML Keynote.pptxDevFest 2022 - Nairobi ML Keynote.pptx
DevFest 2022 - Nairobi ML Keynote.pptxRobert John
 
Arduino Certification
Arduino CertificationArduino Certification
Arduino CertificationRobert John
 
Fundamentals of cloud computing
Fundamentals of cloud computingFundamentals of cloud computing
Fundamentals of cloud computingRobert John
 
What is Google Cloud Good For at DevFestInspire 2021
What is Google Cloud Good For at DevFestInspire 2021What is Google Cloud Good For at DevFestInspire 2021
What is Google Cloud Good For at DevFestInspire 2021Robert John
 
TinyML at DevFestLagos21
TinyML at DevFestLagos21TinyML at DevFestLagos21
TinyML at DevFestLagos21Robert John
 
TinyML: Machine Learning for Microcontrollers
TinyML: Machine Learning for MicrocontrollersTinyML: Machine Learning for Microcontrollers
TinyML: Machine Learning for MicrocontrollersRobert John
 

More from Robert John (7)

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

Recently uploaded

办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一F sss
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
 
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degreeyuu sss
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsappssapnasaifi408
 
9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home Service9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home ServiceSapana Sha
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingNeil Barnes
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptSonatrach
 
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024thyngster
 
ASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel CanterASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel Cantervoginip
 
Data Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxData Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxFurkanTasci3
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Jack DiGiovanna
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样vhwb25kk
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubaihf8803863
 
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一F La
 
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...ThinkInnovation
 
RadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfRadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfgstagge
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort servicejennyeacort
 
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)jennyeacort
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfSocial Samosa
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Sapana Sha
 

Recently uploaded (20)

办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
 
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
 
9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home Service9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home Service
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data Storytelling
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
 
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
 
ASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel CanterASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel Canter
 
Data Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxData Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptx
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
 
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
 
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
 
RadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfRadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdf
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
 
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
 

Baby Steps ML TensorFlow 2.0

  • 1. Baby Steps to Machine Learning With TensorFlow 2.0
  • 2. What is Machine Learning? Machine Learning is learning from examples.
  • 5. 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()
  • 6.
  • 9. y = train_df['medv'].values train_df['constant'] = 1 columns = ['constant', 'rm', 'zn', 'indus'] x = train_df[columns].values w = np.zeros((x.shape[1], 1)) y_pred = np.dot(x, w)
  • 10. Measure the quality of prediction
  • 11. 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)
  • 13. costs = [] w_0_s = [] w_1_s = [] learning_rate = 1e-3 steps = 20
  • 14. 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)
  • 15. # 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
  • 16. 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()
  • 17. Did the model improve?
  • 18. _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()
  • 19.
  • 20. That was a lot of work for something basic
  • 21.
  • 22. 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
  • 23. model = Model() output = model(tf.constant([3.0, 3.1, 1.9, 2.0, 2.5, 2.9], shape=(3,2))) print(output)
  • 24. @tf.function def loss(y_pred, y): return tf.reduce_mean(tf.square(y-y_pred))
  • 25. This is the interesting part
  • 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. Could it be simpler?
  • 30. 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())
  • 31.
  • 32. 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. # we need a new way of getting data into the model def df_to_dataset(df, columns, shuffle=True, batch_size=64): df = df.copy() labels = df.pop('medv') features_df = df[columns] ds = tf.data.Dataset.from_tensor_slices( (dict(features_df), labels) ) if shuffle: ds = ds.shuffle(buffer_size=len(df)) ds = ds.batch(batch_size) return ds
  • 35. from sklearn.model_selection import train_test_split train, val = train_test_split(df, test_size=0.1) train_ds = df_to_dataset(train, columns) val_ds = df_to_dataset(val, columns)
  • 36. feature_columns = [] # numeric columns for _col in columns: feature_columns.append(tf.feature_column.numeric_column(_col)) # bucketize number of rooms rm_buckets = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('rm '), boundaries=[1, 2, 3, 4, 5, 6, 7, 8, 9])
  • 37. rad_buckets = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('rad '), boundaries=[1, 5, 10]) nox_buckets = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('nox '), boundaries=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) feature_columns.append(rm_buckets) feature_columns.append(rad_buckets) feature_columns.append(nox_buckets)
  • 38. featuresLayer = keras.layers.DenseFeatures(feature_columns) model = keras.Sequential([ featuresLayer, keras.layers.Dense(50, activation='relu'), keras.layers.Dense(50, activation='relu'), keras.layers.Dropout(0.5), keras.layers.Dense(1) ]) model.compile(optimizer='adam', loss='mse') model.fit(train_ds, epochs=50, validation_data=val_ds)
  • 39. Neural Networks and Deep Learning http://neuralnetworksanddeeplearning.com/ Learn More Machine Learning Crash Course https://developers.google.com/machine-lear ning/crash-course TensorFlow https://www.tensorflow.org/
  • 40. Robert John @robert_thas GDE: ML & Cloud Baby Steps to Machine Learning