Showing posts with label Deep Learning. Show all posts
Showing posts with label Deep Learning. Show all posts

Sunday, 5 December 2021

Fundamentals of Deep Learning | Basic Concepts

 



Fundamentals of Deep Learning


    In this blog, we will discuss the fundamentals of deep learning with a brief introduction and then look at the logical component of deep learning. 


Introduction of Deep Learning


    Deep Learning is a subset of machine learning in artificial intelligence (AI) that deals with artificial neural networks, algorithms caused by the biological structure and functioning of the human brain to aid machines with intelligence. It learns from a large amount of data to bring out meaningful insights for decision-making.





    Deep learning would be able to leverage the surplus data more effectively for improved performance. The following diagram represents the deep learning model performance with the data size.




    Deep Learning models are designed using the neural network architecture, and it enables learning through performing tasks repeatedly to improve the outcome. A neural network is a collection of the hierarchical structure of neurons, and it is similar to the nervous system in the human body works. Each neuron with connection to other neurons, and it transmits the information or signal to other neurons.





The deep neural network will consist of three types of layers:

  • Input Layer
  • Hidden Layer
  • Output Layer


    As you can see above example, the input layer takes the input data by the user, and that input data has consumed by the neurons in the first hidden layer, then it performs various computations on the input data, which then provides an output from the output layer. 





    Each layer has one or more neurons, and each of them will compute various functions (like activation function). The connection between two neurons would have some weight. That weight defines the impact of the input for the next neuron, and finally, for the overall final output is provided by the output layer. In a neural network, the initial weights would all be random during the model training, but these weights are updated or learned iteratively to predict a correct output. 



Basic Components of Deep Learning

Activation Function

    An activation function is the function that takes the combined input as shown in the previous sample, applies a function on it, and passes the output value, it decides whether the neuron should be activated or not.


    

    There are many types of activation functions available in deep learning. The most commonly used functions are sigmoid function, the ReLU (rectified linear unit), SoftMax function and, tanh function.






Core Layers

    There are some important layers in deep neural network(DNN), that we will be using in the most use case.

Dense Layer

    A dense layer is also referred to as a fully connected layer, it is a regular DNN layer that connects all neurons in the output layer to all neurons in the previous layer.
tf.keras.layers.Dense(
    units,
    activation=None,
    use_bias=True,
    kernel_initializer="glorot_uniform",
    bias_initializer="zeros",
    kernel_regularizer=None,
    bias_regularizer=None,
    activity_regularizer=None,
    kernel_constraint=None,
    bias_constraint=None,
    **kwargs
)


Dropout Layer


    A dropout layer intercepts all neurons in a layer of synchronously optimizing their weights. It helps to reduce overfitting by introducing regularization and generalization capabilities into the model. Its drops out some neurons from layers.

tf.keras.layers.Dropout(rate, 
	noise_shape=None, 
    	seed=None, 
    	**kwargs)


Loss Function


The loss function is an important concept of deep learning. It's nothing but a prediction error of a neural network. It helps a neural network understand whether model learning goes in the right direction.


There are some popular loss functions available here:
  • Mean squared error
  • Mean absolute error
  • Binary cross-entropy
  • Categorical cross-entropy
  • Sparse categorical cross-entropy
        etc...

Optimizers 


Optimizer function is a mathematical algorithm to use understand how much change the network will see in the loss function. It helps to reduce losses and get results faster.


There are some popular optimizer available here:

  • Adam(Adaptive Moment Estimation)
  • SGD(Stochastic Gradient Descent)
  • RMSprop(Root Mean Square Propagation)
        etc...

Metrics


    The metrics can be understood as the function that is used to judge the performance of the model, that the results from evaluating metrics are not used in training the model concerning optimization. And we can also define custom functions for our model metrics.


Model Training


    Once we configure a model, we have ready to train the model with the training data and validation data for us to evaluate whether the model is performing as desired after each epoch. 



Example:

import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# Create dummy dataset  

# training dataset
np.random.seed(1000)
X_train = np.random.random((10000,10))
y_train = np.random.randint(2, size=(10000, 1))

# validation dataset
X_val = np.random.random((2500,10))
y_val = np.random.randint(2, size=(2500, 1))

# test dataset
X_test = np.random.random((2500,10))
y_test = np.random.randint(2, size=(2500, 1))

#Define the model architecture
model = Sequential()
model.add(Dense(64,input_dim=10,activation="relu"))
model.add(Dense(32,activation = "relu")) 
model.add(Dense(16,activation = "relu")) 
model.add(Dense(8,activation = "relu")) 
model.add(Dense(4,activation = "relu"))
model.add(Dense(1,activation = "sigmoid")) 

#Compile the model
model.compile(optimizer='Adam',
	loss='binary_crossentropy',
    	metrics=['accuracy'])

#Train the model
model.fit(X_train, 
	y_train, 
    	epochs=2, 
    	validation_data=(X_val,y_val))
Out[]:
Epoch 1/2
157/157 [=============] - 1s 5ms/step - 
loss: 0.6934 - accuracy: 0.4964 - 
val_loss: 0.6934 - val_accuracy: 0.4904
Epoch 2/2
157/157 [=============] - 1s 3ms/step - 
loss: 0.6933 - accuracy: 0.5044 - 
val_loss: 0.6933 - val_accuracy: 0.5044



Conclusion


    In summary, I hope now you understand the fundamentals of deep learning. It’s really easy once you understand doing it practically as well. If you want to explore more, please check my blog site: Techy Scientists and GitHub



References:

    [1]: Learn Keras for Deep Neural Networks, A Fast-Track Approach to Modern Deep Learning with Python, Jojo Moolayil, Apress. link

Saturday, 18 September 2021

Image Classification Using Convolutional Neural Network (CNN)

 





Cifar10 Image Classification using Convolutional Neural Network 


Introduction:


    In this blog, I created image classification using convolutional neural network on Cifar10 small image classification data which I have implemented using TensorFlow and Keras.

    This blog offers you a step-by-step instruction guide with source code, so you can build your model. It is not designed to be a deep dive into model design, statistical analysis, improvement, and validation. If you want to learn more, please check out my blog site: Techy Scientists.

It contains the following parts:


  1. Setup your environment
  2. Build your image classification model
  3. Model Prediction


Setup your environment


   To run the program on your local computer, install the following required libraries, These libraries are 


  1.   python 3.8.0
  2.   numpy
  3.   pandas
  4.   matplotlib
  5.   tensorflow 2.0
  6.   keras 2.3.0


Build your image classification model


Step 1: Understand the data


  The first step of model prediction is to understand the data. It is more important to all machine learning and deep learning projects. You can find more information about the data, go to CIFAR10 small images classification dataset.






Step 2: Import the Packages


  Create a python file (for example model.py). After installed the required packages, import packages  in your python file.


import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import datasets, layers, models

Step 3: Import the data

    Next, import the data

cifar = datasets.cifar10

Step 4: Split the data
    
    We want to create a model, must have split it into training and testing. The model trained by training dataset and then apply the evaluation of model used by testing dataset.

(X_train, y_train), (X_test,y_test) = cifar.load_data()

Then, resize the data

y_train = y_train.reshape(-1,)
y_test = y_test.reshape(-1,)


Step 5: Normalize the data

    Then, Normalize the data values to the range [0, 1].

X_train = X_train / 255.0
X_test = X_test / 255.0


Step 6: Create Deep Learning Model

    We create model for image classification using convolutional neural network. It is type of deep learning networks. It is used for classification, segmentation and image processing problems. In this neural network, extract the features from input layer and perform mathematical convolutional operation. 


cnn = models.Sequential([
    layers.Conv2D(filters=32, 
    	kernel_size=(3, 3), 
        activation='relu', 
        input_shape=(32, 32, 3)),
    layers.MaxPooling2D((2, 2)),
    
    layers.Conv2D(filters=64, 
    	kernel_size=(3, 3), 
        activation='relu'),
    layers.MaxPooling2D((2, 2)),
    
    layers.Flatten(),
    layers.Dense(64, activation='relu'),
    layers.Dense(10, activation='softmax')
])


  •     Sequential - appropriate for a plain stack of layers where each layer has exactly one input tensor and one output tensor.
  •     Conv2D - Convolutional two dimensional layer.
  •     MaxPooling2D - pooling operation that calculate maximum value.
  •     Flatten -  matrix flatten to one dimensional array.
  •     Dense - fully connected neural network layer and it implement the operations.
  •     Activation - used through an activation  layer, or through the activation argument supported by all forward layers.


Step 7: Train the Model

    Now, we ready to train the model.

cnn.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
cnn.fit(X_train, y_train, epochs=10)
Out[]:
Epoch 1/10
1563/1563 [============] - 6s 4ms/step -
loss: 1.5192 - accuracy: 0.4548
Epoch 2/10
1563/1563 [============] - 6s 4ms/step -
loss: 1.1484 - accuracy: 0.6002
Epoch 3/10
1563/1563 [============] - 6s 4ms/step -
loss: 1.0044 - accuracy: 0.6497
Epoch 4/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.9205 - accuracy: 0.6823
Epoch 5/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.8628 - accuracy: 0.7020
Epoch 6/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.8106 - accuracy: 0.7186
Epoch 7/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.7674 - accuracy: 0.7340
Epoch 8/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.7278 - accuracy: 0.7475
Epoch 9/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.6919 - accuracy: 0.7611
Epoch 10/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.6584 - accuracy: 0.7708


Step 8: Evaluate the Model

    Finally, We created the model and then evaluate it.

cnn.evaluate(X_test,y_test)
313/313 [==============] - 0s 1ms/step -
loss: 0.9197 - accuracy: 0.6942

[0.9197465777397156, 0.6941999793052673]


Model Prediction

    Finally, We predict the label of data on the basis of trained model. It returns the labels of the data passed as argument based upon the learned or trained data obtained from the model.

classes = ["airplane",
"automobile",
"bird",
"cat",
"deer",
"dog",
"frog",
"horse",
"ship",
"truck"]

    

Then, we predict the model using test dataset.

y_pred = cnn.predict(X_test)
       
Check that prediction,
y_classes = [np.argmax(element) for element in y_pred]
y_classes[:5]
Out[]:
[3, 8, 8, 0, 6]
def plot_sample(X, y, index):
    plt.figure(figsize = (15,2))
    plt.imshow(X[index])
    plt.xlabel(classes[y[index]])
plot_sample(X_test, y_test,3)


classes[y_classes[3]]
Out[]:
'airplane'

Conclusion:

     In summary, we created the image classification using convolutional neural network on fashion mnist data which I have implemented using TensorFlow and Keras. If you want to source code, check this GitHub linkImage classification.



Sunday, 5 September 2021

Simple Text Classification using LSTM


Simple Text Classification using LSTM for Beginners


Introduction:


    In this blog, I created Simple Text Classification using LSTM (Long Short Term Memory) on IMDB movie review sentiment classification dataset, which I have implemented using Keras.

    This blog offers you a step-by-step instruction guide with source code, so you can build your model. It is not designed to be a deep dive into model design, statistical analysis, improvement, and validation. If you want to learn more, please check out my blog site: Techy Scientists.

It contains the following parts:


  1. Setup your environment
  2. Build your Text Classification model
  3. Model Validation


Setup your environment


   To run the program on your local computer, install the following required libraries, These libraries are 


  1.   python 3.8.0
  2.   numpy
  3.   pandas
  4.   matplotlib
  5.   scikit-learn
  6.   tensorflow 2.0
  7.   keras 2.3.0


Build your Text Classification model


Step 1: Understand the data


  The first step of model prediction is to understand the data. It is more important to all machine learning and deep learning projects. You can find more information about the data, go to IMDB Movie Review Sentiment Classification Data.



Step 2: Import the Packages


  Create a python file (for example model.py). After installed the required packages, import packages  in your python file.


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.embeddings import Embedding
from keras.preprocessing import sequence
np.random.seed(7)

Step 3: Import and Split the data

    Next, import the data using pandas and split the data into training and testing. The model trained by training dataset and then apply the evaluation of model used by test dataset. 

top_words = 5000
(X_train, y_train), (X_test, y_test) = 
	imdb.load_data(num_words=top_words)
print('Shape of training data: ')
print(X_train.shape)
print(y_train.shape)
print('Shape of test data: ')
print(X_test.shape)
print(y_test.shape)
Out[]:
Shape of training data: 
(25000,)
(25000,)
Shape of test data: 
(25000,)
(25000,)


Step 4: Padding the data

    Padding the data transform list of sequences into 2D Numpy array of shape. It used to pad the number of samples length.
max_review_length = 500
X_train = sequence.pad_sequences(X_train, 
	maxlen=max_review_length)
X_test = sequence.pad_sequences(X_test, 
	maxlen=max_review_length)


Step 5:
 Create LSTM (Long Short Term Memory) Model

    We create model for simple text classification using LSTM. It is type of deep learning networks. It is variation of reccurent neural network. In this neural network, has feedback connections. 

epochs = 10

embedding_vecor_length = 16
model = Sequential()
model.add(Embedding(top_words, 
	embedding_vecor_length, 
    	input_length=max_review_length))
model.add(LSTM(16))
model.add(Dense(1, activation='sigmoid'))


  •     Embedding- used for text data, requires that input data be encoded.
  •     LSTM- lstm layer, information thorugh as it propagates forward.
  •     Dense - fully connected neural network layer and it implement the operations.
  •     Activation - used through an activation  layer, or through the activation argument supported by all forward layers.


model.summary()

Out[]:
Model: "sequential"

Layer (type)               Output Shape       Param #   
===========================================
embedding (Embedding)      (None, 500, 16)    80000     
___________________________________________
lstm (LSTM)                (None, 16)         2112      
___________________________________________
dense (Dense)              (None, 1)          17        
===========================================
Total params: 82,129
Trainable params: 82,129
Non-trainable params: 0
___________________________________________

Step 6: Train the Model

    Now, we ready to train the model.

model.compile(optimizer='rmsprop', 
	loss='binary_crossentropy', 
    	metrics=['accuracy'])
history = model.fit(X_train, 
	y_train, 
    	validation_data=(X_test, y_test), 
        epochs=epochs, 
            	batch_size=64)
Out[]:
Epoch 1/10
391/391 [=========] - 89s 222ms/step -
loss: 0.5819 - accuracy: 0.6733
- val_loss: 0.3507 - val_accuracy: 0.8565
Epoch 2/10
391/391 [=========] - 85s 217ms/step -
loss: 0.2959 - accuracy: 0.8832
- val_loss: 0.3219 - val_accuracy: 0.8748
Epoch 3/10
391/391 [=========] - 86s 221ms/step -
loss: 0.2520 - accuracy: 0.9049
- val_loss: 0.2859 - val_accuracy: 0.8808
Epoch 4/10
391/391 [=========] - 87s 223ms/step -
loss: 0.2263 - accuracy: 0.9155
- val_loss: 0.2997 - val_accuracy: 0.8828
Epoch 5/10
391/391 [=========] - 87s 223ms/step -
loss: 0.2101 - accuracy: 0.9233
- val_loss: 0.3244 - val_accuracy: 0.8742
Epoch 6/10
391/391 [=========] - 84s 216ms/step -
loss: 0.2057 - accuracy: 0.9239
- val_loss: 0.3207 - val_accuracy: 0.8778
Epoch 7/10
391/391 [=========] - 85s 217ms/step -
loss: 0.1951 - accuracy: 0.9268
- val_loss: 0.3366 - val_accuracy: 0.8714
Epoch 8/10
391/391 [==========] - 85s 218ms/step -
loss: 0.1919 - accuracy: 0.9296
- val_loss: 0.3122 - val_accuracy: 0.8807
Epoch 9/10
391/391 [==========] - 85s 217ms/step -
loss: 0.1809 - accuracy: 0.9345
- val_loss: 0.4599 - val_accuracy: 0.8459
Epoch 10/10
391/391 [==========] - 84s 215ms/step -
loss: 0.1708 - accuracy: 0.9374
- val_loss: 0.3143 - val_accuracy: 0.8803


Model Validation

    Finally, We created the model and then validate it.

test =  model.evaluate(X_test, y_test, verbose=0)
print("Testing Accuracy: %.2f%%" % (test[1]*100))
Out[]:
Testing Accuracy: 88.03%
    Visualize the accuracy and loss between training and validation.
def plot_result(history, epoch):
    
    epoch_range = range(1, epoch+1)
    
    plt.plot(epoch_range, 
    	history.history['accuracy'], 
        label='Training acc')
    plt.plot(epoch_range, 
    	history.history['val_accuracy'], 
        label='Validation acc')
    plt.title('Training and validation accuracy')
    plt.xlabel('epochs')
    plt.ylabel('acc')
    plt.legend()

    plt.show()
    
    plt.plot(epoch_range, 
    	history.history['loss'], 
        label='Training loss')
    plt.plot(epoch_range, 
    	history.history['val_loss'], 
        label='Validation loss')
    plt.title('Training and validation loss')
    plt.xlabel('epochs')
    plt.ylabel('loss')
    plt.legend()

    plt.show()
plot_result(history, epochs)

Training and validation accuracy




Training and validation loss




Conclusion:

     In summary, we created the Simple Text Classification using LSTM (Long Short Term Memory) on IMDB movie review sentiment classification dataset, which I have implemented using Keras. If you want to source code, check this GitHub linkSimple Text Classification using LSTM.

Thank you...