Deepaksiwania12's picture
Update app.py
a942d3e
import numpy as np
import cv2
import glob
import os
import matplotlib.pyplot as plt
import string
from mlxtend.plotting import plot_decision_regions
from mpl_toolkits.mplot3d import Axes3D
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.utils.multiclass import unique_labels
from sklearn import metrics
from sklearn.svm import SVC
dim = 100
from imutils import paths
import cv2
!unzip /content/drive/MyDrive/Tomato.zip -d MTP
import os
# Define the paths for the train and test datasets
train_base_dir = '/content/MTP/dataset/train'
test_base_dir = '/content/MTP/dataset/val'
# List of class names to keep
class_names_to_keep = [
"Late_blight", "Tomato_mosaic_virus", "healthy",
"Septoria_leaf_spot", "Bacterial_spot", "Tomato_Yellow_Leaf_Curl_Virus"
]
# Create lists to store the file paths for train and test images
train_image_paths = []
test_image_paths = []
# Populate the train and test image paths based on the specified classes
for class_name in class_names_to_keep:
train_image_paths.extend([os.path.join(train_base_dir, class_name, filename) for filename in os.listdir(os.path.join(train_base_dir, class_name))])
test_image_paths.extend([os.path.join(test_base_dir, class_name, filename) for filename in os.listdir(os.path.join(test_base_dir, class_name))])
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# Define image dimensions and batch size
image_height, image_width = 224, 224
batch_size = 32
# Define a function to load and preprocess the images, including labels
def load_and_preprocess_image(image_path, label):
image = tf.io.read_file(image_path)
image = tf.image.decode_jpeg(image, channels=3)
image = tf.image.resize(image, [image_height, image_width])
image = image / 255.0
return image, label
# Create TensorFlow Datasets with labels
train_labels = [0 if "healthy" in path else 1 for path in train_image_paths]
test_labels = [0 if "healthy" in path else 1 for path in test_image_paths]
train_dataset = tf.data.Dataset.from_tensor_slices((train_image_paths, train_labels))
train_dataset = train_dataset.map(load_and_preprocess_image)
train_dataset = train_dataset.batch(batch_size)
test_dataset = tf.data.Dataset.from_tensor_slices((test_image_paths, test_labels))
test_dataset = test_dataset.map(load_and_preprocess_image)
test_dataset = test_dataset.batch(batch_size)
# Define and compile the CNN model as before
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
# Define the CNN model
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(image_height, image_width, 3)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Conv2D(128, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(128, activation='relu'),
Dense(1, activation='sigmoid') # Binary classification, so using sigmoid activation
])
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Train the model on the training dataset
model.fit(train_dataset, epochs=10)
# Call the function to plot the training histo
# Evaluate the model on the test dataset
test_loss, test_accuracy = model.evaluate(test_dataset)
print(f'Test Accuracy: {test_accuracy}')
import numpy as np
import matplotlib.pyplot as plt
# Assuming train_dataset and test_dataset are BatchDataset objects
# Function to get a batch of random images and labels
def get_random_batch(dataset, batch_size=5):
dataset_iter = iter(dataset)
images, labels = [], []
for _ in range(batch_size):
batch = next(dataset_iter)
images.append(batch[0][0])
labels.append(batch[1][0])
return np.array(images), np.array(labels)
# Get random images and labels from the test dataset
random_images, random_labels = get_random_batch(test_dataset)
# Predict the labels using the trained model
predictions = model.predict(random_images)
# Convert the predicted probabilities to binary predictions
binary_predictions = [1 if p > 0.5 else 0 for p in predictions]
# Map binary labels and predictions to their respective classes
class_labels = {0: 'Healthy', 1: 'Defective'}
true_labels = [class_labels[label] for label in random_labels]
predicted_labels = [class_labels[prediction] for prediction in binary_predictions]
# Display the images along with their true and predicted labels
plt.figure(figsize=(15, 5))
for i in range(5):
plt.subplot(1, 5, i+1)
plt.imshow(random_images[i])
plt.title(f'True: {true_labels[i]}\nPredicted: {predicted_labels[i]}')
plt.axis('off')
plt.show()