SlideShare a Scribd company logo
1 of 46
Download to read offline
Keras with Tensorflow
back-end in R and Python
Longhow Lam
Agenda
• Introduction to neural networks &Deep learning
• Keras some examples
• Train from scratch
• Use pretrained models
• Fine tune
Introduction to neural networks
Neural network NEURAL NETWORK FOR BEGINNERS, JUST LINEAR REGRESSION
f Y = f(X,w) = w1 + w2X2 + w3X3 + w4X41
X2
X3
X4
w4
w3
w1
w2 Neural network compute node
f is the so-called activation function. This could be
the logit function, but other choices are possible.
There are no hidden layers.
There are four weights w’s that have to
be determined
Neural networks ONE HIDDEN LAYER, MATHEMATICAL FORMULATION
Age
Income
Region
Gender
X1
X2
X3
X4
Z1
Z2
Z3
f
X inputs Hidden layer z outputs
α1
β1
neural net prediction f = 𝑔 𝑇𝑌
𝑇𝑌 = 𝛽0𝑌 + 𝛽 𝑌
𝑇
𝑍
𝑍 𝑚 = 𝜎 𝛼0𝑚 + 𝛼 𝑚
𝑇 𝑋
The function σ is defined as:
𝜎(𝑥) =
1
1+𝑒−𝑥
𝝈 is also called the activation function,
In case of regression the function g is the Identify function I
In case of a binary classifier, g is the softmax 𝑔 𝑇𝑌 =
𝑒 𝑇 𝑌
𝑒 𝑇 𝑁+𝑒 𝑇 𝑌
The model weights w = (α , β) have to be estimated from the data
m = 1, ... ,M
number of nodes / neurons
in the hidden layer
Neural networks
Back propagation algorithm
is just gradient descent in numerical optimization terms
Randomly choose small values for all wi’ s. For each data point (observation) i :
• Calculate the neural net prediction fi
• Calculate the error, for example for regression squared error (yi – fi)2
• Calculate the sum of all errors: E = Σ (yi – fi)2
Adjust weights w according to:
A run through all observations is called an epoch
Stop if error E is small enough.
Training the weights
𝑤𝑖
𝑛𝑒𝑤
= 𝑤𝑖 + ∆𝑤𝑖
∆𝑤𝑖 = −𝛼
𝜕𝐸
𝜕𝑤𝑖
Deep learning
Deep learning LOOSELY DEFINED:
NEURAL NET WORK WITH MORE THAN 2 HIDDEN LAYERS
Don’t use deep learning for ‘simple’ business
analytics problems… it is really an overkill!
Keep it simple if you have ‘classical’ churn or
response models: logistics regression, trees,
or forests.
In this example all layers are fully connected (or also called dense layers)
Convolutional networks
For computer vision special structures are used.Usually not all layers fully connected.
We have so-called Convolutional layers and pooling layers.
Convolutional layer A, takes only from a
local window inputs from previous layer
Pooling layer ‘max’, takes max value of a bunch of inputs
But pictures are arrays…. No problem
These blocks of numbers are called “tensors” in linear algebra terms.
Calculations on these tensors can be done very fast in parallel on GPU’s
Training images
VGG19 deep learning networks structure
The model achieves 92.7% top-5 test
accuracy in ImageNet , which is a dataset of
over 14 million images belonging to 1000
classes. 143.mln weights!
Target output:
1000 classes
KERAS on Tensorflow
Keras
• Keras is a high-level neural networks API, written in Python and
capable of running on top of either TensorFlow or Theano.
• It was developed with a focus on enabling fast experimentation.
• Being able to go from idea to result with the least possible delay is
key to doing good research.
• Specifying models in keras is at a higher level than tensorflow, but you
still have lot’s of options
• There is now also an R interface (of course created by Rstudio… )
Simpel set-up “Architecture”
Tensorflow installed on a (linux) machine
Ideally with lots of GPU’s 
pip install keras
You’re good to go in
Python
(Jupyter notebooks)
install_github("rstudio/keras")
You’re good to go in
R / RStudio
Training from scratch: MNIST example
MNIST data:
70.000 handwritten digits with a
label (“0”, “1”,…,”9”)
Each image has a resolution of
28*28 pixels, so a 28 by 28 matrix
First a simple neural network in R
Treat image as a vector. It has length 784 (28by28), the number of
pixels. One hidden layer (fully connected)
Pixel 3
Pixel 2
Pixel 1
Pixel 783
Pixel 784
neuron 1
neuron 256
Label 0
Label 9
First a simple neural network in R
N of neurons time for 50 epochs Test accuracy
5 39 s 0.8988
15 51 s 0.9486
25 44 s 0.9626
50 51 s 0.9741
100 73 s 0.9751
256 125 s 0.9796
512 213 s 0.9825
1024 314 s 0.9830
2 dense (fully connected) layers
2 layer sec Test acc
64 *64 58 0.9705
128*128 88 0.9768
256*256 143 0.9797
512*512 349 0.9819
1024*1024 900 0.9835
Pixel 3
Pixel 2
Pixel 1
Pixel 783
Pixel 784
Label 0
Label 9
A more complex model in Python
Images are treated as matrices / arrays
• Convolutional layers
• Pooling layer
• Dropouts
• Dense last layer
Test loss: 0.028
Test Accuracy: 0.9912
Run time 25 minutes
Now compare with GPU
Some extra steps:
1. Spin up: Microsoft NC6 machine: 1 X Tesla K80 GPU ($1.084/hr)
2. Install CUDA toolkit / install cuDNN
3. pip install tensorflow-gpu
Run same model as in previous slide: Now it takes 2.9 minutes
Example predictions some are wrong….
1 vs 9 7 vs 2 8 vs 8 0 vs 6
Tensorboard
TensorBoard is a visualization tool included with TensorFlow
It enables you to visualize dynamic graphs of your Keras training and
test metrics, as well as activation histograms for the different layers in
your model.
model %>% fit(
x_train, y_train,
batch_size = batch_size,
epochs = epochs,
verbose = 2,
callbacks = callback_tensorboard(
log_dir = "logs/run_1",
write_images = TRUE
),
validation_split = 0.2
)
Now open a shell and start tensorboard, providing the log directory
Pre trained neural networks
Using pre-trained models
Image classifiers have been trained on big GPU machines
for weeks with millions of pictures on very large networks
Not many people do that from scratch. Instead, one can
use pre-trained networks and start from there.
predict image class using pretrained models
RTL NIEUWS Images trough resnet and vgg16
Link to trellisJS app
Images from Videos
Use ffmpeg: open source tool for video analyses Example call for Dutch series Family Kruys trailer
ffmpeg –i
"FAMILIE_KRUYS_TRAILER.mp4"
-s 600x400 –ss 00:00:05.000
-t 1200 -r 2.0
"FamKruys%03d.jpg"
And now tag them with vgg16
See my video analyser shiny app on github
Extract features using pre-trained models
Remove top layers for feature extraction
We have a 7*7*512 ‘feature’ tensor = 25.088 values
Only a few lines of R code
RTL NIEUWS Image similarity
1024 RTL Nieuws Sample pictures. Compute for each image the 25.088 feature values.
Calculate for each image the top 10 closest images, based on cosine similarity.
Little Shiny APP
Examples RTL Nieuws image similarities
Examples RTL Nieuws image similarities
Examples RTL Nieuws image similarities
Same can be done for Videoland ‘boxarts’
See little shiny app
The Brad Pitt similarity index
Take five Brad Pitt pictures
Run them trough the pre-trained
vgg16 and extract feature vectors.
This is a 5 by 25088 matrix
The brad Pit Index
Take other images, run them through the VGG16
Calculate the distances with the five Brad Pitt pictures and average:
0.771195 0.802654 0.714752 0.792587 0.8291976 0.8096944 0.665990 0.9737212
0.6273 0.5908 0.8231 0.7711 0.8839 0.8975 0.6934 0.9659
Focusing on only the face!!
Transfer learning / Fine tune
pre trained models
Transfer learning or
finetune pre-trained models
Train new image classifiers on limited training cases
• Get a pretrained model, say VGG16
• Remove existing top layers
• Add your own (fully) connected layer(s)
• Fix all the parameters except for your layers
• Use your (limited) samples as train cases to train the
weights of your layers.
Python code example
base_model = VGG16(weights='imagenet', include_top=False)
x = base_model.output
x = GlobalAveragePooling2D()(x)
# let's add a fully-connected layer
x = Dense(256, activation='relu')(x)
# and a logistic layer -- 2 classes dogs and cats
predictions = Dense(2, activation='softmax')(x)
# this is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)
# first: train only the top layers (which were randomly initialized)
# i.e. freeze all convolutional layers
for layer in base_model.layers:
layer.trainable = False
# compile the model (should be done *after* setting layers to non-trainable)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics =['accuracy'])
Python code example
1000 cats and dogs example

More Related Content

What's hot

TensorFlow Tutorial Part1
TensorFlow Tutorial Part1TensorFlow Tutorial Part1
TensorFlow Tutorial Part1Sungjoon Choi
 
Deep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlowDeep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlowOswald Campesato
 
Deep Recurrent Neural Networks for Sequence Learning in Spark by Yves Mabiala
Deep Recurrent Neural Networks for Sequence Learning in Spark by Yves MabialaDeep Recurrent Neural Networks for Sequence Learning in Spark by Yves Mabiala
Deep Recurrent Neural Networks for Sequence Learning in Spark by Yves MabialaSpark Summit
 
Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...
Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...
Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...MLconf
 
Language translation with Deep Learning (RNN) with TensorFlow
Language translation with Deep Learning (RNN) with TensorFlowLanguage translation with Deep Learning (RNN) with TensorFlow
Language translation with Deep Learning (RNN) with TensorFlowS N
 
Neural networks and google tensor flow
Neural networks and google tensor flowNeural networks and google tensor flow
Neural networks and google tensor flowShannon McCormick
 
TENSORFLOW: ARCHITECTURE AND USE CASE - NASA SPACE APPS CHALLENGE by Gema Par...
TENSORFLOW: ARCHITECTURE AND USE CASE - NASA SPACE APPS CHALLENGE by Gema Par...TENSORFLOW: ARCHITECTURE AND USE CASE - NASA SPACE APPS CHALLENGE by Gema Par...
TENSORFLOW: ARCHITECTURE AND USE CASE - NASA SPACE APPS CHALLENGE by Gema Par...Big Data Spain
 
An Introduction to TensorFlow architecture
An Introduction to TensorFlow architectureAn Introduction to TensorFlow architecture
An Introduction to TensorFlow architectureMani Goswami
 
Teaching Recurrent Neural Networks using Tensorflow (May 2016)
Teaching Recurrent Neural Networks using Tensorflow (May 2016)Teaching Recurrent Neural Networks using Tensorflow (May 2016)
Teaching Recurrent Neural Networks using Tensorflow (May 2016)Rajiv Shah
 
Introduction to Neural Networks in Tensorflow
Introduction to Neural Networks in TensorflowIntroduction to Neural Networks in Tensorflow
Introduction to Neural Networks in TensorflowNicholas McClure
 
Neural Turing Machines
Neural Turing MachinesNeural Turing Machines
Neural Turing MachinesKato Yuzuru
 
Large Scale Deep Learning with TensorFlow
Large Scale Deep Learning with TensorFlow Large Scale Deep Learning with TensorFlow
Large Scale Deep Learning with TensorFlow Jen Aman
 
Deep Learning with TensorFlow: Understanding Tensors, Computations Graphs, Im...
Deep Learning with TensorFlow: Understanding Tensors, Computations Graphs, Im...Deep Learning with TensorFlow: Understanding Tensors, Computations Graphs, Im...
Deep Learning with TensorFlow: Understanding Tensors, Computations Graphs, Im...Altoros
 
Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016
Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016
Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016MLconf
 
Introduction to Deep Learning, Keras, and TensorFlow
Introduction to Deep Learning, Keras, and TensorFlowIntroduction to Deep Learning, Keras, and TensorFlow
Introduction to Deep Learning, Keras, and TensorFlowSri Ambati
 
Scalable Deep Learning Using Apache MXNet
Scalable Deep Learning Using Apache MXNetScalable Deep Learning Using Apache MXNet
Scalable Deep Learning Using Apache MXNetAmazon Web Services
 
TensorFlow Dev Summit 2017 요약
TensorFlow Dev Summit 2017 요약TensorFlow Dev Summit 2017 요약
TensorFlow Dev Summit 2017 요약Jin Joong Kim
 
Neural Networks with Google TensorFlow
Neural Networks with Google TensorFlowNeural Networks with Google TensorFlow
Neural Networks with Google TensorFlowDarshan Patel
 

What's hot (19)

TensorFlow Tutorial Part1
TensorFlow Tutorial Part1TensorFlow Tutorial Part1
TensorFlow Tutorial Part1
 
Deep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlowDeep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlow
 
Deep Recurrent Neural Networks for Sequence Learning in Spark by Yves Mabiala
Deep Recurrent Neural Networks for Sequence Learning in Spark by Yves MabialaDeep Recurrent Neural Networks for Sequence Learning in Spark by Yves Mabiala
Deep Recurrent Neural Networks for Sequence Learning in Spark by Yves Mabiala
 
Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...
Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...
Avi Pfeffer, Principal Scientist, Charles River Analytics at MLconf SEA - 5/2...
 
Language translation with Deep Learning (RNN) with TensorFlow
Language translation with Deep Learning (RNN) with TensorFlowLanguage translation with Deep Learning (RNN) with TensorFlow
Language translation with Deep Learning (RNN) with TensorFlow
 
Neural networks and google tensor flow
Neural networks and google tensor flowNeural networks and google tensor flow
Neural networks and google tensor flow
 
TENSORFLOW: ARCHITECTURE AND USE CASE - NASA SPACE APPS CHALLENGE by Gema Par...
TENSORFLOW: ARCHITECTURE AND USE CASE - NASA SPACE APPS CHALLENGE by Gema Par...TENSORFLOW: ARCHITECTURE AND USE CASE - NASA SPACE APPS CHALLENGE by Gema Par...
TENSORFLOW: ARCHITECTURE AND USE CASE - NASA SPACE APPS CHALLENGE by Gema Par...
 
An Introduction to TensorFlow architecture
An Introduction to TensorFlow architectureAn Introduction to TensorFlow architecture
An Introduction to TensorFlow architecture
 
Teaching Recurrent Neural Networks using Tensorflow (May 2016)
Teaching Recurrent Neural Networks using Tensorflow (May 2016)Teaching Recurrent Neural Networks using Tensorflow (May 2016)
Teaching Recurrent Neural Networks using Tensorflow (May 2016)
 
Tensor flow
Tensor flowTensor flow
Tensor flow
 
Introduction to Neural Networks in Tensorflow
Introduction to Neural Networks in TensorflowIntroduction to Neural Networks in Tensorflow
Introduction to Neural Networks in Tensorflow
 
Neural Turing Machines
Neural Turing MachinesNeural Turing Machines
Neural Turing Machines
 
Large Scale Deep Learning with TensorFlow
Large Scale Deep Learning with TensorFlow Large Scale Deep Learning with TensorFlow
Large Scale Deep Learning with TensorFlow
 
Deep Learning with TensorFlow: Understanding Tensors, Computations Graphs, Im...
Deep Learning with TensorFlow: Understanding Tensors, Computations Graphs, Im...Deep Learning with TensorFlow: Understanding Tensors, Computations Graphs, Im...
Deep Learning with TensorFlow: Understanding Tensors, Computations Graphs, Im...
 
Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016
Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016
Rajat Monga, Engineering Director, TensorFlow, Google at MLconf 2016
 
Introduction to Deep Learning, Keras, and TensorFlow
Introduction to Deep Learning, Keras, and TensorFlowIntroduction to Deep Learning, Keras, and TensorFlow
Introduction to Deep Learning, Keras, and TensorFlow
 
Scalable Deep Learning Using Apache MXNet
Scalable Deep Learning Using Apache MXNetScalable Deep Learning Using Apache MXNet
Scalable Deep Learning Using Apache MXNet
 
TensorFlow Dev Summit 2017 요약
TensorFlow Dev Summit 2017 요약TensorFlow Dev Summit 2017 요약
TensorFlow Dev Summit 2017 요약
 
Neural Networks with Google TensorFlow
Neural Networks with Google TensorFlowNeural Networks with Google TensorFlow
Neural Networks with Google TensorFlow
 

Similar to Keras on tensorflow in R & Python

Separating Hype from Reality in Deep Learning with Sameer Farooqui
 Separating Hype from Reality in Deep Learning with Sameer Farooqui Separating Hype from Reality in Deep Learning with Sameer Farooqui
Separating Hype from Reality in Deep Learning with Sameer FarooquiDatabricks
 
Learn to Build an App to Find Similar Images using Deep Learning- Piotr Teterwak
Learn to Build an App to Find Similar Images using Deep Learning- Piotr TeterwakLearn to Build an App to Find Similar Images using Deep Learning- Piotr Teterwak
Learn to Build an App to Find Similar Images using Deep Learning- Piotr TeterwakPyData
 
Machine Learning, Deep Learning and Data Analysis Introduction
Machine Learning, Deep Learning and Data Analysis IntroductionMachine Learning, Deep Learning and Data Analysis Introduction
Machine Learning, Deep Learning and Data Analysis IntroductionTe-Yen Liu
 
Diving into Deep Learning (Silicon Valley Code Camp 2017)
Diving into Deep Learning (Silicon Valley Code Camp 2017)Diving into Deep Learning (Silicon Valley Code Camp 2017)
Diving into Deep Learning (Silicon Valley Code Camp 2017)Oswald Campesato
 
Introduction to Deep Learning and Tensorflow
Introduction to Deep Learning and TensorflowIntroduction to Deep Learning and Tensorflow
Introduction to Deep Learning and TensorflowOswald Campesato
 
Deep Dive on Deep Learning (June 2018)
Deep Dive on Deep Learning (June 2018)Deep Dive on Deep Learning (June 2018)
Deep Dive on Deep Learning (June 2018)Julien SIMON
 
A Platform for Accelerating Machine Learning Applications
 A Platform for Accelerating Machine Learning Applications A Platform for Accelerating Machine Learning Applications
A Platform for Accelerating Machine Learning ApplicationsNVIDIA Taiwan
 
Neural network image recognition
Neural network image recognitionNeural network image recognition
Neural network image recognitionOleksii Sekundant
 
backpropagation in neural networks
backpropagation in neural networksbackpropagation in neural networks
backpropagation in neural networksAkash Goel
 
BMVA summer school MATLAB programming tutorial
BMVA summer school MATLAB programming tutorialBMVA summer school MATLAB programming tutorial
BMVA summer school MATLAB programming tutorialpotaters
 
Final training course
Final training courseFinal training course
Final training courseNoor Dhiya
 
Introduction to Applied Machine Learning
Introduction to Applied Machine LearningIntroduction to Applied Machine Learning
Introduction to Applied Machine LearningSheilaJimenezMorejon
 
Deep Learning: R with Keras and TensorFlow
Deep Learning: R with Keras and TensorFlowDeep Learning: R with Keras and TensorFlow
Deep Learning: R with Keras and TensorFlowOswald Campesato
 
Transfer Learning (20230516)
Transfer Learning (20230516)Transfer Learning (20230516)
Transfer Learning (20230516)FEG
 
NVIDIA深度學習教育機構 (DLI): Object detection with jetson
NVIDIA深度學習教育機構 (DLI): Object detection with jetsonNVIDIA深度學習教育機構 (DLI): Object detection with jetson
NVIDIA深度學習教育機構 (DLI): Object detection with jetsonNVIDIA Taiwan
 
Overview of Chainer and Its Features
Overview of Chainer and Its FeaturesOverview of Chainer and Its Features
Overview of Chainer and Its FeaturesSeiya Tokui
 
Handwritten Digit Recognition using Convolutional Neural Networks
Handwritten Digit Recognition using Convolutional Neural  NetworksHandwritten Digit Recognition using Convolutional Neural  Networks
Handwritten Digit Recognition using Convolutional Neural NetworksIRJET Journal
 
(CMP305) Deep Learning on AWS Made EasyCmp305
(CMP305) Deep Learning on AWS Made EasyCmp305(CMP305) Deep Learning on AWS Made EasyCmp305
(CMP305) Deep Learning on AWS Made EasyCmp305Amazon Web Services
 

Similar to Keras on tensorflow in R & Python (20)

Separating Hype from Reality in Deep Learning with Sameer Farooqui
 Separating Hype from Reality in Deep Learning with Sameer Farooqui Separating Hype from Reality in Deep Learning with Sameer Farooqui
Separating Hype from Reality in Deep Learning with Sameer Farooqui
 
Learn to Build an App to Find Similar Images using Deep Learning- Piotr Teterwak
Learn to Build an App to Find Similar Images using Deep Learning- Piotr TeterwakLearn to Build an App to Find Similar Images using Deep Learning- Piotr Teterwak
Learn to Build an App to Find Similar Images using Deep Learning- Piotr Teterwak
 
Android and Deep Learning
Android and Deep LearningAndroid and Deep Learning
Android and Deep Learning
 
Machine Learning, Deep Learning and Data Analysis Introduction
Machine Learning, Deep Learning and Data Analysis IntroductionMachine Learning, Deep Learning and Data Analysis Introduction
Machine Learning, Deep Learning and Data Analysis Introduction
 
Diving into Deep Learning (Silicon Valley Code Camp 2017)
Diving into Deep Learning (Silicon Valley Code Camp 2017)Diving into Deep Learning (Silicon Valley Code Camp 2017)
Diving into Deep Learning (Silicon Valley Code Camp 2017)
 
Introduction to Deep Learning and Tensorflow
Introduction to Deep Learning and TensorflowIntroduction to Deep Learning and Tensorflow
Introduction to Deep Learning and Tensorflow
 
MXNet Workshop
MXNet WorkshopMXNet Workshop
MXNet Workshop
 
Deep Dive on Deep Learning (June 2018)
Deep Dive on Deep Learning (June 2018)Deep Dive on Deep Learning (June 2018)
Deep Dive on Deep Learning (June 2018)
 
A Platform for Accelerating Machine Learning Applications
 A Platform for Accelerating Machine Learning Applications A Platform for Accelerating Machine Learning Applications
A Platform for Accelerating Machine Learning Applications
 
Neural network image recognition
Neural network image recognitionNeural network image recognition
Neural network image recognition
 
backpropagation in neural networks
backpropagation in neural networksbackpropagation in neural networks
backpropagation in neural networks
 
BMVA summer school MATLAB programming tutorial
BMVA summer school MATLAB programming tutorialBMVA summer school MATLAB programming tutorial
BMVA summer school MATLAB programming tutorial
 
Final training course
Final training courseFinal training course
Final training course
 
Introduction to Applied Machine Learning
Introduction to Applied Machine LearningIntroduction to Applied Machine Learning
Introduction to Applied Machine Learning
 
Deep Learning: R with Keras and TensorFlow
Deep Learning: R with Keras and TensorFlowDeep Learning: R with Keras and TensorFlow
Deep Learning: R with Keras and TensorFlow
 
Transfer Learning (20230516)
Transfer Learning (20230516)Transfer Learning (20230516)
Transfer Learning (20230516)
 
NVIDIA深度學習教育機構 (DLI): Object detection with jetson
NVIDIA深度學習教育機構 (DLI): Object detection with jetsonNVIDIA深度學習教育機構 (DLI): Object detection with jetson
NVIDIA深度學習教育機構 (DLI): Object detection with jetson
 
Overview of Chainer and Its Features
Overview of Chainer and Its FeaturesOverview of Chainer and Its Features
Overview of Chainer and Its Features
 
Handwritten Digit Recognition using Convolutional Neural Networks
Handwritten Digit Recognition using Convolutional Neural  NetworksHandwritten Digit Recognition using Convolutional Neural  Networks
Handwritten Digit Recognition using Convolutional Neural Networks
 
(CMP305) Deep Learning on AWS Made EasyCmp305
(CMP305) Deep Learning on AWS Made EasyCmp305(CMP305) Deep Learning on AWS Made EasyCmp305
(CMP305) Deep Learning on AWS Made EasyCmp305
 

More from Longhow Lam

Xomia_20220602.pptx
Xomia_20220602.pptxXomia_20220602.pptx
Xomia_20220602.pptxLonghow Lam
 
A Unifying theory for blockchain and AI
A Unifying theory for blockchain and AIA Unifying theory for blockchain and AI
A Unifying theory for blockchain and AILonghow Lam
 
Data science inspiratie_sessie
Data science inspiratie_sessieData science inspiratie_sessie
Data science inspiratie_sessieLonghow Lam
 
Jaap Huisprijzen, GTST, The Bold, IKEA en Iens
Jaap Huisprijzen, GTST, The Bold, IKEA en IensJaap Huisprijzen, GTST, The Bold, IKEA en Iens
Jaap Huisprijzen, GTST, The Bold, IKEA en IensLonghow Lam
 
text2vec SatRDay Amsterdam
text2vec SatRDay Amsterdamtext2vec SatRDay Amsterdam
text2vec SatRDay AmsterdamLonghow Lam
 
Dataiku meetup 12 july 2018 Amsterdam
Dataiku meetup 12 july 2018 AmsterdamDataiku meetup 12 july 2018 Amsterdam
Dataiku meetup 12 july 2018 AmsterdamLonghow Lam
 
Data science in action
Data science in actionData science in action
Data science in actionLonghow Lam
 
MasterSearch_Meetup_AdvancedAnalytics
MasterSearch_Meetup_AdvancedAnalyticsMasterSearch_Meetup_AdvancedAnalytics
MasterSearch_Meetup_AdvancedAnalyticsLonghow Lam
 
Latent transwarp neural networks
Latent transwarp neural networksLatent transwarp neural networks
Latent transwarp neural networksLonghow Lam
 
MathPaperPublished
MathPaperPublishedMathPaperPublished
MathPaperPublishedLonghow Lam
 
Heliview 29sep2015 slideshare
Heliview 29sep2015 slideshareHeliview 29sep2015 slideshare
Heliview 29sep2015 slideshareLonghow Lam
 
Parameter estimation in a non stationary markov model
Parameter estimation in a non stationary markov modelParameter estimation in a non stationary markov model
Parameter estimation in a non stationary markov modelLonghow Lam
 
The analysis of doubly censored survival data
The analysis of doubly censored survival dataThe analysis of doubly censored survival data
The analysis of doubly censored survival dataLonghow Lam
 
Machine learning overview (with SAS software)
Machine learning overview (with SAS software)Machine learning overview (with SAS software)
Machine learning overview (with SAS software)Longhow Lam
 

More from Longhow Lam (14)

Xomia_20220602.pptx
Xomia_20220602.pptxXomia_20220602.pptx
Xomia_20220602.pptx
 
A Unifying theory for blockchain and AI
A Unifying theory for blockchain and AIA Unifying theory for blockchain and AI
A Unifying theory for blockchain and AI
 
Data science inspiratie_sessie
Data science inspiratie_sessieData science inspiratie_sessie
Data science inspiratie_sessie
 
Jaap Huisprijzen, GTST, The Bold, IKEA en Iens
Jaap Huisprijzen, GTST, The Bold, IKEA en IensJaap Huisprijzen, GTST, The Bold, IKEA en Iens
Jaap Huisprijzen, GTST, The Bold, IKEA en Iens
 
text2vec SatRDay Amsterdam
text2vec SatRDay Amsterdamtext2vec SatRDay Amsterdam
text2vec SatRDay Amsterdam
 
Dataiku meetup 12 july 2018 Amsterdam
Dataiku meetup 12 july 2018 AmsterdamDataiku meetup 12 july 2018 Amsterdam
Dataiku meetup 12 july 2018 Amsterdam
 
Data science in action
Data science in actionData science in action
Data science in action
 
MasterSearch_Meetup_AdvancedAnalytics
MasterSearch_Meetup_AdvancedAnalyticsMasterSearch_Meetup_AdvancedAnalytics
MasterSearch_Meetup_AdvancedAnalytics
 
Latent transwarp neural networks
Latent transwarp neural networksLatent transwarp neural networks
Latent transwarp neural networks
 
MathPaperPublished
MathPaperPublishedMathPaperPublished
MathPaperPublished
 
Heliview 29sep2015 slideshare
Heliview 29sep2015 slideshareHeliview 29sep2015 slideshare
Heliview 29sep2015 slideshare
 
Parameter estimation in a non stationary markov model
Parameter estimation in a non stationary markov modelParameter estimation in a non stationary markov model
Parameter estimation in a non stationary markov model
 
The analysis of doubly censored survival data
The analysis of doubly censored survival dataThe analysis of doubly censored survival data
The analysis of doubly censored survival data
 
Machine learning overview (with SAS software)
Machine learning overview (with SAS software)Machine learning overview (with SAS software)
Machine learning overview (with SAS software)
 

Recently uploaded

Decoding Patterns: Customer Churn Prediction Data Analysis Project
Decoding Patterns: Customer Churn Prediction Data Analysis ProjectDecoding Patterns: Customer Churn Prediction Data Analysis Project
Decoding Patterns: Customer Churn Prediction Data Analysis ProjectBoston Institute of Analytics
 
Statistics For Management by Richard I. Levin 8ed.pdf
Statistics For Management by Richard I. Levin 8ed.pdfStatistics For Management by Richard I. Levin 8ed.pdf
Statistics For Management by Richard I. Levin 8ed.pdfnikeshsingh56
 
knowledge representation in artificial intelligence
knowledge representation in artificial intelligenceknowledge representation in artificial intelligence
knowledge representation in artificial intelligencePriyadharshiniG41
 
Digital Indonesia Report 2024 by We Are Social .pdf
Digital Indonesia Report 2024 by We Are Social .pdfDigital Indonesia Report 2024 by We Are Social .pdf
Digital Indonesia Report 2024 by We Are Social .pdfNicoChristianSunaryo
 
Digital Marketing Plan, how digital marketing works
Digital Marketing Plan, how digital marketing worksDigital Marketing Plan, how digital marketing works
Digital Marketing Plan, how digital marketing worksdeepakthakur548787
 
World Economic Forum Metaverse Ecosystem By Utpal Chakraborty.pdf
World Economic Forum Metaverse Ecosystem By Utpal Chakraborty.pdfWorld Economic Forum Metaverse Ecosystem By Utpal Chakraborty.pdf
World Economic Forum Metaverse Ecosystem By Utpal Chakraborty.pdfsimulationsindia
 
Data Factory in Microsoft Fabric (MsBIP #82)
Data Factory in Microsoft Fabric (MsBIP #82)Data Factory in Microsoft Fabric (MsBIP #82)
Data Factory in Microsoft Fabric (MsBIP #82)Cathrine Wilhelmsen
 
What To Do For World Nature Conservation Day by Slidesgo.pptx
What To Do For World Nature Conservation Day by Slidesgo.pptxWhat To Do For World Nature Conservation Day by Slidesgo.pptx
What To Do For World Nature Conservation Day by Slidesgo.pptxSimranPal17
 
Principles and Practices of Data Visualization
Principles and Practices of Data VisualizationPrinciples and Practices of Data Visualization
Principles and Practices of Data VisualizationKianJazayeri1
 
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...Jack Cole
 
DATA ANALYSIS using various data sets like shoping data set etc
DATA ANALYSIS using various data sets like shoping data set etcDATA ANALYSIS using various data sets like shoping data set etc
DATA ANALYSIS using various data sets like shoping data set etclalithasri22
 
modul pembelajaran robotic Workshop _ by Slidesgo.pptx
modul pembelajaran robotic Workshop _ by Slidesgo.pptxmodul pembelajaran robotic Workshop _ by Slidesgo.pptx
modul pembelajaran robotic Workshop _ by Slidesgo.pptxaleedritatuxx
 
Rithik Kumar Singh codealpha pythohn.pdf
Rithik Kumar Singh codealpha pythohn.pdfRithik Kumar Singh codealpha pythohn.pdf
Rithik Kumar Singh codealpha pythohn.pdfrahulyadav957181
 
Non Text Magic Studio Magic Design for Presentations L&P.pdf
Non Text Magic Studio Magic Design for Presentations L&P.pdfNon Text Magic Studio Magic Design for Presentations L&P.pdf
Non Text Magic Studio Magic Design for Presentations L&P.pdfPratikPatil591646
 
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...Dr Arash Najmaei ( Phd., MBA, BSc)
 
Bank Loan Approval Analysis: A Comprehensive Data Analysis Project
Bank Loan Approval Analysis: A Comprehensive Data Analysis ProjectBank Loan Approval Analysis: A Comprehensive Data Analysis Project
Bank Loan Approval Analysis: A Comprehensive Data Analysis ProjectBoston Institute of Analytics
 
Role of Consumer Insights in business transformation
Role of Consumer Insights in business transformationRole of Consumer Insights in business transformation
Role of Consumer Insights in business transformationAnnie Melnic
 
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdfEnglish-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdfblazblazml
 

Recently uploaded (20)

Decoding Patterns: Customer Churn Prediction Data Analysis Project
Decoding Patterns: Customer Churn Prediction Data Analysis ProjectDecoding Patterns: Customer Churn Prediction Data Analysis Project
Decoding Patterns: Customer Churn Prediction Data Analysis Project
 
Statistics For Management by Richard I. Levin 8ed.pdf
Statistics For Management by Richard I. Levin 8ed.pdfStatistics For Management by Richard I. Levin 8ed.pdf
Statistics For Management by Richard I. Levin 8ed.pdf
 
knowledge representation in artificial intelligence
knowledge representation in artificial intelligenceknowledge representation in artificial intelligence
knowledge representation in artificial intelligence
 
Data Analysis Project: Stroke Prediction
Data Analysis Project: Stroke PredictionData Analysis Project: Stroke Prediction
Data Analysis Project: Stroke Prediction
 
Digital Indonesia Report 2024 by We Are Social .pdf
Digital Indonesia Report 2024 by We Are Social .pdfDigital Indonesia Report 2024 by We Are Social .pdf
Digital Indonesia Report 2024 by We Are Social .pdf
 
Digital Marketing Plan, how digital marketing works
Digital Marketing Plan, how digital marketing worksDigital Marketing Plan, how digital marketing works
Digital Marketing Plan, how digital marketing works
 
World Economic Forum Metaverse Ecosystem By Utpal Chakraborty.pdf
World Economic Forum Metaverse Ecosystem By Utpal Chakraborty.pdfWorld Economic Forum Metaverse Ecosystem By Utpal Chakraborty.pdf
World Economic Forum Metaverse Ecosystem By Utpal Chakraborty.pdf
 
Data Factory in Microsoft Fabric (MsBIP #82)
Data Factory in Microsoft Fabric (MsBIP #82)Data Factory in Microsoft Fabric (MsBIP #82)
Data Factory in Microsoft Fabric (MsBIP #82)
 
What To Do For World Nature Conservation Day by Slidesgo.pptx
What To Do For World Nature Conservation Day by Slidesgo.pptxWhat To Do For World Nature Conservation Day by Slidesgo.pptx
What To Do For World Nature Conservation Day by Slidesgo.pptx
 
Principles and Practices of Data Visualization
Principles and Practices of Data VisualizationPrinciples and Practices of Data Visualization
Principles and Practices of Data Visualization
 
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
 
DATA ANALYSIS using various data sets like shoping data set etc
DATA ANALYSIS using various data sets like shoping data set etcDATA ANALYSIS using various data sets like shoping data set etc
DATA ANALYSIS using various data sets like shoping data set etc
 
modul pembelajaran robotic Workshop _ by Slidesgo.pptx
modul pembelajaran robotic Workshop _ by Slidesgo.pptxmodul pembelajaran robotic Workshop _ by Slidesgo.pptx
modul pembelajaran robotic Workshop _ by Slidesgo.pptx
 
2023 Survey Shows Dip in High School E-Cigarette Use
2023 Survey Shows Dip in High School E-Cigarette Use2023 Survey Shows Dip in High School E-Cigarette Use
2023 Survey Shows Dip in High School E-Cigarette Use
 
Rithik Kumar Singh codealpha pythohn.pdf
Rithik Kumar Singh codealpha pythohn.pdfRithik Kumar Singh codealpha pythohn.pdf
Rithik Kumar Singh codealpha pythohn.pdf
 
Non Text Magic Studio Magic Design for Presentations L&P.pdf
Non Text Magic Studio Magic Design for Presentations L&P.pdfNon Text Magic Studio Magic Design for Presentations L&P.pdf
Non Text Magic Studio Magic Design for Presentations L&P.pdf
 
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
 
Bank Loan Approval Analysis: A Comprehensive Data Analysis Project
Bank Loan Approval Analysis: A Comprehensive Data Analysis ProjectBank Loan Approval Analysis: A Comprehensive Data Analysis Project
Bank Loan Approval Analysis: A Comprehensive Data Analysis Project
 
Role of Consumer Insights in business transformation
Role of Consumer Insights in business transformationRole of Consumer Insights in business transformation
Role of Consumer Insights in business transformation
 
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdfEnglish-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
 

Keras on tensorflow in R & Python

  • 1. Keras with Tensorflow back-end in R and Python Longhow Lam
  • 2. Agenda • Introduction to neural networks &Deep learning • Keras some examples • Train from scratch • Use pretrained models • Fine tune
  • 4. Neural network NEURAL NETWORK FOR BEGINNERS, JUST LINEAR REGRESSION f Y = f(X,w) = w1 + w2X2 + w3X3 + w4X41 X2 X3 X4 w4 w3 w1 w2 Neural network compute node f is the so-called activation function. This could be the logit function, but other choices are possible. There are no hidden layers. There are four weights w’s that have to be determined
  • 5. Neural networks ONE HIDDEN LAYER, MATHEMATICAL FORMULATION Age Income Region Gender X1 X2 X3 X4 Z1 Z2 Z3 f X inputs Hidden layer z outputs α1 β1 neural net prediction f = 𝑔 𝑇𝑌 𝑇𝑌 = 𝛽0𝑌 + 𝛽 𝑌 𝑇 𝑍 𝑍 𝑚 = 𝜎 𝛼0𝑚 + 𝛼 𝑚 𝑇 𝑋 The function σ is defined as: 𝜎(𝑥) = 1 1+𝑒−𝑥 𝝈 is also called the activation function, In case of regression the function g is the Identify function I In case of a binary classifier, g is the softmax 𝑔 𝑇𝑌 = 𝑒 𝑇 𝑌 𝑒 𝑇 𝑁+𝑒 𝑇 𝑌 The model weights w = (α , β) have to be estimated from the data m = 1, ... ,M number of nodes / neurons in the hidden layer
  • 6. Neural networks Back propagation algorithm is just gradient descent in numerical optimization terms Randomly choose small values for all wi’ s. For each data point (observation) i : • Calculate the neural net prediction fi • Calculate the error, for example for regression squared error (yi – fi)2 • Calculate the sum of all errors: E = Σ (yi – fi)2 Adjust weights w according to: A run through all observations is called an epoch Stop if error E is small enough. Training the weights 𝑤𝑖 𝑛𝑒𝑤 = 𝑤𝑖 + ∆𝑤𝑖 ∆𝑤𝑖 = −𝛼 𝜕𝐸 𝜕𝑤𝑖
  • 8. Deep learning LOOSELY DEFINED: NEURAL NET WORK WITH MORE THAN 2 HIDDEN LAYERS Don’t use deep learning for ‘simple’ business analytics problems… it is really an overkill! Keep it simple if you have ‘classical’ churn or response models: logistics regression, trees, or forests. In this example all layers are fully connected (or also called dense layers)
  • 9. Convolutional networks For computer vision special structures are used.Usually not all layers fully connected. We have so-called Convolutional layers and pooling layers. Convolutional layer A, takes only from a local window inputs from previous layer Pooling layer ‘max’, takes max value of a bunch of inputs
  • 10. But pictures are arrays…. No problem These blocks of numbers are called “tensors” in linear algebra terms. Calculations on these tensors can be done very fast in parallel on GPU’s
  • 11. Training images VGG19 deep learning networks structure The model achieves 92.7% top-5 test accuracy in ImageNet , which is a dataset of over 14 million images belonging to 1000 classes. 143.mln weights! Target output: 1000 classes
  • 13. Keras • Keras is a high-level neural networks API, written in Python and capable of running on top of either TensorFlow or Theano. • It was developed with a focus on enabling fast experimentation. • Being able to go from idea to result with the least possible delay is key to doing good research. • Specifying models in keras is at a higher level than tensorflow, but you still have lot’s of options • There is now also an R interface (of course created by Rstudio… )
  • 14. Simpel set-up “Architecture” Tensorflow installed on a (linux) machine Ideally with lots of GPU’s  pip install keras You’re good to go in Python (Jupyter notebooks) install_github("rstudio/keras") You’re good to go in R / RStudio
  • 15. Training from scratch: MNIST example MNIST data: 70.000 handwritten digits with a label (“0”, “1”,…,”9”) Each image has a resolution of 28*28 pixels, so a 28 by 28 matrix
  • 16. First a simple neural network in R Treat image as a vector. It has length 784 (28by28), the number of pixels. One hidden layer (fully connected) Pixel 3 Pixel 2 Pixel 1 Pixel 783 Pixel 784 neuron 1 neuron 256 Label 0 Label 9
  • 17. First a simple neural network in R N of neurons time for 50 epochs Test accuracy 5 39 s 0.8988 15 51 s 0.9486 25 44 s 0.9626 50 51 s 0.9741 100 73 s 0.9751 256 125 s 0.9796 512 213 s 0.9825 1024 314 s 0.9830
  • 18. 2 dense (fully connected) layers 2 layer sec Test acc 64 *64 58 0.9705 128*128 88 0.9768 256*256 143 0.9797 512*512 349 0.9819 1024*1024 900 0.9835 Pixel 3 Pixel 2 Pixel 1 Pixel 783 Pixel 784 Label 0 Label 9
  • 19. A more complex model in Python Images are treated as matrices / arrays • Convolutional layers • Pooling layer • Dropouts • Dense last layer
  • 20. Test loss: 0.028 Test Accuracy: 0.9912 Run time 25 minutes
  • 21. Now compare with GPU Some extra steps: 1. Spin up: Microsoft NC6 machine: 1 X Tesla K80 GPU ($1.084/hr) 2. Install CUDA toolkit / install cuDNN 3. pip install tensorflow-gpu Run same model as in previous slide: Now it takes 2.9 minutes
  • 22. Example predictions some are wrong…. 1 vs 9 7 vs 2 8 vs 8 0 vs 6
  • 23. Tensorboard TensorBoard is a visualization tool included with TensorFlow It enables you to visualize dynamic graphs of your Keras training and test metrics, as well as activation histograms for the different layers in your model. model %>% fit( x_train, y_train, batch_size = batch_size, epochs = epochs, verbose = 2, callbacks = callback_tensorboard( log_dir = "logs/run_1", write_images = TRUE ), validation_split = 0.2 )
  • 24. Now open a shell and start tensorboard, providing the log directory
  • 25. Pre trained neural networks
  • 26. Using pre-trained models Image classifiers have been trained on big GPU machines for weeks with millions of pictures on very large networks Not many people do that from scratch. Instead, one can use pre-trained networks and start from there.
  • 27. predict image class using pretrained models
  • 28. RTL NIEUWS Images trough resnet and vgg16 Link to trellisJS app
  • 29. Images from Videos Use ffmpeg: open source tool for video analyses Example call for Dutch series Family Kruys trailer ffmpeg –i "FAMILIE_KRUYS_TRAILER.mp4" -s 600x400 –ss 00:00:05.000 -t 1200 -r 2.0 "FamKruys%03d.jpg"
  • 30. And now tag them with vgg16
  • 31. See my video analyser shiny app on github
  • 32. Extract features using pre-trained models Remove top layers for feature extraction We have a 7*7*512 ‘feature’ tensor = 25.088 values
  • 33. Only a few lines of R code
  • 34. RTL NIEUWS Image similarity 1024 RTL Nieuws Sample pictures. Compute for each image the 25.088 feature values. Calculate for each image the top 10 closest images, based on cosine similarity. Little Shiny APP
  • 35. Examples RTL Nieuws image similarities
  • 36. Examples RTL Nieuws image similarities
  • 37. Examples RTL Nieuws image similarities
  • 38. Same can be done for Videoland ‘boxarts’ See little shiny app
  • 39. The Brad Pitt similarity index
  • 40. Take five Brad Pitt pictures Run them trough the pre-trained vgg16 and extract feature vectors. This is a 5 by 25088 matrix The brad Pit Index Take other images, run them through the VGG16 Calculate the distances with the five Brad Pitt pictures and average: 0.771195 0.802654 0.714752 0.792587 0.8291976 0.8096944 0.665990 0.9737212
  • 41. 0.6273 0.5908 0.8231 0.7711 0.8839 0.8975 0.6934 0.9659 Focusing on only the face!!
  • 42. Transfer learning / Fine tune pre trained models
  • 43. Transfer learning or finetune pre-trained models Train new image classifiers on limited training cases • Get a pretrained model, say VGG16 • Remove existing top layers • Add your own (fully) connected layer(s) • Fix all the parameters except for your layers • Use your (limited) samples as train cases to train the weights of your layers.
  • 44. Python code example base_model = VGG16(weights='imagenet', include_top=False) x = base_model.output x = GlobalAveragePooling2D()(x) # let's add a fully-connected layer x = Dense(256, activation='relu')(x) # and a logistic layer -- 2 classes dogs and cats predictions = Dense(2, activation='softmax')(x) # this is the model we will train model = Model(inputs=base_model.input, outputs=predictions) # first: train only the top layers (which were randomly initialized) # i.e. freeze all convolutional layers for layer in base_model.layers: layer.trainable = False # compile the model (should be done *after* setting layers to non-trainable) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics =['accuracy'])
  • 46. 1000 cats and dogs example

Editor's Notes

  1. binaire clasificatie  2 output nodes: Y en N 4 input variabelen  4 input nodes: X = (X1,..,X4) 1 hidden layer met 3 hidden nodes: Z = (Z1, Z2, Z3)