import tensorflow as tf
from tensorflow.keras import models, layers
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import cv2
import numpy as np
import PIL
from sklearn.metrics import classification_report,confusion_matrix
from sklearn.model_selection import train_test_split
from pathlib import Path
my_path = Path(r'/content/PlantVillage')
Potato___Early_blight = list(my_path.glob('Potato___Early_blight/*'))
Potato___Late_blight = list(my_path.glob('Potato___Late_blight/*'))
Potato___Late_blight = list(my_path.glob('Potato___Late_blight/*'))
potato_images_dict = {
'Potato___Early_blight': list(my_path.glob('Potato___Early_blight/*')),
'Potato___Late_blight': list(my_path.glob('Potato___Late_blight/*')),
'Potato___healthy': list(my_path.glob('Potato___healthy/*'))
}
potato_labels_dict = {
'Potato___Early_blight': 0,
'Potato___Late_blight': 1,
'Potato___healthy': 2
}
Summary of PlantVillage Dataset:
Split Data into Dependent variable and Independent variable :
X = []
y = []
for name,images in potato_images_dict.items():
for image in images:
img = cv2.imread(str(image))
resize = cv2.resize(img,(256,256))
X.append(resize)
y.append(potato_labels_dict[name])
Data Preprocessing :
X = np.array(X)
y = np.array(y)
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.1)
X_train_scaled = X_train / 255
X_test_scaled = X_test / 255
Create Dictionary with class names and corresponding lables :
class_names = {0:'Potato___Early_blight',1:'Potato___Late_blight',2:'Potato___healthy'}
Print Some Images from our Dataset :
plt.figure(figsize=(16,10))
for i in range(12):
ax = plt.subplot(3,4,i+1)
plt.imshow(X_train_scaled[i])
plt.title(class_names[y_train[i]],{'fontsize':20})
plt.axis("off")
model = models.Sequential([
layers.Conv2D(filters=32, kernel_size=(4, 4),
activation='relu', input_shape=(256, 256, 3)),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(filters=32, kernel_size=(3, 3),
activation='relu'),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dense(60,activation='relu'),
layers.Dense(3,activation='softmax')
]
)
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
model.fit(X_train_scaled,y_train,epochs=10)
Model Evaluation :
model.evaluate(X_test_scaled,y_test)
Classification Report :
y_pred = list()
for i in model.predict(X_test_scaled):
y_pred.append(np.argmax(i))
y_pred = np.array(y_pred)
print(classification_report(y_test,y_pred))
Confusion Matrix :
class_names = [0,1,2]
fig,ax = plt.subplots()
tick_marks = np.arange(len(class_names))
plt.xticks(tick_marks,class_names)
plt.yticks(tick_marks,class_names)
cnf_matrix = confusion_matrix(y_test,y_pred)
sns.heatmap(pd.DataFrame(cnf_matrix), annot = True, cmap = 'YlGnBu',
fmt = 'g')
ax.xaxis.set_label_position('top')
plt.tight_layout()
plt.ylabel('Actual label')
plt.xlabel('Predicted label')
plt.show()
Thank You ):