You are on page 1of 2

Tensorflow 2.

0 Cheat Sheet
Some pre-requisites TF Core learning algorithms Working with Keras models
Artificial Intelligence - Can computers think? It is a Some fundemental machine learning algorithms:- Once the model is created, we can config the model with losses
process of automating intelligent tasks done by humans. and metrics with model.compile(), train the model with
Linear Regression
Machine Learning - Where A.I. is pre-defined set of rules, model.fit(), check the loss value and metrics values in test
machine Learning takes data and answers, and figures out the Linear regression is one of the most basic forms of machine mode with model.evaluate() or use the model to do prediction
rules for us using an algorithm. learning and is used to predict numeric values. with model.predict().
Neural Networks - (Or Deep Learning) Now, here we have # Creating a model Define a model
more than two layers i.e. input and output layer as compared lr = tf . estimator . L i ne a rC l as s i f i er (
to machine learning. There are multiple layers of information. f ea tu re _co lu m ns ) model = keras . Model ( inputs , outputs , ...)
# Train the model
Tensorflow lr . train ( tr ain_func tion )
model . summary ()
# Groups a linear stack of layers into a model
It is a open-source machine learning platform developed and # Get model metrics on testing data keras . Sequential ( layers , ...)
maintained by google used for scientific computing, neural lr . evaluate ( test_function ) # For multi - GPU data parallelism
networks, image classification, clustering, regression, # Get prediction from data set keras . utils . mu lt i _g pu_m o de l ( model , gpus , ...)
reinforcement learning, natural language processing etc. It has lr . predict ( test_function )
two main components - graph and session. It builds graph for Compile a model
computations, basically a way of defining operations. Session Deep Neural Network for classification
allows parts of the graph to be executed. For classification tasks, DNN seems to be the best choice when # Configures the model for training
we are not able to find a linear correspondence in data. # Stage for h yp ye rp arame t er tuning
Installation and Importing model . compile ( optimizer , loss , metrics ,
To install TensorFlow on your local machine you can use pip. # Creating a model
loss_weights , weighted_metrics , ...)
c = tf . estimator . DNNClassifier ( feature_columns ,
pip install tensorflow
hidden_units , n_classes )
You can also install the GPU version of TensorFlow. For that Fit a model
# hidden_units - [# neurons in 1 st hidden layer ,
you need to install some other software.
# neurons in 2 nd layer , ..]
pip install tensorflow-gpu # Train the model # Train model for a fixed number of iterations
For google collab users to use 2.x version, c . train ( train_function , steps ) model . fit (x , y , batch_size , epochs , verbose ,
callbacks , ...)
# Add this line
Hidden Markov Model # Fits the model on data yielded batch - by - batch
% te n so r f l ow _ ve r s i o n 2. x
by a generator
Importing tensorflow, Hidden Markov Model works with probabilities to predict model . fit_generator ()
future events or states. Understanding HMM. # Gradient update on one particular batch of
import tensorflow as tf training data
# Necessory imports as it is statistical model
# Make sure the version is 2. x model . train _on_batch ()
import t e n s o r f l o w _ p r o b a b i l i t y as tfp
print ( tf . version )
tfd = tfp . distributions
# Creating a model Evaluate a model
Tensors model = tfd . Hi d d e n M a r k o v M o d e l (
Tensors are generalization of vectors and matrices to higher initial_distribution , transition_distribution , # Returns the loss value & metrics values for
dimension which represents a partially defined computation observation_distribution , num_steps ) the model in test mode
model . evaluate (x , y , batch_size , steps , ...)
that produces a value. Each tensor has data-type and IMP - In the new version of tensorflow we need to use # Evaluates the model on a data generator
dimension. Creating a tensor, tf.compat.v1.Session() rather than just tf.Session() model . e v a l u a t e _ g e n e r a t o r ( generator , ...)
tf . Variable (" sample string " , tf . string )
Keras
tf . Variable (32 , tf . int16 ) Make predictions
Keras is a high-level neural networks API, written in Python
Degree of Tensors - number of dimensions involved in the and capable of running on top of TensorFlow, CNTK, or
# Generate predictions from a model
tensor Theano. One of the best deep learning module which allows model . predict ()
easy and fast prototyping through user friendliness, # Returns predictions for a single batch of
tf . rank ( tf . Variable ([[1 , 2] , [3 , 4]] , tf . int16 ) )
modularity, and extensibility. Supports both convolutional samples
# Rank - 2
networks and recurrent networks, as well as combinations of model . p r e di c t _o n_ b a tc h ( x )
Changing shape of tensors the two. Runs seamlessly on CPU and GPU. # Generates predictions for the input samples
Basic workflow of a keras model:- from a data generator
t1 = tf . ones ( original_shape ) Define model - Compile - Fit - Evaluate - Predict model . p r e d i ct _ ge n er a t o r ( generator , steps , ...)
t2 = tf . reshape ( t1 , new_shape )
# The logic for one inference step
# Importing keras
Types of tensors - Variable, Constant, Placeholder, model . predict_step ( data )
from tensorflow import keras
SparseTensor
Various Operations Activation and dropout layers Text and Sequence Preprocessing
• Print summary of model - model.summary() • Applies an activation function to an output - • Text tokenization utility class -
keras.layers.Activation(’relu’) keras.preprocessing.text.Tokenizer()
• Adds a layer on top of the layer stack - • Different versions of a Rectified Linear Unit - • One-hot encodes a text into a list of word indexes -
model.add(layer) keras.layers.ReLU(), keras.layers.LeakyReLU(), keras.preprocessing.text.one hot()
• Retrieves a layer using name/index - keras.layers.PReLU()
• Pads sequences to the same length -
model.get layer() • Applies Dropout to the input - keras.preprocessing.sequence.pad sequences
keras.layers.Dropout()
• Save the model and reload it at anytime in the future - • Generates skipgram word pairs -
• Spatial 1D, 2D, 3D version of Dropout - Spatial 1D
model.save() and keras.models.load model() keras.preprocessing.sequence.skipgrams()
version of Dropout.
• Various datasets to play with - keras.datasets Recurrent and Embedding layers Pre-trained models
• For example - keras.datasets.cifar10.load data(), • Turns positive integers (indexes) into dense vectors of • Transfer learning and fine-tuning of pretrained models
this model contains 60,000 32x32 color images with fixed size - keras.layers.Embedding() saves time if your data set does not differ significantly
6000 images of 10 different everyday objects. • Long Short-Term Memory layer - from the original one. Keras applications are deep
keras.layers.LSTM() learning models that are made available alongside
• Draws samples from a categorical distribution - pre-trained weights. These models can be used for
tf.random.categorical() • Base class for recurrent layers - keras.layers.RNN()
prediction, feature extraction, and fine-tuning -
• Gated Recurrent Unit - keras.layers.GRU() keras.applications
• Load any checkpoint by specifying the exact file to load
- tf.train.load checkpoint() Flatten, Dense and Locally connected layers • For example - keras.applications.MobileNetV2(),
• Flattens the input, does not affect the batch size - this model is trained on 1.4 million images and has 1000
keras.layers.Flatten() different classes.
Different layers
• Densely-connected NN layer - keras.layers.Dense(32,
Various keras layers are under keras.layers activation=’relu’) Various Hyperparameters
• Locally-connected layer works similarly to the Conv Built-in optimizers
Convolutional and Pooling layers
layer, except that weights are unshared, that is, a tf.keras.optimizers
• The choice of dimension (1D, 2D, 3D) depends on the different set of filters is applied at each different patch
• Stochastic Gradient descent
dimensions of input. of the input - keras.layers.LocallyConnected1D,
keras.layers.LocallyConnected2D • Adagrad
• Conv1D is usually used for input signals which are
• Adam
similar to the voice. Conv2D is used for images. Callbacks
Conv3D is usually used for videos where you have a A callback is a set of functions to be applied at given stages of • RMSProp
frame for each time span. - layers.Conv1D(), the training procedure. You can use callbacks to get a view on
layers.Conv2D(), layers.Conv3D() Built-in loss functions
internal states and statistics of the model during training -
keras.callbacks tf.keras.losses
• The need for transposed convolutions generally arises
from the desire to use a transformation going in the • Callback to save the Keras model or model weights at • BinaryCrossentropy
opposite direction of a normal convolution - some frequency - • CategoricalCrossentropy
keras.layers.Conv1DTranspose() keras.callbacks.ModelCheckpoint()
• MeanAbsoluteError
• Stop training when a monitored metric has stopped
• Zero padding layers - keras.layers.ZeroPadding1D() • MeanSquaredError
improving - keras.callbacks.EarlyStopping()
• Cropping layers - keras.layers.ZeroPadding1D() Built-in metrics
Pre-Processing
• Upsampling layers - keras.layers.UpSampling1D() tf.keras.metrics
Image Preprocessing
• Accuracy
• Max pooling operations - keras.layers.MaxPool1D(), • Set of tools for real-time data augmentation on image
keras.layers.MaxPool2D(), data. - keras.preprocessing.image • AUC
keras.layers.MaxPool3D() • Loading an image, image to array and vice versa - • False Positive
keras.preprocessing.image.load img(),
• Average pooling - keras.layers.AveragePooling1D() • Precision
keras.preprocessing.image.array to img(),
• Global average pooling operation and Global max keras.preprocessing.image.img to array()
pooling operation - • Generate batches of tensor image data with real-time
keras.layers.GlobalAveragePooling1D(), data augmentation -
keras.layers.GlobalMaxPool2D() keras.preprocessing.image.ImageGenerator

You might also like