Bonus 1 - TF2.0 Practical Advanced Cheat Sheet PDF
Bonus 1 - TF2.0 Practical Advanced Cheat Sheet PDF
0
PRACTICAL ADVANCED
Master Tensorflow 2.0, Google’s most powerful Machine Learning
Library, with 6 advanced practical projects covering Generative
Adversarial Networks (GANs), DeepDream, AutoEncoders, LSTM
Recurrent Neural Networks (RNNs), Tensorboard, Transfer Learning
with TF Hub and TF Serving
• Eager execution means that we can now interact with TF 2.0 line by
line in Google Colab or Jupyter notebook without the need to define
a graph and run sessions and all the complexity that came with
TensorFlow 1.0.
>> x = tf.Variable(3)
>> y = tf.Variable(5)
# Tensorflow created a graph but did not execute the graph yet so a
session is needed to run the graph
>> z = tf.add(x,y)
# TensorFlow 2.0 still works with graphs but enable eager execution
by default
>> x = tf.Variable(3)
>> y = tf.Variable(5)
>> z = tf.add(x,y) # immediate answer!
>> print("The sum of x and y is:", z)
# we get the answer immediately!
• The second important feature in TF 2.0 is the use of keras as the high
level API by default
• Keras is extremely easy to work with since Keras syntax is very
pythonic
• Let's build a mini artificial neural network that can classify fashion
images using keras API using couple of lines of code.
>> model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
>> log_dir="logs/fit/" +
datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
>> tensorboard_callback =
tf.keras.callbacks.TensorBoard(log_dir=log_dir,
histogram_freq=1)
>> model.fit(train_images, train_labels, epochs=5, callbacks =
[tensorboard_callback])
>> %tensorboard --logdir logs/fit
>> model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
2.1 CONCEPT
CNNs are a type of deep neural networks that are commonly used for
image classification.
Airplanes
Hidden
Cars
Input
Output Birds
CONVOLUTION POOLING FLATTENING
Cats
Deer
Dogs
KERNELS/ POOLING Frogs
FEATURE FILTERS
Horses
DETECTORS
Ships
Trucks
POOLINGL
LAYER
f(y)
CONVOLUTIONAL (DOWNSAMPLING)
f(y)=y
LAYER
f(y)=0 y
2.2 BUILD A DEEP CONVOLUTIONAL NEURAL NETWORKS
IN TF 2.0:
>> cnn.add(tf.keras.layers.Flatten())
3. TRANSFER LEARNING
3.1 CONCEPT
1. Freeze the trained CNN network weights from the first layers.
2. Retrain the entire CNN network while setting the learning rate to
be very small, this is critical to ensure that you do not
aggressively change the trained weights.
Hidden
Input
Africal elephants
KERNELS/ KERNELS/
IMAGE.NET FEATURE FEATURE Snakes
DETECTORS DETECTORS Lions
LAYER #1 LAYER #2
TRANSFER TRAINED
PARAMETERS NEW DENSE LAYERS
TRAINED ON SPECIFIC TASKS
Hidden
Input
>> MobileNet_feature_extractor_url =
"https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vect
or/2" #@param {type:"string"}
>> MobileNet_feature_extractor_layer =
hub.KerasLayer(MobileNet_feature_extractor_url,
input_shape=(224, 224, 3))
>> model.compile(optimizer=tf.keras.optimizers.Adam(),
loss='categorical_crossentropy', metrics=['accuracy'])
4. AUTOENCODERS
4.1 CONCEPT
• Auto encoders are a type of Artificial Neural Networks that are used
to perform a task of data encoding (representation learning).
• Auto encoders use the same input data as an input and output to
the model.
BOTTLENECK
“CODE LAYER”
(I.E.: ENCODED
CAT IMAGE)
ENCODER DECODER
SAMPLE
μ
>> autoencoder.compile(loss='binary_crossentropy',
optimizer=tf.keras.optimizers.Adam(lr=0.001))
>> autoencoder.summary()
• A RNN contains a temporal loop in which the hidden layer not only
gives an output but it feeds itself as well.
o ot−1 ot ot+1
Unfold
W W W W
x xt−1 xt xt+1
• LSTM networks are type of RNN that are designed to remember long
term dependencies by default.
x + x + x +
A A
tanh tanh tanh
x x x x x x
xt−1 xt xt+1
• LSTM equations:
ht
f t = σ (Wf . h t− 1 , xt + bf )
сt−1 сt
x + i t = σ (Wi. h t− 1 , xt + b i )
ft it ot
tanh
Ct = f t * Ct− 1 + i t * Ct
~
x C x
t Ct = tanh(Wc. h t− 1 , xt + b c
ht−1 σ σ tanh σ ht
o t = σ(Wo . h t− 1 , xt + b o )
h t = o t * tanh( Ct )
xt
5.3 LSTM IN TF 2.0
6. DEEPDREAM
• But, the discriminator will detect the fake money and provide
feedback to the generator on why does he think that the money is
fake.
−
REAL MONEY
UPDATE WEIGHTS
8. TENSORFLOW SERVING
# Let's join the temp model directory with our chosen version
number
>> if os.path.isdir(export_path):
print('\nAlready saved a model, cleaning up\n')
!rm -r {export_path}
>> tf.saved_model.simple_save(
keras.backend.get_session(),
export_path,
inputs={'input_image': model.input},
outputs={t.name:t for t in model.outputs})