Learn Python

Learn Data Structure & Algorithm

Learn Numpy

Learn Pandas

Learn Matplotlib

Learn Seaborn

Learn Statistics

Learn Math

Learn MATLAB

Learn Machine learning

Learn Github

Learn OpenCV

Introduction

Setup

ANN

Working process ANN

Propagation

Bias parameter

Activation function

Loss function

Overfitting and Underfitting

Optimization function

Chain rule

Minima

Gradient problem

Weight initialization

Dropout

ANN Regression Exercise

ANN Classification Exercise

Hyper parameter tuning

CNN

CNN basics

Convolution

Padding

Pooling

Data argumentation

Flattening

Create Custom Dataset

Binary Classification Exercise

Multiclass Classification Exercise

Transfer learning

Transfer model Basic template

RNN

How RNN works

LSTM

Bidirectional RNN

Sequence to sequence

Attention model

Transformer model

Bag of words

Tokenization & Stop words

Stemming & Lemmatization

TF-IDF

N-Gram

Word embedding

Normalization

Pos tagging

Parser

semantic analysis

Regular expression

Learn MySQL

Learn MongoDB

Learn Web scraping

Learn Excel

Learn Power BI

Learn Tableau

Learn Docker

Learn Hadoop

Convolution Neural Network Binary Classification Exercise

About the Dataset

Let's understand the file:
In this example we have two different category of strawberry angular leaf spot and leaf spot. In D drive of my computer I have a folder name data. In this folder I have two different folder named angular_leaf_spot and leaf_spot. Inside angular_leaf_spot I have a all the strawberry images which are angular spot of strawberry leaf(different image of strawberry angular leaf spot disease) and in the leaf_spot I have all the images which are leaf_spot of strawberry leaf(different image of strawberry leaf spot disease). So we can say that we have two different disease category of strawberry leaf in two different separate folders and this two folder are present inside data folder present in my D drive. So download image from online and prepare a dataset like I did.

Install keras

#!pip install tensorflow
#!pip install keras

Importing Libraries

#Basic libraries
import pandas as pd
import numpy as np
import os
import cv2
import random
import matplotlib.pyplot as plt

Getting the data

directory=r"D:\data"
'''
Because my those two different image folder are present in main folder name data. So we need the path of this data folder to access those images folder. So in directory variable we have the path of the data folder.
'''


categories=["angular_leaf_spot","leaf_spot"]
'''
Now we have to define the category folders name in form of list. So here we have only two folder one is angular_leaf_spot which contain angular leaf spot images and other is leaf_spot which contain leaf spot images. So in the list we will pass these two folders name in form of list.
'''

Connect the directory and category

Look in directory variable we have the path of main folder which contain our two different image folder and in category variable we have the name of those two folders name which contain two different category images. Now we have to connect these two together to access the image. To do this we will use a for loop.

img_data=[]
for catago in categories:
    folder=os.path.join(directory,catago)
    label=categories.index(catago)
    '''
    Here I joined the directory and categories and put in a
variable name folder.
    Now if you print the folder variable then you will see
    the complete path of these
two categories. So we can say by joining directory and
    categories variable we are
accessing the angular_leaf_spot and leaf_spot folder.
    Now we have to access the images
present inside of the folders.
    '''

    # Now we have to access the images present inside of the folders.
    for img in os.listdir(folder):
'''
    In folder we have angular_leaf_spot and leaf_spot
    folder and images are present inside of these
    two folders. So listdir function will take all the
    images from the folder.
    '''
    img=os.path.join(folder,img)
    '''
    In img variable we have     images and in folder we have
    the path of the images folder. So using
    path.join() we will joining     the images path(from
    folder) with the image. So by doing these we will
    get the images and complete     path of the images and we     will store all these in img variable.
'''

    #now we have to convert the image into array by
    read the image using imread function.
'''
    img_array=cv2.imread(img)

    #Resize the image
    img_array=cv2.resize(img_array,(100,100))
    '''
    We can have image in different sizes but for our
    work we need to convert all the images into
    same size.
    '''

    #labeling the images according to categories

    img_data.append([img_array,label])
    '''
    We have two different categories but we can have
    more. So to we have to use a label to
    the images according to the category. Suppose
    angular leaf spot as 0 and leaf spot
    as 1 so that we can classify that which image is
    from which category. We have images in
    different folders and in categories variable we
pass the images folder name as a list.
    So according to the image folder we can label the
    images. So after the first for loop we
    created the labels and at first outside of the for
    loop we created a empty list named
    img_data where we will store the images and label.
    '''

img_data
'''
After printing we will get two different things one is the
image array and other is the image label. Here
you will see only two label 0 or 1. It happens because label
the image according to the categories variable
list
'''
#Shuffle the images
random.shuffle(img_data)
'''
We have to shuffle because there can't be no sequence
between the image. Sequence means, suppose
first 10 images are angular leaf spot and then 10 images are
leaf spot. If this type of things happen
then the model will give bad accuracy because it will learn
the first 10 is angular leaf spot category and
second 10 images are leaf spot category. So when new test
data or new images will come it will not be able
to classify those image.
'''

Separating dependent variable(image label) and independent variable(image array)

x=[]
y=[]
for features,labels in img_data:
    x.append(features)
    y.append(labels)

#Convert X and Y list into array
X=np.array(x)
Y=np.array(y)

Feature scaling the X or independent data

X=X/255
'''
By doing this we scaled the array value between 0 to 1.
'''

X.shape

Model training

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D,Flatten,Dense,Activation
cnn=Sequential()
cnn.add(Conv2D(filters=32,kernel_size=(3,3),input_shape=X.shape[1:],activation="relu"))
'''
In cnn at first we have convolution layer and here we apply filters. So using Conv2D we are using convolution layer.
1. First parameter is number of filter. Here we write that how many number of filters we want to use on image in this layer.
2. Second parameter is filter size.
3. Third parameter is input_shape. Here we write the shape of an image. Here all the images are present in X variable so by using X.shape we are getting the shape of the image and by using [1:] we taking the shape of the first image.
4. Last parameter is activation function
'''
cnn.add(MaxPooling2D(pool_size=(2,2)))
'''
After performing convolution the image goes to the pooling
layer. So the second layer will be pooling layer.
There are lot of pooling types but here we will use
maxpooling. In the maxpooling layers we have to define
the pooling layer size as a parameter
'''
cnn.add(Flatten())
'''
After the pooling layer the image goes to the flatten layer.
So our third layer will be flatten layer.
'''
cnn.add(Dense(units=2,activation="sigmoid"))
'''
After the flatten layer we have the output layer.
Because we have two categories so we will use 2 neurons in
output layer.
That's why passed 2 as units value and for binary
classification sigmoid activation
function works well but here you can use any list softmax etc.
Now if we have more than 2 category then we will use the
number of neurons equal to the number of categories and for multi class
classification softmax activation function works well.
'''
cnn.compile(optimizer="adam",loss="sparse_categorical_crossentropy",metrics=["accuracy"])

cnn.fit(X,Y,epochs=100,validation_split=0.2)
'''
So here at first we passed our independent feature X and
dependent feature Y.
After this we have to pass the epochs size.
Because here we don't divide the data into train and test
data that's why we need to
pass validation_split. In the example 0.2 means from the
total data 20 data will be used
as test data and remaining 80% will be train data.
'''

prediction system

#from keras.preprocessing import image
from tensorflow.keras.utils import load_img, img_to_array


img_pred= keras.utils.load_img("D:/data/angular_leaf_spot/angular_leafspot359.jpg",target_size=(100,100))
'''
To load the image, here at first we have to give the image
full path, image name and image extension.
After we have to resize the image. While training we resize
all the images 100x100. So
we have to also resize the image 100x100.
'''
img_pred=keras.utils.img_to_array(img_pred)
'''
As we know the can be read in it's original form. To read
the image we have to convert
the image into a array. So here we converted the image into
a array.
'''
img_pred=np.expand_dims(img_pred,axis=0)
'''
Using expand_dims we increase the dimension of the image
array
'''
result=cnn.predict(img_pred)
print(result)
'''
In result we will get a 2D array
'''
if result[0][0]>result[0][1]:
    prediction="angular leaf spot"
    '''
    Look the see the category variable again:
    categories=["angular_leaf_spot","leaf_spot"]
    Here we have total 2 category and in the result variable
we     have the 2D array. The index number of angular leaf spot
is [0][0]     and leaf_ spot is [0][1]. So     in the 2D array of the
result if the value     of angular leaf spot means[0][0] is greater than leaf
spot[0][1] then we     can say that it is a angular     leaf spot image and if not
then it is leaf spot image
    '''
else:
    prediction="leaf spot"
print(prediction)

CodersAim is created for learning and training a self learner to become a professional from beginner. While using CodersAim, you agree to have read and accepted our terms of use, privacy policy, Contact Us

© Copyright All rights reserved www.CodersAim.com. Developed by CodersAim.