Deep Learning Projects Archives - Indian AI Production https://indianaiproduction.com/deep-learning-projects/ Artificial Intelligence Education Free for Everyone Mon, 31 Aug 2020 05:27:17 +0000 en-US hourly 1 https://i0.wp.com/indianaiproduction.com/wp-content/uploads/2019/06/Channel-logo-in-circle-473-x-472-px.png?fit=32%2C32&ssl=1 Deep Learning Projects Archives - Indian AI Production https://indianaiproduction.com/deep-learning-projects/ 32 32 163118462 InceptionV3 Convolution Neural Network Architecture Explain | Object Detection https://indianaiproduction.com/inceptionv3-cnn-model/ https://indianaiproduction.com/inceptionv3-cnn-model/#respond Mon, 17 Aug 2020 06:56:51 +0000 https://indianaiproduction.com/?p=1646 Inception is a CNN Architecture Model. The network trained on more than a million images from the ImageNet database. The pretrained network can classify images into 1000 object categories, such as keyboard, computer, pen, and many hourse. Inception V3 Project Inception Paper >>> https://arxiv.org/abs/1409.4842 Network in Network Paper >>> https://arxiv.org/abs/1312.4400 Keras Application >>> https://keras.io/api/applications/

The post InceptionV3 Convolution Neural Network Architecture Explain | Object Detection appeared first on Indian AI Production.

]]>

Inception is a CNN Architecture Model. The network trained on more than a million images from the ImageNet database. The pretrained network can classify images into 1000 object categories, such as keyboard, computer, pen, and many hourse.

Inception V3 Project

# Inception V3

from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras.applications.inception_v3 import decode_predictions
from keras.applications.inception_v3 import preprocess_input

from keras.preprocessing import image
import numpy as np
import matplotlib.pyplot as plt
import os
from os import listdir
from PIL import Image as PImage

img_width, img_height = 299, 299

model_pretrained = InceptionV3(weights='imagenet', 
                      include_top=True, 
                      input_shape=(img_height, img_width, 3))

# Insert correct path of your image below
img_path = '/content/drive/My Drive/My ML Project /DL Project/Transfer Learning/images/lemon.png'
img = image.load_img(img_path, target_size=(img_width, img_height))
img_data = image.img_to_array(img)
img_data = np.expand_dims(img_data, axis=0)
img_data = preprocess_input(img_data)

#predict the result
cnn_feature = model_pretrained.predict(img_data,verbose=0)
# decode the results into a list of tuples (class, description, probability)
label = decode_predictions(cnn_feature)
label = label[0][0]


plt.imshow(img)

stringprint ="%.1f" % round(label[2]*100,1)
plt.title(label[1] + " " + str(stringprint) + "%", fontsize=20)
plt.axis('off')
plt.show()

# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted:', decode_predictions(cnn_feature, top=3)[0])

label

# Insert correct path of your image below
img_path = '/content/drive/My Drive/My ML Project /DL Project/Transfer Learning/images/flowers-5463475_640.jpg'
img = image.load_img(img_path, target_size=(img_width, img_height))
img_data = image.img_to_array(img)
img_data = np.expand_dims(img_data, axis=0)
img_data = preprocess_input(img_data)

#predict the result
cnn_feature = model_pretrained.predict(img_data,verbose=0)
# decode the results into a list of tuples (class, description, probability)
label = decode_predictions(cnn_feature)
label = label[0][0]


plt.imshow(img)

stringprint ="%.1f" % round(label[2]*100,1)
plt.title(label[1] + " " + str(stringprint) + "%", fontsize=20)
plt.axis('off')
plt.show()

# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted:', decode_predictions(cnn_feature, top=3)[0])

# Insert correct path of your image folder below

folder_path = '/content/drive/My Drive/My ML Project /DL Project/Transfer Learning/images/'
images = os.listdir(folder_path)
fig = plt.figure(figsize=(16,20))
i=0
rows=4
columns=3

for image1 in images:
    i+=1
    img = image.load_img(folder_path+image1, target_size=(img_width, img_height))
    img_data = image.img_to_array(img)
    img_data = np.expand_dims(img_data, axis=0)
    img_data = preprocess_input(img_data)

    cnn_feature = model_pretrained.predict(img_data,verbose=0)
    label = decode_predictions(cnn_feature)
    label = label[0][0]
    
    fig.add_subplot(rows,columns,i)
    fig.subplots_adjust(hspace=.5)

    plt.imshow(img)
    stringprint ="%.1f" % round(label[2]*100,1)
    plt.title(label[1] + " " + str(stringprint) + "%", fontsize=20)
    plt.axis('off')
plt.show()

Inception Paper >>> https://arxiv.org/abs/1409.4842

Network in Network Paper >>> https://arxiv.org/abs/1312.4400

Keras Application >>> https://keras.io/api/applications/

The post InceptionV3 Convolution Neural Network Architecture Explain | Object Detection appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/inceptionv3-cnn-model/feed/ 0 1646
VGG16 CNN Model Architecture | Transfer Learning https://indianaiproduction.com/vgg16-convolutional-neural-network/ https://indianaiproduction.com/vgg16-convolutional-neural-network/#respond Sun, 16 Aug 2020 06:01:29 +0000 https://indianaiproduction.com/?p=1643 VGG16 was introduced in 2014 by Karen Simonyan and Andrew Zisserman in the paper titled Very Deep Convolutional Networks for Large-Scale Image Recognition. The paper can be read at https://arxiv.org/abs/1409.1556 VGG16 CNN Model Keras Application >>> https://keras.io/api/applications/

The post VGG16 CNN Model Architecture | Transfer Learning appeared first on Indian AI Production.

]]>
VGG16 was introduced in 2014 by Karen Simonyan and Andrew Zisserman in the paper titled Very Deep Convolutional Networks for Large-Scale Image Recognition.

The paper can be read at https://arxiv.org/abs/1409.1556

VGG16 CNN Model

# VGG16
 
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg16 import decode_predictions
from keras.applications.vgg16 import preprocess_input
 
from keras.preprocessing import image
import numpy as np
import matplotlib.pyplot as plt
import os
from os import listdir
from PIL import Image as PImage
 
img_width, img_height = 224, 224
 
model_pretrained = VGG16(weights='imagenet', 
                      include_top=True, 
                      input_shape=(img_height, img_width, 3))
 
# Insert correct path of your image below
img_path = '/content/drive/My Drive/My ML Project /DL Project/Transfer Learning/images/lemon.png'
img = image.load_img(img_path, target_size=(img_width, img_height))
img_data = image.img_to_array(img)
img_data = np.expand_dims(img_data, axis=0)
img_data = preprocess_input(img_data)
 
#predict the result
cnn_feature = model_pretrained.predict(img_data,verbose=0)
# decode the results into a list of tuples (class, description, probability)
label = decode_predictions(cnn_feature)
label = label[0][0]
 
 
plt.imshow(img)
 
stringprint ="%.1f" % round(label[2]*100,1)
plt.title(label[1] + " " + str(stringprint) + "%", fontsize=20)
plt.axis('off')
plt.show()
 
# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted:', decode_predictions(cnn_feature, top=3)[0])
 
label
 
# Insert correct path of your image below
img_path = '/content/drive/My Drive/My ML Project /DL Project/Transfer Learning/images/flowers-5463475_640.jpg'
img = image.load_img(img_path, target_size=(img_width, img_height))
img_data = image.img_to_array(img)
img_data = np.expand_dims(img_data, axis=0)
img_data = preprocess_input(img_data)
 
#predict the result
cnn_feature = model_pretrained.predict(img_data,verbose=0)
# decode the results into a list of tuples (class, description, probability)
label = decode_predictions(cnn_feature)
label = label[0][0]
 
 
plt.imshow(img)
 
stringprint ="%.1f" % round(label[2]*100,1)
plt.title(label[1] + " " + str(stringprint) + "%", fontsize=20)
plt.axis('off')
plt.show()
 
# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted:', decode_predictions(cnn_feature, top=3)[0])
 
# Insert correct path of your image folder below
 
folder_path = '/content/drive/My Drive/My ML Project /DL Project/Transfer Learning/images/'
images = os.listdir(folder_path)
fig = plt.figure(figsize=(16,20))
i=0
rows=4
columns=3
 
for image1 in images:
    i+=1
    img = image.load_img(folder_path+image1, target_size=(img_width, img_height))
    img_data = image.img_to_array(img)
    img_data = np.expand_dims(img_data, axis=0)
    img_data = preprocess_input(img_data)
 
    cnn_feature = model_pretrained.predict(img_data,verbose=0)
    label = decode_predictions(cnn_feature)
    label = label[0][0]
     
    fig.add_subplot(rows,columns,i)
    fig.subplots_adjust(hspace=.5)
 
    plt.imshow(img)
    stringprint ="%.1f" % round(label[2]*100,1)
    plt.title(label[1] + " " + str(stringprint) + "%", fontsize=20)
    plt.axis('off')
plt.show()

Keras Application >>> https://keras.io/api/applications/

The post VGG16 CNN Model Architecture | Transfer Learning appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/vgg16-convolutional-neural-network/feed/ 0 1643
ResNet50 CNN Model Architecture | Transfer Learning https://indianaiproduction.com/resnet50-cnn-model/ https://indianaiproduction.com/resnet50-cnn-model/#respond Sun, 16 Aug 2020 05:52:38 +0000 https://indianaiproduction.com/?p=1640 ResNet-50 is a Cnn That Is 50 layers deep. the network trained on more than a million images from the ImageNet database. The pretrained network can classify images into 1000 object categories, such as keyboard, computer, pen, and many hourse. ResNet50 CNN Model Paper Link >> https://arxiv.org/pdf/1512.03385.pdf Keras Applications >> https://keras.io/api/applications/

The post ResNet50 CNN Model Architecture | Transfer Learning appeared first on Indian AI Production.

]]>
ResNet-50 is a Cnn That Is 50 layers deep. the network trained on more than a million images from the ImageNet database. The pretrained network can classify images into 1000 object categories, such as keyboard, computer, pen, and many hourse.

ResNet50 CNN Model

# ResNet50

from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.applications.resnet50 import decode_predictions
from keras.applications.resnet50 import preprocess_input

from keras.preprocessing import image
import numpy as np
import matplotlib.pyplot as plt
import os
from os import listdir
from PIL import Image as PImage

img_width, img_height = 224, 224

model_pretrained = ResNet50(weights='imagenet', 
                      include_top=True, 
                      input_shape=(img_height, img_width, 3))

# Insert correct path of your image below
img_path = '/content/drive/My Drive/My ML Project /DL Project/Transfer Learning/images/lemon.png'
img = image.load_img(img_path, target_size=(img_width, img_height))
img_data = image.img_to_array(img)
img_data = np.expand_dims(img_data, axis=0)
img_data = preprocess_input(img_data)

#predict the result
cnn_feature = model_pretrained.predict(img_data,verbose=0)
# decode the results into a list of tuples (class, description, probability)
label = decode_predictions(cnn_feature)
label = label[0][0]


plt.imshow(img)

stringprint ="%.1f" % round(label[2]*100,1)
plt.title(label[1] + " " + str(stringprint) + "%", fontsize=20)
plt.axis('off')
plt.show()

# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted:', decode_predictions(cnn_feature, top=3)[0])

label

# Insert correct path of your image below
img_path = '/content/drive/My Drive/My ML Project /DL Project/Transfer Learning/images/flowers-5463475_640.jpg'
img = image.load_img(img_path, target_size=(img_width, img_height))
img_data = image.img_to_array(img)
img_data = np.expand_dims(img_data, axis=0)
img_data = preprocess_input(img_data)

#predict the result
cnn_feature = model_pretrained.predict(img_data,verbose=0)
# decode the results into a list of tuples (class, description, probability)
label = decode_predictions(cnn_feature)
label = label[0][0]


plt.imshow(img)

stringprint ="%.1f" % round(label[2]*100,1)
plt.title(label[1] + " " + str(stringprint) + "%", fontsize=20)
plt.axis('off')
plt.show()

# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted:', decode_predictions(cnn_feature, top=3)[0])

# Insert correct path of your image folder below

folder_path = '/content/drive/My Drive/My ML Project /DL Project/Transfer Learning/images/'
images = os.listdir(folder_path)
fig = plt.figure(figsize=(16,20))
i=0
rows=4
columns=3

for image1 in images:
    i+=1
    img = image.load_img(folder_path+image1, target_size=(img_width, img_height))
    img_data = image.img_to_array(img)
    img_data = np.expand_dims(img_data, axis=0)
    img_data = preprocess_input(img_data)

    cnn_feature = model_pretrained.predict(img_data,verbose=0)
    label = decode_predictions(cnn_feature)
    label = label[0][0]
    
    fig.add_subplot(rows,columns,i)
    fig.subplots_adjust(hspace=.5)

    plt.imshow(img)
    stringprint ="%.1f" % round(label[2]*100,1)
    plt.title(label[1] + " " + str(stringprint) + "%", fontsize=20)
    plt.axis('off')
plt.show()

Paper Link >> https://arxiv.org/pdf/1512.03385.pdf

Keras Applications >> https://keras.io/api/applications/

The post ResNet50 CNN Model Architecture | Transfer Learning appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/resnet50-cnn-model/feed/ 0 1640
🌿Cotton Plant Disease Prediction & Get Cure App using Artificial Intelligence https://indianaiproduction.com/cotton-plant-disease-prediction-get-cure-app-using-artificial-intelligence/ https://indianaiproduction.com/cotton-plant-disease-prediction-get-cure-app-using-artificial-intelligence/#comments Tue, 11 Aug 2020 12:39:21 +0000 https://indianaiproduction.com/?p=1613 I developed “🌿Cotton Plant Disease Prediction & Get Cure App” using Artificial Intelligence especially Deep learning. As Farmer, I know Farmer can’t solve Farm’s complex and even small problems due to lack of perfect education. So as AI enthusiastic I decided to solve this problem using the latest technology like AI. I just took baby …

🌿Cotton Plant Disease Prediction & Get Cure App using Artificial Intelligence Read More »

The post 🌿Cotton Plant Disease Prediction & Get Cure App using Artificial Intelligence appeared first on Indian AI Production.

]]>

I developed “🌿Cotton Plant Disease Prediction & Get Cure App” using Artificial Intelligence especially Deep learning. As Farmer, I know Farmer can’t solve Farm’s complex and even small problems due to lack of perfect education. So as AI enthusiastic I decided to solve this problem using the latest technology like AI.

I just took baby step and start to collect lots of images of cotton crop plants from my farm. To collect accurate data we need expertise in that domain and as a farmer it help me a lot.

Then I decide which algorithm is best to solve this problem and I select as usual you know “Convolution Neural Network” (CNN). I create my own CNN architecture and it works well on the training and as well as testing dataset.

It gives me more than 98% accuracy on training and validation data set in just 500 epochs. I am trying to increase accuracy with more data and epochs.

After that I have deployed this model on AWS cloud. Please have look.

Model Accuracy & Loss

Tools / IDE

I used Jupyter NoteBook (Google Colab) for model training. used spyder for model deployment on the local system. To use Jupyter NoteBook and Spyder, just install anaconda.

Software Requirments

  • Python == 3.7.7
  • TensorFlow == 2.1.0
  • Keras == 2.4.3
  • NumPy == 1.18.5
  • Flask == 1.1.2

Install above packages using below command in anaconda prompt

pip install tensorflow==2.1.0
pip install Keras==2.4.3
pip install numpy==1.18.5
pip install flask==1.1.2

Training 🌿Cotton Plant Disease Prediction & Get Cure AI App

## Project: Cotton Plant Disease Prediction & Get Cure AI App - IAIP

#import libraries
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
import matplotlib.pyplot as plt

keras.__version__

train_data_path = "/content/drive/My Drive/My ML Project /DL Project/CNN/cotton plant disease prediction/data/train"
validation_data_path = "/content/drive/My Drive/My ML Project /DL Project/CNN/cotton plant disease prediction/data/val"

def plotImages(images_arr):
    fig, axes = plt.subplots(1, 5, figsize=(20, 20))
    axes = axes.flatten()
    for img, ax in zip(images_arr, axes):
        ax.imshow(img)
    plt.tight_layout()
    plt.show()

# this is the augmentation configuration we will use for training
# It generate more images using below parameters
training_datagen = ImageDataGenerator(rescale=1./255,
                                      rotation_range=40,
                                      width_shift_range=0.2,
                                      height_shift_range=0.2,
                                      shear_range=0.2,
                                      zoom_range=0.2,
                                      horizontal_flip=True,
                                      fill_mode='nearest')

# this is a generator that will read pictures found in
# at train_data_path, and indefinitely generate
# batches of augmented image data
training_data = training_datagen.flow_from_directory(train_data_path, # this is the target directory
                                      target_size=(150, 150), # all images will be resized to 150x150
                                      batch_size=32,
                                      class_mode='binary')  # since we use binary_crossentropy loss, we need binary labels

training_data.class_indices



# this is the augmentation configuration we will use for validation:
# only rescaling
valid_datagen = ImageDataGenerator(rescale=1./255)

# this is a similar generator, for validation data
valid_data = valid_datagen.flow_from_directory(validation_data_path,
                                  target_size=(150,150),
                                  batch_size=32,
                                  class_mode='binary')

images = [training_data[0][0][0] for i in range(5)]
plotImages(images)

model_path = '/content/drive/My Drive/My ML Project /DL Project/CNN/cotton plant disease prediction/v3_red_cott_dis.h5'
checkpoint = ModelCheckpoint(model_path, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')
callbacks_list = [checkpoint]

#Building cnn model
cnn_model = keras.models.Sequential([
                                    keras.layers.Conv2D(filters=32, kernel_size=3, input_shape=[150, 150, 3]),
                                    keras.layers.MaxPooling2D(pool_size=(2,2)),
                                    keras.layers.Conv2D(filters=64, kernel_size=3),
                                    keras.layers.MaxPooling2D(pool_size=(2,2)),
                                    keras.layers.Conv2D(filters=128, kernel_size=3),
                                    keras.layers.MaxPooling2D(pool_size=(2,2)),                                    
                                    keras.layers.Conv2D(filters=256, kernel_size=3),
                                    keras.layers.MaxPooling2D(pool_size=(2,2)),

                                    keras.layers.Dropout(0.5),                                                                        
                                    keras.layers.Flatten(), # neural network beulding
                                    keras.layers.Dense(units=128, activation='relu'), # input layers
                                    keras.layers.Dropout(0.1),                                    
                                    keras.layers.Dense(units=256, activation='relu'),                                    
                                    keras.layers.Dropout(0.25),                                    
                                    keras.layers.Dense(units=4, activation='softmax') # output layer
])


# compile cnn model
cnn_model.compile(optimizer = Adam(lr=0.0001), loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# train cnn model
history = cnn_model.fit(training_data, 
                          epochs=500, 
                          verbose=1, 
                          validation_data= valid_data,
                          callbacks=callbacks_list) # time start 16.06

# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

history.history

Deploy 🌿Cotton Plant Disease Prediction & Get Cure AI App on Local System

Open Spyder and create a new project then create folders and files according to below hierarchy of the project.

app.py

#Import necessary libraries
from flask import Flask, render_template, request

import numpy as np
import os

from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.models import load_model

#load model
model =load_model("model/v3_pred_cott_dis.h5")

print('@@ Model loaded')


def pred_cot_dieas(cott_plant):
  test_image = load_img(cott_plant, target_size = (150, 150)) # load image 
  print("@@ Got Image for prediction")
  
  test_image = img_to_array(test_image)/255 # convert image to np array and normalize
  test_image = np.expand_dims(test_image, axis = 0) # change dimention 3D to 4D
  
  result = model.predict(test_image).round(3) # predict diseased palnt or not
  print('@@ Raw result = ', result)
  
  pred = np.argmax(result) # get the index of max value

  if pred == 0:
    return "Healthy Cotton Plant", 'healthy_plant_leaf.html' # if index 0 burned leaf
  elif pred == 1:
      return 'Diseased Cotton Plant', 'disease_plant.html' # # if index 1
  elif pred == 2:
      return 'Healthy Cotton Plant', 'healthy_plant.html'  # if index 2  fresh leaf
  else:
    return "Healthy Cotton Plant", 'healthy_plant.html' # if index 3

#------------>>pred_cot_dieas<<--end
    

# Create flask instance
app = Flask(__name__)

# render index.html page
@app.route("/", methods=['GET', 'POST'])
def home():
        return render_template('index.html')
    
 
# get input image from client then predict class and render respective .html page for solution
@app.route("/predict", methods = ['GET','POST'])
def predict():
     if request.method == 'POST':
        file = request.files['image'] # fet input
        filename = file.filename        
        print("@@ Input posted = ", filename)
        
        file_path = os.path.join('static/user uploaded', filename)
        file.save(file_path)

        print("@@ Predicting class......")
        pred, output_page = pred_cot_dieas(cott_plant=file_path)
              
        return render_template(output_page, pred_output = pred, user_image = file_path)
    
# For local system & cloud
if __name__ == "__main__":
    app.run(threaded=False) 

index.html

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
        integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css2?family=Rowdies:wght@700&display=swap" rel="stylesheet">

    <title>COTTON PLANT DISEASE PREDICTION</title>

    <style>
        * {
            margin: 0px;
            padding: 0px;
            box-sizing: border-box;

        }

        .carousel-inner img {
            height: 70vh;
        }

        form {
            display: flex;
            height: 85vh;
            justify-content: center;
            align-items: center;
            margin-top: 50px;
            width: 60%;
            text-align: center;
            margin: auto;
        }

        .details h2 {
            
            position: relative;
            top: 100px;
            margin: auto;
            color: rgb(18, 231, 231);
            font-size: 3rem;
        }

        label:hover {
            transform: scale(1.03);
        }

        .details h2 {
            /* margin-bottom: 300px; */
            position: relative;
            top: 100px;
            margin: auto;
            color: rgb(18, 231, 231);
            font-size: 3rem;

        }

        .gallery-h1 h1 {

            background-color: rgb(44, 43, 43);
            color: white;
            padding: 20px;
            border-radius: 15px;

        }

        .details h1 {
            color: white;
            padding: 20px;
            border-radius: 15px;
            background-color: rgb(45, 47, 49);
        }

        .upload {

            font-size: 20px;
            background-color: rgb(255, 252, 252);
            border-radius: 20px;
            outline: none;
            width: 315px;
            color: rgb(0, 0, 0);
            border: 3px solid rgb(45, 47, 49);

        }

        ::-webkit-file-upload-button {
            color: white;
            padding: 20px;
            border: 2px solid rgb(129, 129, 129);
            background-color: rgb(129, 129, 129);
            border-radius: 15px;

        }

        ::-webkit-file-upload-button:hover {
            border-radius: 20px;
            border: 2px solid rgb(177, 174, 174);

        }

        input[type="submit"] {
            position: absolute;
            margin-top: 150px;
            padding: 15px 35px;
            background-color: white;
            border-radius: 15px;
            color: black;
            font-size: 1.5rem;
            border: 4px solid rgb(31, 185, 190);
        }

        .carousel-caption {
            background: rgba(24, 25, 26, 0.5);
            border-radius: 10px;
        }

        .carousel-caption h3 {


            font-family: 'Rowdies', cursive;
            color: yellow;
            text-transform: uppercase;
            margin-bottom: 10px;

        }

        .carousel-caption p {
            padding: 7px;

        }

        .img-thumbnail {
            height: 300px;
        }

        .Content-h5 {

            padding: 15px;
            background-color: rgb(153, 156, 150);
            color: white;
            border-radius: 15px;
            margin-bottom: 25px;
        }

        @media only screen and (max-width: 325px) {
            body {
                font-size: x-small;
            }
        }
    </style>


</head>

<body>

    <header>
        <div class="container-fluid">
            <div id="myCarousel" class="carousel slide" data-ride="carousel">
                <ol class="carousel-indicators">
                    <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
                    <li data-target="#myCarousel" data-slide-to="1" class=""></li>
                    <li data-target="#myCarousel" data-slide-to="2" class=""></li>
                </ol>
                <div class="carousel-inner">
                    <div class="carousel-item active ">
                        <img src="/static/images/img1.jpg" class="d-block w-100" alt="...">

                        <div class="container">
                            <div class="container background-img3">
                                <div class="carousel-caption">

                                    <h3>Cotton
                                        Plant Disease Prediction AI App</h3>
                                    <p>
                                        Many veterans said that Deep Learning and AI is a threat to our world, but if we
                                        use it properly, we can do many good things today, we will see a small example
                                        of this in which we will be in cotton farming
                                        Find out about the disease
                                    </p>

                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="carousel-item">
                        <img src="/static/images/img2.jpg" class="d-block w-100" alt="...">
                        <div class="container">
                            <div class="carousel-caption">
                                <h3>कपास पेड़ का रोग का अंदाज और उपाय 
                                </h3>
                                <p>
                                    कई दिग्गजों ने कहा कि Deep Learning and AI यह हमारी दुनिया के लिए खतरा है लेकिन अगर
                                    हम इसका सही यूज़ करें तो हम कई अच्छे काम भी कर सकते हैं आज इसी का छोटा सा example
                                    देखेंगे जिसमें हम कपास की खेती में होने वाले
                                    रोग के बारे मे पता करेगें</p>

                            </div>
                        </div>
                    </div>


                    <div class="carousel-item">
                        <img src="/static/images/img3.jpg" class="d-block w-100" alt="...">
                        <div class="container">
                            <div class="container ">
                                <div class="carousel-caption">
                                    <h3>
                                        कपाशीच्या झाडाच्या रोगाचा अंदाज आणि उपाय </h3>
                                    <p>गेल्या काही वर्षांपासून
								 सखोल अभ्यास (Deep Learning) आणि कृत्रिम बुद्धिमत्ता (Artificial Intelligence) हा सर्वात चर्चेचा विषय राहिला आहे, 
								बरेच दिग्गज लोक म्हणतात की हा आपल्या जगासाठी धोका आहे, परंतु जर आपण त्याचा योग्य वापर केला तर आपण आज बर्‍याच चांगल्या गोष्टी करू शकतो. 
								त्याचेच एक उदाहरण हे  की  आपण कापसाचे रोग जाणून त्यावर त्यावर उपाय काढतो.
                                    </p>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <a class="carousel-control-prev" href="#myCarousel" role="button" data-slide="prev">
                    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                    <span class="sr-only">Previous</span>
                </a>
                <a class="carousel-control-next" href="#myCarousel" role="button" data-slide="next">
                    <span class="carousel-control-next-icon" aria-hidden="true"></span>
                    <span class="sr-only">Next</span>
                </a>
            </div>
        </div>
    </header>

    <section>

        <div class="container-fluid details">
            <h1 class="text-center mt-5 ">Predict Cotton Crop Disease & Get Cure</h1>

            <h2 class="text-center mt-4 mb-4" style="font-size: 2rem;">कपास के पेड कि तस्वीर डालिये</h2>
            <form action="/predict" method="post" enctype="multipart/form-data" onsubmit="showloading()">

                <input type="file" name="image" class="upload">
                <input type="submit" value="Predict">

            </form>
        </div>
    </section>

    <section style="margin-bottom: 100px;">

        <div class="container gallery-h1">

            <h1 class="text-center mt-4 mb-4">Photo Gallery</h1>

            <hr class="mt-2 mb-5">

            <div class="row text-center text-lg-left">

                <div class="col-lg-4 col-md-4 col-6 col-12">
                    <a href="#" class="d-block mb-4 h-100">
                        <img class="img-fluid img-thumbnail" src="/static/images/Gallery1.jpg" alt="">
                    </a>
                </div>
                <div class="col-lg-4 col-md-4 col-6 col-12">
                    <a href="#" class="d-block mb-4 h-100">
                        <img class="img-fluid img-thumbnail" src="/static/images/Gallery2.jpg" alt="">
                    </a>
                </div>

                <div class="col-lg-4 col-md-4 col-6 col-12">
                    <a href="#" class="d-block mb-4 h-100">
                        <img class="img-fluid img-thumbnail" src="/static/images/Gallery3.jpg" alt="">
                    </a>
                </div>
                <div class="col-lg-4 col-md-4 col-6 col-12">
                    <a href="#" class="d-block mb-4 h-100">
                        <img class="img-fluid img-thumbnail" src="/static/images/Gallery4.jpg" alt="">
                    </a>
                </div>
                <div class="col-lg-4 col-md-4 col-6 col-12">
                    <a href="#" class="d-block mb-4 h-100">
                        <img class="img-fluid img-thumbnail" src="/static/images/Gallery5.jpg" alt="">
                    </a>
                </div>
                <div class="col-lg-4 col-md-4 col-6 col-12">
                    <a href="#" class="d-block mb-4 h-100">
                        <img class="img-fluid img-thumbnail" src="/static/images/Gallery6.jpg" alt="">
                    </a>
                </div>

            </div>

        </div>

    </section>


    <section>
        <div class="container Content-h5">

            <h5 style="font-size: 1rem;" class="text-center my-3 contents">
                Delivery Contact:
                [email protected]</h5>

        </div>
    </section>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
        integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
        integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
        crossorigin="anonymous"></script>

</body>

</html>

healthy_plant.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css"
        integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">

    <title>COTTON PLANT DISEASE PREDICTION</title>

    <style>
        * {
            margin: 0px;
            padding: 0px;
            box-sizing: border-box;
        }

        .border img {
            border-radius: 15px;
            border: 2px solid black;
        }
    </style>
</head>

<body>

    <div>
        <img src="/static/images/cotton palnt banner.png" class="w3-border w3-padding" alt="Indian AI Production"
            style="width:100%">
    </div>

    <div class="container my-2">
        <div class="row mb-5">

            <div class="col-sm" style="margin-bottom: 23px;">
                <span class="border border-primary">
                    <img src="{{ user_image }}" alt="User Image" class="img-thumbnail">
                    
                </span>
            </div>

            <div class="col-sm">

                <div>
                    <h1 style="padding: 15px; background-color: rgb(153, 156, 150); color: white;"
                        class="text-center mb-5 content-h1 rounded">
                        {{pred_output}} </h1>
                </div>
                <div class="details">

                    <h5>

                        There is no disease on the cotton Plant.</br></br>
                        कपास के पेड़ पर कोई बीमारी नहीं है। </br></br>
                        कपाशीच्या झाडावर कोणताही रोग नाही आहे. </br></br>
                        કપાસના ઝાડ ઉપર કોઈ રોગ નથી.</br></br>
                        ಹತ್ತಿ ಮರದ ಮೇಲೆ ಯಾವುದೇ ರೋಗವಿಲ್ಲ..</br></br>
                        పత్తి చెట్టుపై వ్యాధి లేదు..</br></br>
                    </h5>
                </div>
            </div>
        </div>

    </div>
</body>

</html>

healthy_plant_leaf.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css"
        integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">

    <title>COTTON PLANT DISEASE PREDICTION</title>

    <style>
        * {
            margin: 0px;
            padding: 0px;
            box-sizing: border-box;
        }

        .border img {
            border-radius: 15px;
            border: 2px solid black;
        }
    </style>
</head>

<body>

    <div>
        <img src="/static/images/cotton palnt banner.png" class="w3-border w3-padding" alt="Indian AI Production"
            style="width:100%">
    </div>

    <div class="container my-2">
        <div class="row mb-5">

            <div class="col-sm" style="margin-bottom: 23px;">
                <span class="border border-primary">
                    <img src="{{ user_image }}" alt="User Image" class="img-thumbnail">
                    
                </span>
            </div>

            <div class="col-sm">

                <div>
                    <h1 style="padding: 15px; background-color: rgb(153, 156, 150); color: white;"
                        class="text-center mb-5 content-h1 rounded">
                        {{pred_output}} </h1>
                </div>
                <div class="details">

                    <h6>

                        <b>There is no disease on the cotton plant.</b></br>
                        Although the chemical fertilizer has fallen on the leaves of the tree, the leaves are burnt, but
                        there is no need to worry.</br></br>
                        <b>कपास के पेड़ पर कोई बीमारी नहीं है। </b></br>
                        रासायनिक उर्वरक पेड़ की पत्तियों पर गिर गया है, पत्तियां जल गई हैं, लेकिन चिंता करने की कोई
                        जरूरत नहीं है।</br></br>
                        <b>कपाशीच्या झाडावर कोणताही रोग नाही आहे. </b></br>
                        रासायनिक खत झाडाच्या पानावर पडल्यामुळे पान जळल आहे, तरी काही चिंता करायची गरज नाही. <b>मजूरांना
                            कंबर बागवून खत टाकायला सांगा. </b></br></br>
                        <b>કપાસના ઝાડ ઉપર કોઈ રોગ નથી.</b></br></br>
                        <b>ಹತ್ತಿ ಮರದ ಮೇಲೆ ಯಾವುದೇ ರೋಗವಿಲ್ಲ..</b></br></br>
                        <b>పత్తి చెట్టుపై వ్యాధి లేదు..</b></br></br>

                    </h6>
                </div>
            </div>
        </div>
    </div>
</body>

</html>

disease_plant.html

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css"
        integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">

    <title>COTTON PLANT DISEASE PREDICTION</title>

    <style>
        * {
            margin: 0px;
            padding: 0px;
            box-sizing: border-box;
        }

        .card-style {
            background-color: #dcdcdc;

        }

        .content {
            padding: 15px;
            color: white;
            background-color: rgb(153, 156, 150);
            /* font-size: 1rem; */
        }

        @media (max-width: 430px) and (min-width: 200px) {

            .contents {
                font-size: 0.6rem;
                color: chartreuse;
            }

            .content-h1 {

                font-size: 1rem;
            }
        }

        .border img {
            border-radius: 15px;
            border: 2px solid black;
        }
    </style>
</head>

<body>

    <div>
        <img src="/static/images/cotton palnt banner.png" class="w3-border w3-padding" alt="Indian AI Production"
            style="width:100%">
    </div>

    <div class="container my-2">
        <div class="row mb-5">

            <div class="col-sm" style="margin-bottom: 23px;">
                <span class="border border-primary">
                    <img src="{{ user_image }}" alt="User Image" class="img-thumbnail">
                    <!-- <img src="{{pred_output}}" alt="User Image" class="img-thumbnail"> -->

                </span>
            </div>

            <div class="col-sm">

                <div>
                    <h1 style="padding: 15px; background-color: rgb(153, 156, 150); color: white;"
                        class="text-center mb-5 content-h1 rounded">
                        {{pred_output}} </h1>
                </div>

                <h2>Disease Name / रोग का नाम / रोगाचे नाव / રોગ નામ / ರೋಗದ ಹೆಸರು / వ్యాధి పేరు : </span></h2>
                <h3 style="line-height: 100%;">Attack of Leaf Sucking and Chewing Pests <br> चुरडा,मावा रोग <br> લીફ
                    ચૂસીને જીવાતો જીવાતોનો હુમલો <br> ಎಲೆ
                    ಹೀರುವ
                    ಮತ್ತು ಚೂಯಿಂಗ್ ಕೀಟಗಳ ದಾಳಿ <br> ఆకు పీల్చటం మరియు చూయింగ్ తెగుళ్ళ దాడి</h3>
                <hr class="w-100 mx-auto ">
            </div>
        </div>

        <h1> Solution for Disease / रोग का उपचार / रोगाचा उपाय / રોગનો ઉપાય / ರೋಗಕ್ಕೆ ಪರಿಹಾರ / వ్యాధికి పరిష్కారం: </h1>
        <p><strong>Use any one Systemic Insecticide, which contain<i> Flonicamid 50%/ Thiamethoxam 25% WG / Imidacloprid
                    17.8 Sl / Acetamiprid 20% SP.</i></strong></p>
        <p></p>
        <p>किसी भी एक प्रणालीगत कीटनाशक का प्रयोग करें, जिसमें फ्लोनिकमिड ५०% / थियामेथोक्साम 25% WG / इमिडाक्लोप्रिड
            १७.८
            एसएल / एसिटामिप्रिड २०% एसपी है।</p>
        <p>कोणत्याही एक सिस्टीमिक कीटकनाशकाचा वापर करा, ज्यात फ्लोनीकायमिड ५०% / थियॅमेथॉक्सम 25% WG / इमिडाक्लोप्रिड
            १७.८
            एसएल / एसीटामिप्रिड २०% एसपी असेल.</p>
        <p>કોઈપણ એક પ્રણાલીગત જંતુનાશક દવાઓનો ઉપયોગ કરો, જેમાં ફ્લોનીકેમિડ 50% / થાઇઆમેથોક્સમ 25% WG / ઇમિડાકલોપ્રિડ
            17.8
            એસએલ / એસેટામિપ્રિડ 20% એસપી હોય છે.</p>
        <p>ಫ್ಲೋನಿಕಾಮಿಡ್ 50% / ಥಿಯಾಮೆಥೊಕ್ಸಮ್ 25% WG / ಇಮಿಡಾಕ್ಲೋಪ್ರಿಡ್ 17.8 ಎಸ್ಎಲ್ / ಅಸೆಟಾಮಿಪ್ರಿಡ್ 20% ಎಸ್ಪಿ ಹೊಂದಿರುವ
            ಯಾವುದೇ
            ಒಂದು ವ್ಯವಸ್ಥಿತ ಕೀಟನಾಶಕವನ್ನು ಬಳಸಿ.</p>
        <p>ఫ్లోనికామిడ్ 50% / థియామెథోక్సామ్ 25% WG / ఇమిడాక్లోప్రిడ్ 17.8 స్లా / ఎసిటామిప్రిడ్ 20% ఎస్పిని కలిగి ఉన్న
            ఏదైనా
            ఒక దైహిక పురుగుమందును వాడండి.</p>
    </div>

    <section>

        <div class="container">
            <h1 style="padding: 15px; background-color: rgb(153, 156, 150); color: white;"
                class="text-center my-3 content-h1">
                Recommended Products</h1>
        </div>

        <div class="container">

            <div class="card-columns">
                <div class="card ">
                    <div class="card-body text-center card-style">
                        <img style="border-radius: 10px;" class="img-fluid" src="/static/images/preet.png" alt="">
                        <h3 class="card-text">Dose: 60-80 gm/Acre</h3>
                    </div>
                </div>
                <div class="card">
                    <div class="card-body text-center card-style">
                        <img style="border-radius: 10px;" class="img-fluid" src="/static/images/ulala.png" alt="">
                        <h3 class="card-text">Dose: 25-40 gm/Acre</h3>
                    </div>
                </div>
                <div class="card ">
                    <div class="card-body text-center card-style">
                        <img style="border-radius: 10px" class="img-fluid" src="/static/images/victor.png" alt="">
                        <h3 class="card-text">Dose: 60-80 gm/Acre</h3>
                    </div>
                </div>
                <div class="card ">
                    <div class="card-body text-center card-style">
                        <img style="border-radius: 10px;" class="img-fluid" src="/static/images/confidor.png" alt="">
                        <h3 class="card-text">Dose: 25-35 ml/Acre</h3>
                    </div>
                </div>
                <div class="card ">
                    <div class="card-body text-center card-style">
                        <img style="border-radius: 10px;" class="img-fluid" src="/static/images/panama.png" alt="">
                        <h3 class="card-text">Dose: 60-80 gm/Acre</h3>
                    </div>
                </div>
                <div class="card ">
                    <div class="card-body text-center card-style">
                        <img style="border-radius: 10px;" class="img-fluid" src="/static/images/actara.png" alt="">
                        <h3 class="card-text">Dose: 60-80 gm/Acre</h3>
                    </div>
                </div>

            </div>

            <!-- <div class="container-fluid contents"> -->
            <h5 style="padding: 15px; background-color: rgb(153, 156, 150); color: white;"
                class="text-center my-3 contents">
                Delivery Contact:
                [email protected]</h5>
            <!-- </div> -->
        </div>

    </section>

</body>

</html>

How to use App?

Just run ‘aap.py’ file in spyder or you can run it using anaconda prompt. Then you will get localhost address like ‘http://127.0.0.1:5000/‘ enter it in any browser in your system then enjoy it.

Share your feedback then I will teach you how I have deployed this project on the AWS cloud free of cost.

How to download the project and use it?

Click on the below button and download the project and just open it in Spyder and run ‘aap.py’ file and enjoy it.

Note:

You don’t have the right to use the below data for commercial purposes without our permission and attribute of ‘Indian AI Production’.

Below data share only for study purposes in the local system not for public distribution. (More contact use)

Note:

  1. I just implement my idea and create an APP skeleton, so you will maybe get an error so please share it by comment.
  2. I am trying to use more disease plant data, but waiting for insect attack on my farm crop.
  3. I have used company name in web banner, it does not exist just use for demonstration purposes.

Thanks for reading…..-:)

The post 🌿Cotton Plant Disease Prediction & Get Cure App using Artificial Intelligence appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/cotton-plant-disease-prediction-get-cure-app-using-artificial-intelligence/feed/ 17 1613
Horse or Human Prediction using Convolutional Neural Network https://indianaiproduction.com/horse-or-human-prediction-using-cnn/ https://indianaiproduction.com/horse-or-human-prediction-using-cnn/#comments Thu, 23 Jul 2020 12:29:15 +0000 https://indianaiproduction.com/?p=1566 In the Machine Learning/Data Science/Deep Learning / Computer Vison End to End Project in Python Tutorial in Hindi, we explained each and every step of Machine Learning Project / Data Science Project / Deep Learning Project in detail. Project name: Horse or Human Prediction using Convolutional Neural Network What we cover in this Project: What …

Horse or Human Prediction using Convolutional Neural Network Read More »

The post Horse or Human Prediction using Convolutional Neural Network appeared first on Indian AI Production.

]]>
In the Machine Learning/Data Science/Deep Learning / Computer Vison End to End Project in Python Tutorial in Hindi, we explained each and every step of Machine Learning Project / Data Science Project / Deep Learning Project in detail.

horse-or-human-prediction-deep-learning-machine-learning-project

Project name: Horse or Human Prediction using Convolutional Neural Network

What we cover in this Project:

  1. What is Convolutional Neural Network?
  2. What is Google Colab?
  3. Import Libraries
  4. Load Data
  5. Show Image from Numbers
  6. Change Dimension / Feature Scaling
  7. Build First Convolutional Neural Network
  8. Train Model
  9. Test & Evaluate Model
  10. Confusion Matrix
  11. Classification Report
  12. Save Mode
  13. Build 2 Complex CNN

Software For This Project

  • TensorFlow
  • Keras
  • NumPy
  • Flask
  • Pillow
  • Matplotlib

Build, Train and Visualize CNN Model

# -*- coding: utf-8 -*-
"""human_or_horse_prediction.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1zTI5Ete5C1QdVvMx5IAquUoXgZhHVf5a

# Project: Horse or Human Classification using CNN
We have data for training:

500 horse images
527 human(male & female) images

For validation:

122 horse images
123 human(male & female) images

## Problem Statement:

Classifie given image is horse or human(male/female)

### Solution:

To solve this problem we are going to use Deep Learning Algorithm that is CNN (Convolutional Neural Network)

## Dara Scource

Raw Data Scource: https://www.kaggle.com/sanikamal/horses-or-humans-dataset

## Load Libraries
"""

import matplotlib.pyplot as plt

import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
##
from keras.layers.normalization import BatchNormalization
from keras.regularizers import l2

keras.__version__

"""## Load Data"""

train_data_path = "/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/train"
validation_data_path = "/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/validation"

"""# Data Preprocessing"""

training_datagen = ImageDataGenerator(rescale=1./255,
                                      rotation_range=40,
                                      width_shift_range=0.2,
                                      height_shift_range=0.2,
                                      shear_range=0.2,
                                      zoom_range=0.2,
                                      horizontal_flip=True,
                                      fill_mode='nearest')

training_data =  training_datagen.flow_from_directory(train_data_path, 
                                      target_size=(150, 150), 
                                      batch_size=32,
                                      class_mode='binary')

training_data.class_indices

valid_datagen = ImageDataGenerator(rescale=1./255)

valid_data =  valid_datagen.flow_from_directory(validation_data_path, 
                                      target_size=(150, 150), 
                                      batch_size=32,
                                      class_mode='binary')

def plotImages(images_arr):
    fig, axes = plt.subplots(1, 5, figsize=(20, 20))
    axes = axes.flatten()
    for img, ax in zip(images_arr, axes):
        ax.imshow(img)
    plt.tight_layout()
    plt.show()

images = [training_data[0][0][0] for i in range(5)]
plotImages(images)

"""#Building cnn model"""

#Building cnn model
cnn_model = keras.models.Sequential([
                                    keras.layers.Conv2D(filters=32, kernel_size=7, input_shape=[150, 150, 3],kernel_regularizer=l2(l=0.01)),
                                    BatchNormalization(),
                                    keras.layers.MaxPooling2D(pool_size=(2,2)),
                                     
                                    keras.layers.Conv2D(filters=64, kernel_size=5),
                                    BatchNormalization(),
                                    keras.layers.MaxPooling2D(pool_size=(2,2)),
                                     
                                    keras.layers.Conv2D(filters=128, kernel_size=3),
                                    BatchNormalization(),
                                    keras.layers.MaxPooling2D(pool_size=(2,2)),
                                                                         
                                    keras.layers.Conv2D(filters=256, kernel_size=3),
                                    BatchNormalization(),
                                    keras.layers.MaxPooling2D(pool_size=(2,2)),
                                                                     
                                    keras.layers.Flatten(), # neural network beulding
                                    keras.layers.Dense(units=128, activation='relu'), # input layers
                                    BatchNormalization(),
                                    keras.layers.Dropout(0.5),                                      
                                    keras.layers.Dense(units=256, activation='relu'),  
                                    BatchNormalization(),                                  
                                    keras.layers.Dropout(0.5),                                    
                                    keras.layers.Dense(units=2, activation='softmax') # output layer
])

# compile cnn model
cnn_model.compile(optimizer = Adam(lr=0.0001), loss='sparse_categorical_crossentropy', metrics=['accuracy'])

model_path = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/horse_or_human_predictor.h5'
checkpoint = ModelCheckpoint(model_path, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')
callbacks_list = [checkpoint]

# train cnn model
history = cnn_model.fit(training_data, 
                          epochs=100, 
                          verbose=1, 
                          validation_data= valid_data,
                          callbacks=callbacks_list)

# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

Predict Horse or Human

"""
# Predict Horse or Human

Here we are loading train CNN model to predict Given input (image) is Horse of Human

# Import Libraries
"""

# Load Liraries
import numpy as np

import keras 
from keras.preprocessing.image import ImageDataGenerator

"""# Import Model"""

model_path1 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/horse_human_cnn_model_new.h5' #new model.ipynb
model_path2 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/horse_human_cnn_model_v2.h5' #v2 solve overfitting Horse_or_human Classification using CNN.ipynb
model_path3 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/horse_human_cnn_model_v2_1.h5' #v2 solve overfitting Horse_or_human Classification using CNN.ipynb

model1 = keras.models.load_model(model_path1)
model2 = keras.models.load_model(model_path2)
model3 = keras.models.load_model(model_path3)

"""#Preprocessing"""

#horse image path
h1 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/test_data/horse_test/horse1-204.png'
h2 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/test_data/horse_test/horse2-069.png'
h3 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/test_data/horse_test/horse3-070.png'
h4 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/test_data/horse_test/horse4-439.png'
h5 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/test_data/horse_test/horse5-203.png'
h6 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/test_data/horse_test/horse6-161.png'
h7 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/validation/horses/horse2-224.png'
h8 ="/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/validation/horses/horse5-123.png"

#human image path
hu1 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/test_data/human_test/valhuman01-09.png'
hu2 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/test_data/human_test/valhuman02-18.png'
hu3 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/test_data/human_test/valhuman03-23.png'
hu4 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/test_data/human_test/valhuman04-24.png'
hu5 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/test_data/human_test/valhuman05-19.png'
hu6 = '/content/drive/My Drive/My ML Project /DL Project/CNN/horse-or-human/dataset/validation/humans/valhuman01-13.png'

import numpy as np
from keras.preprocessing import image

def pred_human_horse(model, horse_or_human):
  test_image = image.load_img(horse_or_human, target_size = (150, 150))
  test_image = image.img_to_array(test_image)/255
  test_image = np.expand_dims(test_image, axis = 0)

  result = model.predict(test_image).round(3)

  pred = np.argmax(result)
  print(result, "--->>>", pred)

  if pred == 0:
    print('Predicted>>> Horse')
  else:
    print('Predicted>>> Human')

"""## Predict Output"""

for horse_or_human in [h1,h2,h3,h4,h5,h6,h7,h8, hu1,hu2,hu3,hu4,hu5,hu6]:
  pred_human_horse(model1, horse_or_human)

for horse_or_human in [h1,h2,h3,h4,h5,h6,h7,h8, hu1,hu2,hu3,hu4,hu5,hu6]:
  pred_human_horse(model2, horse_or_human)

for horse_or_human in [h1,h2,h3,h4,h5,h6,h7,h8, hu1,hu2,hu3,hu4,hu5,hu6]:
  pred_human_horse(model3, horse_or_human)


Model Deployment Code on AWS

app.py

#Import necessary libraries
from flask import Flask, render_template, request

import numpy as np
import os

from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.models import load_model

#load model
model =load_model("horse_human_cnn_model_v2_1.h5")

print('@@ Model loaded')


def pred_human_horse(horse_or_human):
  test_image = load_img(horse_or_human, target_size = (150, 150)) # load image 
  print("@@ Got Image for prediction")
  
  test_image = img_to_array(test_image)/255 # convert image to np array and normalize
  test_image = np.expand_dims(test_image, axis = 0) # change dimention 3D to 4D
  
  result = model.predict(test_image).round(3) # predict class horse or human
  print('@@ Raw result = ', result)
  
  pred = np.argmax(result) # get the index of max value

  if pred == 0:
    return "Horse" # if index 0 
  else:
    return "Human" # if index 1

#------------>>pred_human_horse<<--end
    

# Create flask instance
app = Flask(__name__)

# render index.html page
@app.route("/", methods=['GET', 'POST'])
def home():
        return render_template('index.html')
    
  
@app.route("/predict", methods = ['GET','POST'])
def predict():
     if request.method == 'POST':
        file = request.files['image'] # fet input
        filename = file.filename        
        print("@@ Input posted = ", filename)
        
        file_path = os.path.join('static/user uploaded', filename)
        file.save(file_path)

        print("@@ Predicting class......")
        pred = pred_human_horse(horse_or_human=file_path)
              
        return render_template('predict.html', pred_output = pred, user_image = file_path)
    
#Fo local system
if __name__ == "__main__":
    app.run(threaded=False,) 
    
# #Fo AWS cloud
# if __name__ == "__main__":
#     app.run(host='0.0.0.0.0', post='8080',threaded=False,) 
    

Frontend Code (HTML) Files

index.html

<html>
<head>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
     
    <title>Predict Human or Horse ML App</title>
</head>
<body>

  <!-- Show  Banner-->
  <div>
    <img src="static/images/horse or human banner.png" class="w3-border w3-padding" alt="Indian AI Production" style="width:100%">
  </div>

    <form action="/predict" method="post" enctype="multipart/form-data" style="margin-top: 50px; width: 60%; text-align: center; margin: auto;" onsubmit="showloading()">
        <span class="text-left btn btn-default btn-file">
            Upload Image <input type="file" name="image">
        </span>   
    
        <span class="text-right">
          <input type="submit" value="Predict" class="btn btn-primary">
        </span>
      </form>

</body>
</html>

predict.html

<html>
<head>

  <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    
    <title>Predict Human or Horse ML App</title>
</head>
<body>

  <!-- Show  Banner-->
  <div>
    <img src="static/images/horse or human banner.png" class="w3-border w3-padding" alt="Indian AI Production" style="width:100%">
  </div>


  <div class="container">
  <div class="row">

    <div class="col-sm">
      <span class="border border-primary">
        <img src="{{ user_image }}" alt="User Image" class="img-thumbnail">
      </span>
    </div>

    <div class="col-sm">
      <h1>It's <span class="badge badge-secondary">{{pred_output}}</span></h1>
    </div>

  </div>
</div>

</body>
</html>

The post Horse or Human Prediction using Convolutional Neural Network appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/horse-or-human-prediction-using-cnn/feed/ 3 1566
First Convolutional Neural Network Project – Fashion MNIST Classification https://indianaiproduction.com/first-convolutional-neural-network-project-fashion-mnist-classification/ https://indianaiproduction.com/first-convolutional-neural-network-project-fashion-mnist-classification/#comments Fri, 03 Jul 2020 03:22:16 +0000 https://indianaiproduction.com/?p=1514 Course name: “Machine Learning & Data Science – Beginner to Professional Hands-on Python Course in Hindi” In the Machine Learning/Data Science/Deep Learning End to End Project in Python Tutorial in Hindi, we explained each and every step of Machine Learning Project / Data Science Project / Deep Learning Project in detail. Project name: Fashion MNIST …

First Convolutional Neural Network Project – Fashion MNIST Classification Read More »

The post First Convolutional Neural Network Project – Fashion MNIST Classification appeared first on Indian AI Production.

]]>

Course name: “Machine Learning & Data Science – Beginner to Professional Hands-on Python Course in Hindi”

In the Machine Learning/Data Science/Deep Learning End to End Project in Python Tutorial in Hindi, we explained each and every step of Machine Learning Project / Data Science Project / Deep Learning Project in detail.

Project name: Fashion MNIST Classification using Convolutional Neural Network

What we cover in this Project:

  1. What is Convolutional Neural Network?
  2. What is Google Colab?
  3. Import Libraries
  4. Load Data
  5. Show Image from Numbers
  6. Change Dimension / Feature Scaling
  7. Build First Convolutional Neural Network
  8. Train Model
  9. Test & Evaluate Model
  10. Confusion Matrix
  11. Classification Report
  12. Save Mode
  13. Build 2 Complex CNN

1. What is Convolutional Neural Network?

Image Kernels >>> https://setosa.io/ev/image-kernels/

Hand written App >>> https://www.cs.ryerson.ca/~aharley/vis/conv/

2. What is Google Colab?

Google Colab >>> Click Here

3. Data Preprocessing

  1. Import Libraries
  2. Load Data
  3. Show Image from Numbers
  4. Change Dimension / Feature Scaling
# -*- coding: utf-8 -*-
"""CNN Project - Fashion-MNIST .ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1KrIrPLKKRwYobmqpacbf9eiQp5UC9Hhu

# Building CNN - Convolutional Neural Network

###Project Fashion-Classification - End to End 

Train Convolutional Neural Network on 60,000 Fashion-MNIST Images (data in NP array)

Test Convolutional Neural Network on 10,000 Fashion-MNIST Images (data in NP array)

## Import Libraries
"""

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

import keras # to build Neural Network

"""## Load Data"""

(X_train, y_train), (X_test, y_test) = keras.datasets.fashion_mnist.load_data() # load dataset from  keras

# Print shape of Data

X_train.shape, y_train.shape, "******", X_test.shape, y_test.shape

X_train[0] # image data in 2d numpy array shape 28x28 pixel

y_train[0] #9 => Ankle boot

class_labels = ["T-shirt/top","Trouser","Pullover","Dress","Coat","Sandal","Shirt","Sneaker","Bag","Ankle boot"]
'''
0 => T-shirt/top 
1 => Trouser 
2 => Pullover 
3 => Dress 
4 => Coat 
5 => Sandal 
6 => Shirt 
7 => Sneaker 
8 => Bag 
9 => Ankle boot '''

"""## Show image"""

plt.imshow(X_train[0], cmap='Greys')

plt.figure(figsize=(16,16))

j=1
for i in np.random.randint(0, 1000, 25):
  plt.subplot(5,5,j); j+=1
  plt.imshow(X_train[i], cmap="Greys")
  plt.axis('off') # off the axis
  plt.title('{} / {}'.format(class_labels[y_train[i]], y_train[i]))

"""## Change Dimention"""

X_train.shape

X_train.ndim

# expected conv2d_input to have 4 dimensions, but got array with shape (28, 28, 1)
# so we have increase the dimention 3 to 4
X_train = np.expand_dims(X_train, -1)
X_test = np.expand_dims(X_test, -1)

# ref: https://numpy.org/doc/stable/reference/generated/numpy.expand_dims.html

X_train.ndim

"""## Feature Scaling"""

X_train = X_train/255
X_test = X_test/255

"""## Split Dataset"""

from sklearn.model_selection import train_test_split 
X_train, X_validation, y_train, y_validation = train_test_split(X_train, y_train, test_size= 0.2, random_state=2020)

X_train.shape,  y_train.shape, X_validation.shape, y_validation.shape

4. Build First Convolutional Neural Network

"""# Convolutional Neural Network - Model Building"""

#Building CNN model
cnn_model = keras.models.Sequential([
                         keras.layers.Conv2D(filters=32, kernel_size=3, strides=(1,1), padding='valid',activation= 'relu', input_shape=[28,28,1]),
                         keras.layers.MaxPooling2D(pool_size=(2,2)),
                         keras.layers.Flatten(),
                         keras.layers.Dense(units=128, activation='relu'),
                         keras.layers.Dense(units=10, activation='softmax')
])

cnn_model.summary() # get the summary of model

# complie the model
cnn_model.compile(optimizer='adam', loss= 'sparse_categorical_crossentropy', metrics=['accuracy'])

# train cnn model
cnn_model.fit(X_train, y_train, epochs=10, batch_size=512, verbose=1, validation_data=(X_validation, y_validation))

5. Test and Evaluate Model

  1. Test & Evaluate Model
  2. Confusion Matrix
  3. Classification Report
"""# Test the Model"""

y_pred = cnn_model.predict(X_test)
y_pred.round(2)

y_test

cnn_model.evaluate(X_test, y_test)

"""# Visualize output

plt.figure(figsize=(16,16))

j=1
for i in np.random.randint(0, 1000,25):
  plt.subplot(5,5, j); j+=1
  plt.imshow(X_test[i].reshape(28,28), cmap = 'Greys')
  plt.title('Actual = {} / {} \nPredicted = {} / {}'.format(class_labels[y_test[i]], y_test[i], class_labels[np.argmax(y_pred[i])],np.argmax(y_pred[i])))
  plt.axis('off')
"""

plt.figure(figsize=(16,30))

j=1
for i in np.random.randint(0, 1000,60):
  plt.subplot(10,6, j); j+=1
  plt.imshow(X_test[i].reshape(28,28), cmap = 'Greys')
  plt.title('Actual = {} / {} \nPredicted = {} / {}'.format(class_labels[y_test[i]], y_test[i], class_labels[np.argmax(y_pred[i])],np.argmax(y_pred[i])))
  plt.axis('off')

"""## Confusion Matrix"""

from sklearn.metrics import confusion_matrix

plt.figure(figsize=(16,9))
y_pred_labels = [ np.argmax(label) for label in y_pred ]
cm = confusion_matrix(y_test, y_pred_labels)

# show cm 
sns.heatmap(cm, annot=True, fmt='d',xticklabels=class_labels, yticklabels=class_labels)

from sklearn.metrics import classification_report
cr= classification_report(y_test, y_pred_labels, target_names=class_labels)
print(cr)

6. Save Model

"""# Save Model"""

cnn_model.save('fashion_mnist_cnn_model.h5') # Save model

# Load model
fashion_mnist_cnn_model = keras.models.load_model('fashion_mnist_cnn_model.h5')

Y_pred_sample = fashion_mnist_cnn_model.predict(np.expand_dims(X_test[0], axis=0)).round(2)
Y_pred_sample

np.argmax(Y_pred_sample[0])

y_test[0]

7. Build 2 Complex CNN

"""# Convolutional Neural Network - Building Complex Model"""

#Building CNN model
cnn_model2 = keras.models.Sequential([
                         keras.layers.Conv2D(filters=32, kernel_size=3, strides=(1,1), padding='valid',activation= 'relu', input_shape=[28,28,1]),
                         keras.layers.MaxPooling2D(pool_size=(2,2)),
                         keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2,2), padding='same', activation='relu'),
                         keras.layers.MaxPooling2D(pool_size=(2,2)),
                         keras.layers.Flatten(),
                         keras.layers.Dense(units=128, activation='relu'),
                         keras.layers.Dropout(0.25),
                         keras.layers.Dense(units=256, activation='relu'),
                         keras.layers.Dropout(0.25),
                         keras.layers.Dense(units=128, activation='relu'),
                         keras.layers.Dense(units=10, activation='softmax')
                         ])

# complie the model
cnn_model2.compile(optimizer='adam', loss= 'sparse_categorical_crossentropy', metrics=['accuracy'])

#Train the Model
cnn_model2.fit(X_train, y_train, epochs=20, batch_size=512, verbose=1, validation_data=(X_validation, y_validation))

cnn_model2.save('fashion_mnist_cnn_model2.h5')

"""######## very complex model"""

#Building CNN model
cnn_model3 = keras.models.Sequential([
                         keras.layers.Conv2D(filters=64, kernel_size=3, strides=(1,1), padding='valid',activation= 'relu', input_shape=[28,28,1]),
                         keras.layers.MaxPooling2D(pool_size=(2,2)),
                         keras.layers.Conv2D(filters=128, kernel_size=3, strides=(2,2), padding='same', activation='relu'),
                         keras.layers.MaxPooling2D(pool_size=(2,2)),
                         keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2,2), padding='same', activation='relu'),
                         keras.layers.MaxPooling2D(pool_size=(2,2)),
                         keras.layers.Flatten(),
                         keras.layers.Dense(units=128, activation='relu'),
                         keras.layers.Dropout(0.25),
                         keras.layers.Dense(units=256, activation='relu'),
                         keras.layers.Dropout(0.5),
                         keras.layers.Dense(units=256, activation='relu'),
                         keras.layers.Dropout(0.25),                        
                         keras.layers.Dense(units=128, activation='relu'),
                         keras.layers.Dropout(0.10),                         
                         keras.layers.Dense(units=10, activation='softmax')
                         ])

# complie the model
cnn_model3.compile(optimizer='adam', loss= 'sparse_categorical_crossentropy', metrics=['accuracy'])

#Train the Model
cnn_model3.fit(X_train, y_train, epochs=50, batch_size=512, verbose=1, validation_data=(X_validation, y_validation))

cnn_model3.save('fashion_mnist_cnn_model3.h5')

cnn_model3.evaluate(X_test, y_test)

#End

The post First Convolutional Neural Network Project – Fashion MNIST Classification appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/first-convolutional-neural-network-project-fashion-mnist-classification/feed/ 2 1514
First Deep Learning Project End to End | Fashion-MNIST Classification https://indianaiproduction.com/first-deep-learning-project-fashion-mnist-classification/ https://indianaiproduction.com/first-deep-learning-project-fashion-mnist-classification/#comments Tue, 30 Jun 2020 08:33:47 +0000 https://indianaiproduction.com/?p=1501 In the Machine Learning/Data Science/Deep Learning End to End Project in Python Tutorial in Hindi, we explained each and every step of Machine Learning Project / Data Science Project / Deep Learning Project in detail. Project name: Fashion MNIST Classification What we cover in this Project: Import Libraries Load Data Show Image from Numbers Feature …

First Deep Learning Project End to End | Fashion-MNIST Classification Read More »

The post First Deep Learning Project End to End | Fashion-MNIST Classification appeared first on Indian AI Production.

]]>
First Deep Learning Project End to End

In the Machine Learning/Data Science/Deep Learning End to End Project in Python Tutorial in Hindi, we explained each and every step of Machine Learning Project / Data Science Project / Deep Learning Project in detail.

Project name: Fashion MNIST Classification

What we cover in this Project:

  1. Import Libraries
  2. Load Data
  3. Show Image from Numbers
  4. Feature Scaling
  5. Build First Neural Network
  6. Train Model
  7. Test & Evaluate Model
  8. Confusion Matrix
  9. Classification Report
  10. Save Mode

Project Source Code

# -*- coding: utf-8 -*-
"""first deep learning project - MNIST-Fashion Classification.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1bCl8PUVo2XP8_-emIE3Zzi8jQ3Jsy2rH

# First Deep Learning Project
##Fashion Classification

### Train Neural Network on 60,000 Fashion-MNIST Images (data in NP array)
### Test Neural Network on 10,000 Fashion-MNIST Images (data in NP array)
"""

'''
class_labels:

0 => T-shirt/top 
1 => Trouser 
2 => Pullover 
3 => Dress 
4 => Coat 
5 => Sandal 
6 => Shirt 
7 => Sneaker 
8 => Bag 
9 => Ankle boot 

Classify the given input from above class using Neural Network

image shape 28 X 28 pixel ( Gray scale)

'''

"""### Import Libraries"""

import keras
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

"""## Load Data"""

(X_train, y_train), (X_test, y_test) = keras.datasets.fashion_mnist.load_data()

X_train.shape, y_train.shape

X_test.shape, y_test.shape

X_train[0]

y_train[0]

class_labels = ["T-shirt/top","Trouser","Pullover","Dress","Coat","Sandal","Shirt","Sneaker","Bag","Ankle boot"]
'''
0 => T-shirt/top 
1 => Trouser 
2 => Pullover 
3 => Dress 
4 => Coat 
5 => Sandal 
6 => Shirt 
7 => Sneaker 
8 => Bag 
9 => Ankle boot '''

plt.imshow(X_train[0], cmap ="Greys")

plt.figure(figsize=(16,16))
for i in range(25):
  plt.subplot(5,5,i+1)
  plt.imshow(X_train[i],cmap="Greys")
  plt.axis('off')
  plt.title(class_labels[y_train[i]]+"="+str(y_train[i]), fontsize=20)

  '''
0 => T-shirt/top 
1 => Trouser 
2 => Pullover 
3 => Dress 
4 => Coat 
5 => Sandal 
6 => Shirt 
7 => Sneaker 
8 => Bag 
9 => Ankle boot '''

"""# Feature Scalling"""

X_train = X_train/255
X_test = X_test/255

X_train[0]

"""## Build Neural Network"""

model = keras.models.Sequential([
                         keras.layers.Flatten(input_shape=[28,28]),
                         keras.layers.Dense(units=32, activation='relu'),
                         keras.layers.Dense(units=10, activation='softmax')
])

model.summary()

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

model.fit(X_train, y_train, epochs=1)

model.fit(X_train, y_train, epochs=10)

"""## Test and Evaluate Neural Network Model"""

model.evaluate(X_test,y_test)

y_pred = model.predict(X_test)

y_pred[0].round(2)

np.argmax(y_pred[0].round(2))

'''
0 => T-shirt/top 
1 => Trouser 
2 => Pullover 
3 => Dress 
4 => Coat 
5 => Sandal 
6 => Shirt 
7 => Sneaker 
8 => Bag 
9 => Ankle boot '''

y_test[0]

plt.figure(figsize=(16,16))
for i in range(25):
  plt.subplot(5,5,i+1)
  plt.imshow(X_test[i],cmap="Greys")
  plt.axis('off')
  plt.title("Actual= {} \n Predicted = {}".format(class_labels[y_test[i]], class_labels[np.argmax(y_pred[i])]))

"""## Confusion Matrix"""

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, [ np.argmax(i) for i in y_pred])

plt.figure(figsize=(16,9))
sns.heatmap(cm, annot=True, fmt = "d")

"""## Classification Report"""

from sklearn.metrics import classification_report
cr = classification_report(y_test, [ np.argmax(i) for i in y_pred], target_names = class_labels,)

print(cr)

"""## Save Model"""

model.save("MNIST_classifier_nn_model.h5")

model = keras.models.load_model("MNIST_classifier_nn_model.h5")

model.predict(X_test)

The post First Deep Learning Project End to End | Fashion-MNIST Classification appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/first-deep-learning-project-fashion-mnist-classification/feed/ 3 1501