SlideShare a Scribd company logo
Introduction to
Keras and TensorFlow
Qing Wan and Yoonsuck Choe
Texas A&M University
Outline
• Background → NVIDIA CUDA GPU
• Installation
• Basic skills to write a machine learning model
• A specific case: XOR gate
Keras
• A python package (Python 2.7-3.6)
• Sits on top of TensorFlow or Theano (Stopped)
• High-level neural network API
• Runs seamlessly on CPU and GPU
• Open source with user manual (https://keras.io/)
• Less coding lines required to build/run a model
TensorFlow
• Inherit from Theano (data flow graph)
• A python(3.5-3.7) package/C++ library
• Running on CPU or NVIDIA CUDA GPU
• End-2-End platform for machine/deep learning
• Multi platform (desktop, web by TF.js, mobile by TF
Lite)
• Open source with user manual
(https://www.tensorflow.org/)
• More coding lines required to build/run a model
NVIDIA CUDA Toolkit
• C/C++ library
• A parallel computing platform for NVIDIA GPU
• Most deep learning researchers rely on
• GPU-accelerated computing/applications
• Not open source (https://developer.nvidia.com/cuda-zone)
• CPU vs GPU: TensorFlow training CNN model on CIFAR10 images
Anaconda3 Installation
• Anaconda3
• Download (https://www.anaconda.com/distribution/)
• Installation (https://docs.anaconda.com/anaconda/install/)
• Restart required
TensorFlow/Keras Installation
• Start the anaconda navigator
• Windows: Start->All program->Anaconda3-
>Anaconda Navigator
• Linux: type “anaconda-navigator” under the
linux terminal
• Install TensorFlow and Keras
• Environments->choose All
• type “tensorflow”
• CPU based:
tensorflow (choose 1.14)
keras (2.2.4) apply
• GPU based:
• CUDA Compute Capability >= 3.0, better
>= 3.7 (check more)
• tensorflow-gpu (choose 1.14) and keras-
gpu (2.2.4), then apply
Installation Confirmed
• TensorFlow test code:
import tensorflow as tf
sess = tf.compat.v1.Session()
a = tf.compat.v1.constant(1)
b = tf.compat.v1.constant(2)
print(sess.run(a+b))
• Expect to have answer 3
Installation Confirmed
• Keras requires backend setting for Windows users:
• https://keras.io/backend/
• Setting in keras.json:
“backend”: “tensorflow”
• Keras test code:
import keras
• Expect to see
Using TensorFlow backend
Keras Models
• Two main types of models available
• The Sequential model (easy to learn, high-level API)
• A linear stack of layers
• Need to specify what input shape it should expect (input dimension)
• https://keras.io/getting-started/sequential-model-guide/
• The Model class used with the functional API (similar to tensorflow2.0)
• https://keras.io/models/about-keras-models/
• https://keras.io/getting-started/functional-api-guide/
Keras Sequential Model
• Define a sequential model
model = Sequential()
mode.add(Dense(32, input_dim=784))
model.add(Activation(‘relu’))
model.add(Dense(10))
model.add(Activation(‘softmax’))
• Compilation
model.compile(optimizer=‘rmsprop’,
loss=‘binary_crossentropy’,
metrics=[‘accuray’])
• Training
model = model.fit(data, one_hot_labels,
epoch=10, batch_size=32)
• Predition
Y = model.predict(X)
Case Study: XOR gate
import numpy as np
# import necessary packages or APIs from keras
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
from keras.initializers import RandomUniform
# Prepare data and labels
X = np.asarray([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.float32)
Y = np.asarray([[0], [1], [1], [0]], dtype=np.float32)
# Build a model
model = Sequential()
model.add(Dense(units=2, activation='tanh', use_bias=True,
kernel_initializer=RandomUniform(minval=-1, maxval=1,
seed=None), input_dim=2))
model.add(Dense(units=1, activation='sigmoid', use_bias=True,
kernel_initializer=RandomUniform(minval=-1, maxval=1,
seed=None)))
# Build optimizer and do model
compilation op = SGD(lr=0.01,
momentum=0.0) model.compile(optimizer=op,
loss='mse',
metrics=['accuracy'])
# Start to train
model.fit(x=X, y=Y, epochs=20000, batch_size=4, shuffle=True)
# Prediction
Y = model.predict(X)
Case Study: XOR gate
• Training log
4/4 [==============================] - 2s 454ms/step - loss: 0.2538 - acc: 0.7500
Epoch 2/20000
...
4/4 [==============================] - 0s 2ms/step - loss: 0.2531 - acc: 0.5000
Epoch 100/20000
…
4/4 [==============================] - 0s 1ms/step - loss: 0.2511 - acc: 0.5000
Epoch 1000/20000
…
4/4 [==============================] - 0s 2ms/step - loss: 0.2291 - acc: 0.7500
Epoch 10000/20000
…
4/4 [==============================] - 0s 1ms/step - loss: 0.0254 - acc: 1.0000
Epoch 20000/20000
4/4 [==============================] - 0s 1ms/step - loss: 0.0254 - acc: 1.0000
• Prediction
Y = [[0.1462788 ]
[0.8177988 ]
[0.8254448 ]
[0.12802514]]
TensorFlow Models
• What is Tensor?
• An object (constant, scalar, vector, matrix, …)
• Allow to define ops (+, -, *, /, sum, max, concatenate, …) on
• TensorFlow Model
• A function with learnable parameters
• Maps input to an output by ops
• Parameters are all defined by yourself
• Model itself
• Loss
• Optimizer
• Whether a parameter is learnable
• Data operation
More flexible than Keras
More complex than Keras
Build a TensorFlow Model
• Two ways to build a machine learning model
• Using the layers API where you build a model using layers
e.g. tf.keras.layers.Dense, tf.layers.Conv2D, …
• Using the Core API with lower-level ops
e.g. tf.math.add, tf.math.abs, tf.concat, …
Case Study:
XOR gate
import numpy as np
import tensorflow as tf
# Prepare data and labels
data = np.asarray([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]], dtype=np.float32)
# Build a model
x = tf.compat.v1.placeholder(tf.float32, shape=[None, 2], name='x_in') # input
label = tf.compat.v1.placeholder(tf.float32, shape=[None, 1], name='label') # label
hidden = tf.keras.layers.Dense(units=2, activation=tf.nn.tanh, use_bias=True,
kernel_initializer=tf.keras.initializers.RandomUniform(minval=-1, maxval=1))(x)
pred = tf.compat.v1.keras.layers.Dense(units=1, activation=tf.nn.sigmoid, use_bias=True,
kernel_initializer=tf.keras.initializers.RandomUniform(minval=-1, maxval=1))(hidden)
cost = tf.compat.v1.norm(tf.math.subtract(label, pred), ord=2, name='cost')
op = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
training_epochs = 20000
# Set GRAM allocation
config = tf.compat.v1.ConfigProto(device_count={'GPU': 1})
config.gpu_options.per_process_gpu_memory_fraction = 0.5
# Start a Session to train and test
with tf.compat.v1.Session(config=config) as sess:
sess.run(tf.compat.v1.global_variables_initializer())
# Train
for epoch in range(training_epochs):
loss = 0
for d in data:
training_X, training_Y = np.asarray(d[0:2], dtype=np.float32), np.asarray(d[2], dtype=np.float32)
training_X, training_Y = np.expand_dims(training_X, axis=0), np.expand_dims([training_Y], axis=0)
sess.run(op, feed_dict={x: training_X, label: training_Y})
loss += sess.run(cost, feed_dict={x: training_X, label: training_Y})
if epoch % 100 == 0:
print("epoch: %d, loss = %f" % (epoch, loss))
# Test
for d in data:
Y = sess.run(pred, feed_dict={x: np.expand_dims(np.asarray(d[0:2], dtype=np.float32), axis=0)})
print("d = ", d, "output = ", Y)
Case Study: XOR gate
• Training log • Prediction
epoch: 0, loss = 2.025534 d = [0. 0. 0.] output = [[0.00028096]]
epoch: 100, loss = 1.963005 d = [0. 1. 1.] output = [[0.9994849]]
… d = [1. 0. 1.] output = [[0.99948573]]
epoch: 1000, loss = 0.051374
…
epoch: 10000, loss = 0.003195
…
epoch: 19800, loss = 0.001572
epoch: 19900, loss = 0.001564
d = [1. 1. 0.] output = [[0.0002458]]
Case Study: XOR gate
• What happen if we remove kernel_initialization in both Keras model
and TensorFlow model?
• Try if you are interested
• Do we really get the right answer?
• Are these results stable?
• What’s a potential cause to this?
Summary
As two popular deep learning packages
• Keras
• User friendly with high-level APIs
• Quick to get started
• Coding less lines for machine learning model construction/training/testing
• Sometimes training convergence is not stable.
• TensorFlow
• Flexible for developing new machine learning model
• Multi platform
• Community support
• Not friendly for new learner due to many low level APIs
Thanks

More Related Content

Similar to slide-keras-tf.pptx

Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame Graphs
Brendan Gregg
 
Reusable, composable, battle-tested Terraform modules
Reusable, composable, battle-tested Terraform modulesReusable, composable, battle-tested Terraform modules
Reusable, composable, battle-tested Terraform modules
Yevgeniy Brikman
 
Gpu programming with java
Gpu programming with javaGpu programming with java
Gpu programming with java
Gary Sieling
 
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017
StampedeCon
 
Machine Learning and Go. Go!
Machine Learning and Go. Go!Machine Learning and Go. Go!
Machine Learning and Go. Go!
Diana Ortega
 
How Many Ohs? (An Integration Guide to Apex & Triple-o)
How Many Ohs? (An Integration Guide to Apex & Triple-o)How Many Ohs? (An Integration Guide to Apex & Triple-o)
How Many Ohs? (An Integration Guide to Apex & Triple-o)
OPNFV
 
D Trace Support In My Sql Guide To Solving Reallife Performance Problems
D Trace Support In My Sql Guide To Solving Reallife Performance ProblemsD Trace Support In My Sql Guide To Solving Reallife Performance Problems
D Trace Support In My Sql Guide To Solving Reallife Performance ProblemsMySQLConference
 
Anirudh Koul. 30 Golden Rules of Deep Learning Performance
Anirudh Koul. 30 Golden Rules of Deep Learning PerformanceAnirudh Koul. 30 Golden Rules of Deep Learning Performance
Anirudh Koul. 30 Golden Rules of Deep Learning Performance
Lviv Startup Club
 
Real Time Streaming Data with Kafka and TensorFlow (Yong Tang, MobileIron) Ka...
Real Time Streaming Data with Kafka and TensorFlow (Yong Tang, MobileIron) Ka...Real Time Streaming Data with Kafka and TensorFlow (Yong Tang, MobileIron) Ka...
Real Time Streaming Data with Kafka and TensorFlow (Yong Tang, MobileIron) Ka...
confluent
 
Meetup tensorframes
Meetup tensorframesMeetup tensorframes
Meetup tensorframes
Paolo Platter
 
A Tour of Tensorflow's APIs
A Tour of Tensorflow's APIsA Tour of Tensorflow's APIs
A Tour of Tensorflow's APIs
Dean Wyatte
 
Introduction to Chainer
Introduction to ChainerIntroduction to Chainer
Introduction to Chainer
Seiya Tokui
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
JAX London
 
Flux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixFlux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul Dix
InfluxData
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
Alex Payne
 
maxbox starter60 machine learning
maxbox starter60 machine learningmaxbox starter60 machine learning
maxbox starter60 machine learning
Max Kleiner
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
Rainer Stropek
 
Hot tutorials
Hot tutorialsHot tutorials
Hot tutorials
Kanagaraj M
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
Sandeep Kr. Singh
 

Similar to slide-keras-tf.pptx (20)

Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame Graphs
 
Reusable, composable, battle-tested Terraform modules
Reusable, composable, battle-tested Terraform modulesReusable, composable, battle-tested Terraform modules
Reusable, composable, battle-tested Terraform modules
 
Gpu programming with java
Gpu programming with javaGpu programming with java
Gpu programming with java
 
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017
 
Machine Learning and Go. Go!
Machine Learning and Go. Go!Machine Learning and Go. Go!
Machine Learning and Go. Go!
 
How Many Ohs? (An Integration Guide to Apex & Triple-o)
How Many Ohs? (An Integration Guide to Apex & Triple-o)How Many Ohs? (An Integration Guide to Apex & Triple-o)
How Many Ohs? (An Integration Guide to Apex & Triple-o)
 
D Trace Support In My Sql Guide To Solving Reallife Performance Problems
D Trace Support In My Sql Guide To Solving Reallife Performance ProblemsD Trace Support In My Sql Guide To Solving Reallife Performance Problems
D Trace Support In My Sql Guide To Solving Reallife Performance Problems
 
Anirudh Koul. 30 Golden Rules of Deep Learning Performance
Anirudh Koul. 30 Golden Rules of Deep Learning PerformanceAnirudh Koul. 30 Golden Rules of Deep Learning Performance
Anirudh Koul. 30 Golden Rules of Deep Learning Performance
 
Real Time Streaming Data with Kafka and TensorFlow (Yong Tang, MobileIron) Ka...
Real Time Streaming Data with Kafka and TensorFlow (Yong Tang, MobileIron) Ka...Real Time Streaming Data with Kafka and TensorFlow (Yong Tang, MobileIron) Ka...
Real Time Streaming Data with Kafka and TensorFlow (Yong Tang, MobileIron) Ka...
 
Meetup tensorframes
Meetup tensorframesMeetup tensorframes
Meetup tensorframes
 
A Tour of Tensorflow's APIs
A Tour of Tensorflow's APIsA Tour of Tensorflow's APIs
A Tour of Tensorflow's APIs
 
Introduction to Chainer
Introduction to ChainerIntroduction to Chainer
Introduction to Chainer
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Flux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixFlux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul Dix
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
maxbox starter60 machine learning
maxbox starter60 machine learningmaxbox starter60 machine learning
maxbox starter60 machine learning
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
 
Hot tutorials
Hot tutorialsHot tutorials
Hot tutorials
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 

More from RithikRaj25

html1.ppt
html1.ppthtml1.ppt
html1.ppt
RithikRaj25
 
Data
DataData
Data
DataData
Introduction To Database.ppt
Introduction To Database.pptIntroduction To Database.ppt
Introduction To Database.ppt
RithikRaj25
 
Data.ppt
Data.pptData.ppt
Data.ppt
RithikRaj25
 
DataTypes.ppt
DataTypes.pptDataTypes.ppt
DataTypes.ppt
RithikRaj25
 
NoSQL.pptx
NoSQL.pptxNoSQL.pptx
NoSQL.pptx
RithikRaj25
 
NoSQL
NoSQLNoSQL
text classification_NB.ppt
text classification_NB.ppttext classification_NB.ppt
text classification_NB.ppt
RithikRaj25
 
html1.ppt
html1.ppthtml1.ppt
html1.ppt
RithikRaj25
 
Intro_OpenCV.ppt
Intro_OpenCV.pptIntro_OpenCV.ppt
Intro_OpenCV.ppt
RithikRaj25
 
lec1b.ppt
lec1b.pptlec1b.ppt
lec1b.ppt
RithikRaj25
 
objectdetect_tutorial.ppt
objectdetect_tutorial.pptobjectdetect_tutorial.ppt
objectdetect_tutorial.ppt
RithikRaj25
 
14_ReinforcementLearning.pptx
14_ReinforcementLearning.pptx14_ReinforcementLearning.pptx
14_ReinforcementLearning.pptx
RithikRaj25
 
datamining-lect11.pptx
datamining-lect11.pptxdatamining-lect11.pptx
datamining-lect11.pptx
RithikRaj25
 
week6a.ppt
week6a.pptweek6a.ppt
week6a.ppt
RithikRaj25
 

More from RithikRaj25 (17)

html1.ppt
html1.ppthtml1.ppt
html1.ppt
 
Data
DataData
Data
 
Data
DataData
Data
 
Introduction To Database.ppt
Introduction To Database.pptIntroduction To Database.ppt
Introduction To Database.ppt
 
Data.ppt
Data.pptData.ppt
Data.ppt
 
DataTypes.ppt
DataTypes.pptDataTypes.ppt
DataTypes.ppt
 
NoSQL.pptx
NoSQL.pptxNoSQL.pptx
NoSQL.pptx
 
NoSQL
NoSQLNoSQL
NoSQL
 
text classification_NB.ppt
text classification_NB.ppttext classification_NB.ppt
text classification_NB.ppt
 
html1.ppt
html1.ppthtml1.ppt
html1.ppt
 
Intro_OpenCV.ppt
Intro_OpenCV.pptIntro_OpenCV.ppt
Intro_OpenCV.ppt
 
lec1b.ppt
lec1b.pptlec1b.ppt
lec1b.ppt
 
PR7.ppt
PR7.pptPR7.ppt
PR7.ppt
 
objectdetect_tutorial.ppt
objectdetect_tutorial.pptobjectdetect_tutorial.ppt
objectdetect_tutorial.ppt
 
14_ReinforcementLearning.pptx
14_ReinforcementLearning.pptx14_ReinforcementLearning.pptx
14_ReinforcementLearning.pptx
 
datamining-lect11.pptx
datamining-lect11.pptxdatamining-lect11.pptx
datamining-lect11.pptx
 
week6a.ppt
week6a.pptweek6a.ppt
week6a.ppt
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 

slide-keras-tf.pptx

  • 1. Introduction to Keras and TensorFlow Qing Wan and Yoonsuck Choe Texas A&M University
  • 2. Outline • Background → NVIDIA CUDA GPU • Installation • Basic skills to write a machine learning model • A specific case: XOR gate
  • 3. Keras • A python package (Python 2.7-3.6) • Sits on top of TensorFlow or Theano (Stopped) • High-level neural network API • Runs seamlessly on CPU and GPU • Open source with user manual (https://keras.io/) • Less coding lines required to build/run a model
  • 4. TensorFlow • Inherit from Theano (data flow graph) • A python(3.5-3.7) package/C++ library • Running on CPU or NVIDIA CUDA GPU • End-2-End platform for machine/deep learning • Multi platform (desktop, web by TF.js, mobile by TF Lite) • Open source with user manual (https://www.tensorflow.org/) • More coding lines required to build/run a model
  • 5. NVIDIA CUDA Toolkit • C/C++ library • A parallel computing platform for NVIDIA GPU • Most deep learning researchers rely on • GPU-accelerated computing/applications • Not open source (https://developer.nvidia.com/cuda-zone) • CPU vs GPU: TensorFlow training CNN model on CIFAR10 images
  • 6. Anaconda3 Installation • Anaconda3 • Download (https://www.anaconda.com/distribution/) • Installation (https://docs.anaconda.com/anaconda/install/) • Restart required
  • 7. TensorFlow/Keras Installation • Start the anaconda navigator • Windows: Start->All program->Anaconda3- >Anaconda Navigator • Linux: type “anaconda-navigator” under the linux terminal • Install TensorFlow and Keras • Environments->choose All • type “tensorflow” • CPU based: tensorflow (choose 1.14) keras (2.2.4) apply • GPU based: • CUDA Compute Capability >= 3.0, better >= 3.7 (check more) • tensorflow-gpu (choose 1.14) and keras- gpu (2.2.4), then apply
  • 8. Installation Confirmed • TensorFlow test code: import tensorflow as tf sess = tf.compat.v1.Session() a = tf.compat.v1.constant(1) b = tf.compat.v1.constant(2) print(sess.run(a+b)) • Expect to have answer 3
  • 9. Installation Confirmed • Keras requires backend setting for Windows users: • https://keras.io/backend/ • Setting in keras.json: “backend”: “tensorflow” • Keras test code: import keras • Expect to see Using TensorFlow backend
  • 10. Keras Models • Two main types of models available • The Sequential model (easy to learn, high-level API) • A linear stack of layers • Need to specify what input shape it should expect (input dimension) • https://keras.io/getting-started/sequential-model-guide/ • The Model class used with the functional API (similar to tensorflow2.0) • https://keras.io/models/about-keras-models/ • https://keras.io/getting-started/functional-api-guide/
  • 11. Keras Sequential Model • Define a sequential model model = Sequential() mode.add(Dense(32, input_dim=784)) model.add(Activation(‘relu’)) model.add(Dense(10)) model.add(Activation(‘softmax’)) • Compilation model.compile(optimizer=‘rmsprop’, loss=‘binary_crossentropy’, metrics=[‘accuray’]) • Training model = model.fit(data, one_hot_labels, epoch=10, batch_size=32) • Predition Y = model.predict(X)
  • 12. Case Study: XOR gate import numpy as np # import necessary packages or APIs from keras from keras.models import Sequential from keras.layers import Dense from keras.optimizers import SGD from keras.initializers import RandomUniform # Prepare data and labels X = np.asarray([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.float32) Y = np.asarray([[0], [1], [1], [0]], dtype=np.float32) # Build a model model = Sequential() model.add(Dense(units=2, activation='tanh', use_bias=True, kernel_initializer=RandomUniform(minval=-1, maxval=1, seed=None), input_dim=2)) model.add(Dense(units=1, activation='sigmoid', use_bias=True, kernel_initializer=RandomUniform(minval=-1, maxval=1, seed=None))) # Build optimizer and do model compilation op = SGD(lr=0.01, momentum=0.0) model.compile(optimizer=op, loss='mse', metrics=['accuracy']) # Start to train model.fit(x=X, y=Y, epochs=20000, batch_size=4, shuffle=True) # Prediction Y = model.predict(X)
  • 13. Case Study: XOR gate • Training log 4/4 [==============================] - 2s 454ms/step - loss: 0.2538 - acc: 0.7500 Epoch 2/20000 ... 4/4 [==============================] - 0s 2ms/step - loss: 0.2531 - acc: 0.5000 Epoch 100/20000 … 4/4 [==============================] - 0s 1ms/step - loss: 0.2511 - acc: 0.5000 Epoch 1000/20000 … 4/4 [==============================] - 0s 2ms/step - loss: 0.2291 - acc: 0.7500 Epoch 10000/20000 … 4/4 [==============================] - 0s 1ms/step - loss: 0.0254 - acc: 1.0000 Epoch 20000/20000 4/4 [==============================] - 0s 1ms/step - loss: 0.0254 - acc: 1.0000 • Prediction Y = [[0.1462788 ] [0.8177988 ] [0.8254448 ] [0.12802514]]
  • 14. TensorFlow Models • What is Tensor? • An object (constant, scalar, vector, matrix, …) • Allow to define ops (+, -, *, /, sum, max, concatenate, …) on • TensorFlow Model • A function with learnable parameters • Maps input to an output by ops • Parameters are all defined by yourself • Model itself • Loss • Optimizer • Whether a parameter is learnable • Data operation More flexible than Keras More complex than Keras
  • 15. Build a TensorFlow Model • Two ways to build a machine learning model • Using the layers API where you build a model using layers e.g. tf.keras.layers.Dense, tf.layers.Conv2D, … • Using the Core API with lower-level ops e.g. tf.math.add, tf.math.abs, tf.concat, …
  • 16. Case Study: XOR gate import numpy as np import tensorflow as tf # Prepare data and labels data = np.asarray([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]], dtype=np.float32) # Build a model x = tf.compat.v1.placeholder(tf.float32, shape=[None, 2], name='x_in') # input label = tf.compat.v1.placeholder(tf.float32, shape=[None, 1], name='label') # label hidden = tf.keras.layers.Dense(units=2, activation=tf.nn.tanh, use_bias=True, kernel_initializer=tf.keras.initializers.RandomUniform(minval=-1, maxval=1))(x) pred = tf.compat.v1.keras.layers.Dense(units=1, activation=tf.nn.sigmoid, use_bias=True, kernel_initializer=tf.keras.initializers.RandomUniform(minval=-1, maxval=1))(hidden) cost = tf.compat.v1.norm(tf.math.subtract(label, pred), ord=2, name='cost') op = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost) training_epochs = 20000 # Set GRAM allocation config = tf.compat.v1.ConfigProto(device_count={'GPU': 1}) config.gpu_options.per_process_gpu_memory_fraction = 0.5 # Start a Session to train and test with tf.compat.v1.Session(config=config) as sess: sess.run(tf.compat.v1.global_variables_initializer()) # Train for epoch in range(training_epochs): loss = 0 for d in data: training_X, training_Y = np.asarray(d[0:2], dtype=np.float32), np.asarray(d[2], dtype=np.float32) training_X, training_Y = np.expand_dims(training_X, axis=0), np.expand_dims([training_Y], axis=0) sess.run(op, feed_dict={x: training_X, label: training_Y}) loss += sess.run(cost, feed_dict={x: training_X, label: training_Y}) if epoch % 100 == 0: print("epoch: %d, loss = %f" % (epoch, loss)) # Test for d in data: Y = sess.run(pred, feed_dict={x: np.expand_dims(np.asarray(d[0:2], dtype=np.float32), axis=0)}) print("d = ", d, "output = ", Y)
  • 17. Case Study: XOR gate • Training log • Prediction epoch: 0, loss = 2.025534 d = [0. 0. 0.] output = [[0.00028096]] epoch: 100, loss = 1.963005 d = [0. 1. 1.] output = [[0.9994849]] … d = [1. 0. 1.] output = [[0.99948573]] epoch: 1000, loss = 0.051374 … epoch: 10000, loss = 0.003195 … epoch: 19800, loss = 0.001572 epoch: 19900, loss = 0.001564 d = [1. 1. 0.] output = [[0.0002458]]
  • 18. Case Study: XOR gate • What happen if we remove kernel_initialization in both Keras model and TensorFlow model? • Try if you are interested • Do we really get the right answer? • Are these results stable? • What’s a potential cause to this?
  • 19. Summary As two popular deep learning packages • Keras • User friendly with high-level APIs • Quick to get started • Coding less lines for machine learning model construction/training/testing • Sometimes training convergence is not stable. • TensorFlow • Flexible for developing new machine learning model • Multi platform • Community support • Not friendly for new learner due to many low level APIs