Question: I need improvements on Python code for CNN ( convolutional neural network ) model that can follow the steps: 1 . Recognize the crop; 2

I need improvements on Python code for CNN (convolutional neural network)model that can follow the steps:
1.Recognize the crop;
2.Predict healthy/unhealthy crop;
3.Detect the disease;
4.If the crop is not recognized, try to predict healthy/unhealthy and then detect the disease.
Data from kaggle.com: 14kinds of crop, 43459images for training and 10876images for testing.
Print an accuracy plot diagram for each model. Also, logic needs to be corrected and final result printed. Please, leave comments for all steps.
import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.preprocessing import image import matplotlib.pyplot as plt import numpy as np import os train_dir ='/train' test_dir ='/test' IMG_HEIGHT =150 IMG_WIDTH =150 BATCH_SIZE =32 EPOCHS =10 train_datagen = ImageDataGenerator( rescale =1.0/255, rotation_range =20, width_shift_range =0.2, height_shift_range =0.2, shear_range =0.2, zoom_range =0.2, horizontal_flip = True, fill_mode = 'nearest' ) test_datagen = ImageDataGenerator(rescale=1.0/255) train_data = train_datagen.flow_from_directory( train_dir, target_size =(IMG_HEIGHT, IMG_WIDTH), batch_size = BATCH_SIZE, class_mode = 'categorical' ) test_data = test_datagen.flow_from_directory( test_dir, target_size =(IMG_HEIGHT, IMG_WIDTH), batch_size = BATCH_SIZE, class_mode = 'categorical' ) def create_model(output_classes): model = Sequential([ Conv2D(32,(3,3), activation = 'relu', input_shape =(IMG_HEIGHT, IMG_WIDTH, 3)), MaxPooling2D(2,2), Conv2D(64,(3,3), activation = 'relu'), MaxPooling2D(2,2), Conv2D(128,(3,3), activation = 'relu'), MaxPooling2D(2,2), Conv2D(128,(3,3), activation = 'relu'), MaxPooling2D(2,2), Flatten(), Dense(512, activation = 'relu'), Dropout(0.5), Dense(output_classes, activation = 'softmax')]) return model crop_model = create_model(output_classes =14) crop_model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics =['accuracy']) crop = crop_model.fit(test_data, validation_data = train_data, epochs = EPOCHS) plt.plot(crop.history['accuracy'], label = 'Train Accuracy') plt.plot(crop.history['val_accuracy'], label = 'Validation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() test_loss, test_accuracy = crop_model.evaluate(test_data) print(f'Test Accuracy: {test_accuracy *100:.2f}%') health_model = create_model(output_classes =2) #Healthy/Unhealthy health_model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics =['accuracy']) health = health_model.fit(test_data, validation_data = train_data, epochs = EPOCHS) plt.plot(health.history['accuracy'], label = 'Train Accuracy') plt.plot(health.history['val_accuracy'], label = 'Validation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() disease_model = create_model(output_classes =5) #5 diseases disease_model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics =['accuracy']) disease = disease_model.fit(test_data, validation_data = train_data, epochs = EPOCHS) plt.plot(disease.history['accuracy'], label = 'Train Accuracy') plt.plot(disease.history['val_accuracy'], label = 'Validation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() def classify_image(image_path): image_path ='?' img = image.load_img(image_path, target_size=(IMG_HEIGHT, IMG_WIDTH)) img_array = image.img_to_array(img)/255.0 img_array = np.expand_dims(img_array, axis=0) crop_prediction = crop_model.predict(img_array) crop_label = np.argmax(crop_prediction) if crop_label ==-1: health_prediction = health_model.predict(img_array) health_label = np.argmax(health_prediction) if health_label ==1: disease_prediction = disease_model.predict(img_array) disease_label = np.argmax(disease_prediction) return f"Unknown crop, Unhealthy, Disease detected: {disease_label}" else: return "Unknown crop, Healthy" else: health_prediction = health_model.predict(img_array) health_label = np.argmax(health_prediction) if health_label ==1: disease_prediction = disease_model.predict(img_array) disease_label = np.argmax(disease_prediction) return f"Crop: {crop_label}, Unhealthy, Disease detected: {disease_label}" else: return f"Crop: {crop_label}, Healthy" result = classify_image('?') print(result) crop_model.save('crop_recognition_model.h5') health_model.save('health_recognition_model.h5') disease_model.save('disease_recognition_model.h5')

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!