Tomato-Leaf-Disease-Classification - Ipynb - Colaboratory

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Copy of tomato-leaf-disease-classification.ipynb - Colaboratory https://colab.research.google.com/drive/1nCXy9ZkIHWM6W5CmTOj...

!nvidia-smi

Fri Mar 18 09:29:19 2022


+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.32.03 Driver Version: 460.32.03 CUDA Version: 11.2 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|===============================+======================+======================|
| 0 Tesla K80 Off | 00000000:00:04.0 Off | 0 |
| N/A 38C P0 59W / 149W | 8457MiB / 11441MiB | 0% Default |
| | | N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes: |
| GPU GI CI PID Type Process name GPU Memory |
| ID ID Usage |
|=============================================================================|
+-----------------------------------------------------------------------------+

from google.colab import drive


drive.mount('/content/drive')

Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.

import tensorflow as tf
import pandas as pd
from tensorflow.keras.utils import to_categorical
import random
import numpy as np
import os
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split


from tensorflow.keras.layers import Input, Lambda, Dense, Flatten, Conv2D, MaxPooling
from tensorflow.keras.models import Model
from tensorflow.keras.applications.inception_v3 import InceptionV3
from keras.applications.vgg16 import VGG16

1 of 7 3/29/2022, 12:21 AM
Copy of tomato-leaf-disease-classification.ipynb - Colaboratory https://colab.research.google.com/drive/1nCXy9ZkIHWM6W5CmTOj...

from tensorflow.keras.applications.inception_v3 import preprocess_input


from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator,load_img, array_to_im
from tensorflow.keras.models import Sequential
from glob import glob

# Define Constants by re-sizing all the images


IMAGE_SIZE = [224, 224]

train_path = '/content/drive/MyDrive/Data/New Plant Diseases Dataset(Augmented)/train'


valid_path = '/content/drive/MyDrive/Data/New Plant Diseases Dataset(Augmented)/valid'

# Import the InceptionV3 model and here we will be using imagenet weights

inception = InceptionV3(input_shape=IMAGE_SIZE + [3], weights='imagenet', include_top=

# We don't need to train existing weights


for layer in inception.layers:
layer.trainable = False

# Folders in the Training Set


folders = glob('/content/drive/MyDrive/Data/New Plant Diseases Dataset(Augmented)/train/*
folders

['/content/drive/MyDrive/Data/New Plant Diseases Dataset(Augmented)/train/Tomato___S


'/content/drive/MyDrive/Data/New Plant Diseases Dataset(Augmented)/train/Tomato___S
'/content/drive/MyDrive/Data/New Plant Diseases Dataset(Augmented)/train/Tomato___L
'/content/drive/MyDrive/Data/New Plant Diseases Dataset(Augmented)/train/Tomato___h
'/content/drive/MyDrive/Data/New Plant Diseases Dataset(Augmented)/train/Tomato___L
'/content/drive/MyDrive/Data/New Plant Diseases Dataset(Augmented)/train/Tomato___E
'/content/drive/MyDrive/Data/New Plant Diseases Dataset(Augmented)/train/Tomato___T
'/content/drive/MyDrive/Data/New Plant Diseases Dataset(Augmented)/train/Tomato___B
'/content/drive/MyDrive/Data/New Plant Diseases Dataset(Augmented)/train/Tomato___T
'/content/drive/MyDrive/Data/New Plant Diseases Dataset(Augmented)/train/Tomato___T

# Model layers -> can add more if required


x = Flatten()(inception.output)
prediction = Dense(len(folders), activation='softmax')(x)

# Create a model object

2 of 7 3/29/2022, 12:21 AM
Copy of tomato-leaf-disease-classification.ipynb - Colaboratory https://colab.research.google.com/drive/1nCXy9ZkIHWM6W5CmTOj...

model = Model(inputs= inception.input, outputs=prediction)

# View the structure of the model


model.summary()

Model: "model_1"
____________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================
input_2 (InputLayer) [(None, 224, 224, 3 0 []
)]

conv2d_94 (Conv2D) (None, 111, 111, 32 864 ['input_2[0][0]']


)

batch_normalization_94 (BatchN (None, 111, 111, 32 96 ['conv2d_94[0][0]']


ormalization) )

activation_94 (Activation) (None, 111, 111, 32 0 ['batch_normalizati


)

conv2d_95 (Conv2D) (None, 109, 109, 32 9216 ['activation_94[0][


)

batch_normalization_95 (BatchN (None, 109, 109, 32 96 ['conv2d_95[0][0]']


ormalization) )

activation_95 (Activation) (None, 109, 109, 32 0 ['batch_normalizati


)

conv2d_96 (Conv2D) (None, 109, 109, 64 18432 ['activation_95[0][


)

batch_normalization_96 (BatchN (None, 109, 109, 64 192 ['conv2d_96[0][0]']


ormalization) )

activation_96 (Activation) (None, 109, 109, 64 0 ['batch_normalizati


)

max_pooling2d_4 (MaxPooling2D) (None, 54, 54, 64) 0 ['activation_96[0][

conv2d_97 (Conv2D) (None, 54, 54, 80) 5120 ['max_pooling2d_4[0

batch_normalization_97 (BatchN (None, 54, 54, 80) 240 ['conv2d_97[0][0]']


ormalization)

activation_97 (Activation) (None, 54, 54, 80) 0 ['batch_normalizati

conv2d_98 (Conv2D) (None, 52, 52, 192) 138240 ['activation_97[0][

batch_normalization_98 (BatchN (None, 52, 52, 192) 576 ['conv2d_98[0][0]']


ormalization)

activation_98 (Activation) (None, 52, 52, 192) 0 ['batch_normalizati

3 of 7 3/29/2022, 12:21 AM
Copy of tomato-leaf-disease-classification.ipynb - Colaboratory https://colab.research.google.com/drive/1nCXy9ZkIHWM6W5CmTOj...

max_pooling2d_5 (MaxPooling2D) (None, 25, 25, 192) 0 ['activation_98[0][

conv2d_102 (Conv2D) (None, 25, 25, 64) 12288 ['max_pooling2d_5[0

batch_normalization_102 (Batch (None, 25, 25, 64) 192 ['conv2d_102[0][0]'


Normalization)

activation_102 (Activation) (None, 25, 25, 64) 0 ['batch_normalizati

# Defining the cost and model optimization method to use


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

# Using the Image Data Generator to import the images from the dataset
from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255,


shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)

test_datagen = ImageDataGenerator(rescale = 1./255)

# Training Generator
training_set = train_datagen.flow_from_directory('/content/drive/MyDrive/Data/New Plant D
target_size = (224, 224),
batch_size = 32,
class_mode = 'categorical')

Found 18351 images belonging to 10 classes.

# Testing Generator
test_set = test_datagen.flow_from_directory('/content/drive/MyDrive/Data/New Plant Diseas
target_size = (224, 224),
batch_size = 32,
class_mode = 'categorical')

Found 18351 images belonging to 10 classes.

# fit the model, it will take some time to execute


r = model.fit_generator(
training_set,
validation_data=test_set,
epochs=10,
steps_per_epoch=len(training_set),
validation_steps=len(test_set)

4 of 7 3/29/2022, 12:21 AM
Copy of tomato-leaf-disease-classification.ipynb - Colaboratory https://colab.research.google.com/drive/1nCXy9ZkIHWM6W5CmTOj...

validation_steps=len(test_set)
)

/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:7: UserWarning: `Model.


import sys
Epoch 1/10
574/574 [==============================] - 412s 709ms/step - loss: 2.8035 - accuracy
Epoch 2/10
574/574 [==============================] - 406s 707ms/step - loss: 2.2216 - accuracy
Epoch 3/10
574/574 [==============================] - 405s 705ms/step - loss: 1.9214 - accuracy
Epoch 4/10
574/574 [==============================] - 405s 706ms/step - loss: 1.9865 - accuracy
Epoch 5/10
574/574 [==============================] - 405s 705ms/step - loss: 1.8837 - accuracy
Epoch 6/10
574/574 [==============================] - 405s 705ms/step - loss: 1.9020 - accuracy
Epoch 7/10
574/574 [==============================] - 404s 704ms/step - loss: 1.8636 - accuracy
Epoch 8/10
574/574 [==============================] - 401s 698ms/step - loss: 1.7344 - accuracy
Epoch 9/10
574/574 [==============================] - 399s 695ms/step - loss: 1.6948 - accuracy
Epoch 10/10
574/574 [==============================] - 398s 694ms/step - loss: 1.7112 - accuracy

# Plot the Loss and Accuracy


# Loss
plt.plot(r.history['loss'], label='train loss')
plt.plot(r.history['val_loss'], label='val loss')
plt.legend()
plt.show()
plt.savefig('LossVal_loss')

# Accuracy
plt.plot(r.history['accuracy'], label='train acc')
plt.plot(r.history['val_accuracy'], label='val acc')
plt.legend()
plt.show()
plt.savefig('AccVal_acc')

5 of 7 3/29/2022, 12:21 AM
Copy of tomato-leaf-disease-classification.ipynb - Colaboratory https://colab.research.google.com/drive/1nCXy9ZkIHWM6W5CmTOj...

<Figure size 432x288 with 0 Axes>

# Saving the model as a h5 file

from tensorflow.keras.models import load_model


model.save('model_inception.h5')

import tensorflow as tf

model = tf.keras.models.load_model('model_inception.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
open("tomato_model.tflite", "wb").write(tflite_model)

INFO:tensorflow:Assets written to: /tmp/tmp3s8r98vs/assets


INFO:tensorflow:Assets written to: /tmp/tmp3s8r98vs/assets
WARNING:absl:Buffer deduplication procedure will be skipped when flatbuffer library
89172604

y_pred = model.predict(test_set)
y_pred

array([[4.54377349e-26, 1.38337238e-37, 0.00000000e+00, ...,


0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
[5.61664192e-24, 1.67559716e-24, 0.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
[0.00000000e+00, 0.00000000e+00, 8.57696987e-24, ...,
0.00000000e+00, 8.27353865e-13, 5.91662407e-01],
...,

6 of 7 3/29/2022, 12:21 AM
Copy of tomato-leaf-disease-classification.ipynb - Colaboratory https://colab.research.google.com/drive/1nCXy9ZkIHWM6W5CmTOj...

[6.83899657e-37, 4.72217136e-21, 4.17483025e-05, ...,


5.92845635e-25, 2.34638081e-22, 4.86168740e-30],
[0.00000000e+00, 9.36552716e-34, 1.53146848e-31, ...,
0.00000000e+00, 0.00000000e+00, 1.04875594e-13],
[0.00000000e+00, 0.00000000e+00, 1.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 1.50146112e-34]], dtype=float32)

import numpy as np
y_pred = np.argmax(y_pred, axis=1)
y_pred

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-21-ceed490457b5> in <module>()
1 import numpy as np
----> 2 y_pred = np.argmax(y_pred, axis=1)
3 y_pred

NameError: name 'y_pred' is not defined

7 of 7 3/29/2022, 12:21 AM

You might also like