{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport os\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, GlobalAveragePooling2D, Dropout, Flatten\nfrom tensorflow.keras.applications import VGG16\nimport matplotlib.pyplot as plt\nimport seaborn as sns","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-05-05T14:30:48.223691Z","iopub.execute_input":"2023-05-05T14:30:48.224597Z","iopub.status.idle":"2023-05-05T14:31:02.683740Z","shell.execute_reply.started":"2023-05-05T14:30:48.224550Z","shell.execute_reply":"2023-05-05T14:31:02.682559Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_ds=\"/kaggle/input/tomato/train\"\ntest_ds=\"/kaggle/input/tomato/valid\"","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:02.685609Z","iopub.execute_input":"2023-05-05T14:31:02.686465Z","iopub.status.idle":"2023-05-05T14:31:02.691744Z","shell.execute_reply.started":"2023-05-05T14:31:02.686426Z","shell.execute_reply":"2023-05-05T14:31:02.690882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size=32\nimg_size=224","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:02.693111Z","iopub.execute_input":"2023-05-05T14:31:02.693645Z","iopub.status.idle":"2023-05-05T14:31:02.702222Z","shell.execute_reply.started":"2023-05-05T14:31:02.693614Z","shell.execute_reply":"2023-05-05T14:31:02.701270Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale=1/255.,\n                             zoom_range=0.2,\n                            width_shift_range=0.2,height_shift_range=0.2\n                             )\ntest_datagen = ImageDataGenerator(rescale=1/255.)\n\ntrain_generator = train_datagen.flow_from_directory(train_ds,  \n                                                target_size=(img_size, img_size), \n                                                batch_size=batch_size,\n                                                shuffle=True,\n                                                class_mode='categorical')  \ntest_generator = test_datagen.flow_from_directory(test_ds,\n                                                    target_size=(img_size, img_size),\n                                                    batch_size=batch_size,\n                                                    shuffle=False,\n                                                    class_mode='categorical')","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:02.706515Z","iopub.execute_input":"2023-05-05T14:31:02.706791Z","iopub.status.idle":"2023-05-05T14:31:17.358302Z","shell.execute_reply.started":"2023-05-05T14:31:02.706768Z","shell.execute_reply":"2023-05-05T14:31:17.357369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = [k for k in train_generator.class_indices]\nsample_generate = train_generator.__next__()\n\nimages = sample_generate[0]\ntitles = sample_generate[1]\nplt.figure(figsize = (20 , 20))\n\nfor i in range(15):\n    plt.subplot(5 , 5, i+1)\n    plt.subplots_adjust(hspace = 0.3 , wspace = 0.3)\n    plt.imshow(images[i])\n    plt.title(f'Class: {labels[np.argmax(titles[i],axis=0)]}')\n    plt.axis(\"off\")","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:17.359770Z","iopub.execute_input":"2023-05-05T14:31:17.360404Z","iopub.status.idle":"2023-05-05T14:31:19.734306Z","shell.execute_reply.started":"2023-05-05T14:31:17.360366Z","shell.execute_reply":"2023-05-05T14:31:19.733099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator[0][0].shape","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:19.735607Z","iopub.execute_input":"2023-05-05T14:31:19.735953Z","iopub.status.idle":"2023-05-05T14:31:20.168924Z","shell.execute_reply.started":"2023-05-05T14:31:19.735924Z","shell.execute_reply":"2023-05-05T14:31:20.167851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img= train_generator[0]\nprint(img)","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:20.170434Z","iopub.execute_input":"2023-05-05T14:31:20.170788Z","iopub.status.idle":"2023-05-05T14:31:20.609068Z","shell.execute_reply.started":"2023-05-05T14:31:20.170756Z","shell.execute_reply":"2023-05-05T14:31:20.607943Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img = train_generator[0]\nprint(img[0].shape) # shape of the input batch\nprint(img[1].shape) # shape of the target labels","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:20.610969Z","iopub.execute_input":"2023-05-05T14:31:20.611769Z","iopub.status.idle":"2023-05-05T14:31:21.041211Z","shell.execute_reply.started":"2023-05-05T14:31:20.611729Z","shell.execute_reply":"2023-05-05T14:31:21.040033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(train_generator))\nprint(len(test_ds))","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:21.043819Z","iopub.execute_input":"2023-05-05T14:31:21.044862Z","iopub.status.idle":"2023-05-05T14:31:21.051289Z","shell.execute_reply.started":"2023-05-05T14:31:21.044832Z","shell.execute_reply":"2023-05-05T14:31:21.049982Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom skimage import io\n\n# Load image\nimg_url = \"/kaggle/input/tomato/valid/Bacterial_spot/014b58ae-091b-408a-ab4a-5a780cd1c3f3___GCREC_Bact.Sp 2971.JPG\"\nimg = io.imread(img_url)\n\n# Display image\nplt.imshow(img)\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:21.056763Z","iopub.execute_input":"2023-05-05T14:31:21.057476Z","iopub.status.idle":"2023-05-05T14:31:21.894760Z","shell.execute_reply.started":"2023-05-05T14:31:21.057449Z","shell.execute_reply":"2023-05-05T14:31:21.893927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nfrom keras.layers import Dense,Flatten,Conv2D,Activation,Dropout\n\nfrom keras import backend as K\n\nimport keras\n\nfrom keras.models import Sequential, Model\n\nfrom keras.models import load_model\n\nfrom keras.optimizers import SGD\n\nfrom keras.callbacks import EarlyStopping,ModelCheckpoint\n\nfrom keras.layers import MaxPool2D","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:21.896020Z","iopub.execute_input":"2023-05-05T14:31:21.896994Z","iopub.status.idle":"2023-05-05T14:31:21.902491Z","shell.execute_reply.started":"2023-05-05T14:31:21.896940Z","shell.execute_reply":"2023-05-05T14:31:21.901664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import Model\nfrom keras.layers import Input, Conv2D, GlobalAveragePooling2D, Dropout\nfrom keras.layers import Activation, BatchNormalization\nfrom keras.utils import plot_model\nfrom keras.applications.mobilenet import MobileNet\ndef mobilenet(input_shape):\n    input_tensor = Input(shape=input_shape)\n    base_model = MobileNet(include_top=False, input_tensor=input_tensor)\n\n    x = base_model.output\n    x = GlobalAveragePooling2D()(x)\n    x = Dropout(0.5)(x)\n    x = Dense(11, activation='softmax')(x)\n\n    model = Model(inputs=input_tensor, outputs=x)\n\n    return model\n\n\ninput_shape = (224, 224, 3)\nnum_classes = 11\n\nmodel = mobilenet(input_shape)\nmodel.summary()\nplot_model(model, to_file='mobilenet.png', show_shapes=True)","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:21.903727Z","iopub.execute_input":"2023-05-05T14:31:21.904645Z","iopub.status.idle":"2023-05-05T14:31:28.738336Z","shell.execute_reply.started":"2023-05-05T14:31:21.904612Z","shell.execute_reply":"2023-05-05T14:31:28.737515Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = mobilenet((224, 224, 3))","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:28.739405Z","iopub.execute_input":"2023-05-05T14:31:28.739851Z","iopub.status.idle":"2023-05-05T14:31:29.416606Z","shell.execute_reply.started":"2023-05-05T14:31:28.739822Z","shell.execute_reply":"2023-05-05T14:31:29.415613Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.optimizers import Adam\nopt = Adam(learning_rate=0.01)\nmodel.compile(optimizer=opt, loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:29.418250Z","iopub.execute_input":"2023-05-05T14:31:29.418604Z","iopub.status.idle":"2023-05-05T14:31:29.437966Z","shell.execute_reply.started":"2023-05-05T14:31:29.418572Z","shell.execute_reply":"2023-05-05T14:31:29.437013Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history =model.fit(train_generator, validation_data=test_generator, epochs=15)","metadata":{"execution":{"iopub.status.busy":"2023-05-05T14:31:29.439674Z","iopub.execute_input":"2023-05-05T14:31:29.440036Z","iopub.status.idle":"2023-05-05T16:15:39.529487Z","shell.execute_reply.started":"2023-05-05T14:31:29.440005Z","shell.execute_reply":"2023-05-05T16:15:39.528440Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_categories = len(os.listdir('/kaggle/input/tomato/train'))# number of categories print(n_categories)\nn_categories","metadata":{"execution":{"iopub.status.busy":"2023-05-05T16:19:34.899763Z","iopub.execute_input":"2023-05-05T16:19:34.900167Z","iopub.status.idle":"2023-05-05T16:19:34.909225Z","shell.execute_reply.started":"2023-05-05T16:19:34.900135Z","shell.execute_reply":"2023-05-05T16:19:34.908051Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results =pd.DataFrame(history.history)\nresults.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-05T16:19:16.235329Z","iopub.execute_input":"2023-05-05T16:19:16.235689Z","iopub.status.idle":"2023-05-05T16:19:16.285123Z","shell.execute_reply.started":"2023-05-05T16:19:16.235660Z","shell.execute_reply":"2023-05-05T16:19:16.284001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(15,6))\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model Loss')\nplt.ylabel('loss')\nplt.xlabel('epochs')\nplt.legend(['Train','Val'], loc= 'upper left')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-05T16:19:39.314428Z","iopub.execute_input":"2023-05-05T16:19:39.315200Z","iopub.status.idle":"2023-05-05T16:19:39.622845Z","shell.execute_reply.started":"2023-05-05T16:19:39.315166Z","shell.execute_reply":"2023-05-05T16:19:39.621988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(15,5))\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model Accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['Train', 'Val'], loc='upper left')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-05T16:19:44.681129Z","iopub.execute_input":"2023-05-05T16:19:44.681808Z","iopub.status.idle":"2023-05-05T16:19:44.964557Z","shell.execute_reply.started":"2023-05-05T16:19:44.681773Z","shell.execute_reply":"2023-05-05T16:19:44.963628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test_1 = test_generator.classes\ny_pred_1 =model.predict(test_generator)\ny_pred_1 = np.argmax(y_pred_1,axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-05-05T16:19:48.493399Z","iopub.execute_input":"2023-05-05T16:19:48.493777Z","iopub.status.idle":"2023-05-05T16:20:15.199801Z","shell.execute_reply.started":"2023-05-05T16:19:48.493732Z","shell.execute_reply":"2023-05-05T16:20:15.198804Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results =model.evaluate(test_generator)","metadata":{"execution":{"iopub.status.busy":"2023-05-05T16:20:31.200790Z","iopub.execute_input":"2023-05-05T16:20:31.201158Z","iopub.status.idle":"2023-05-05T16:20:57.780292Z","shell.execute_reply.started":"2023-05-05T16:20:31.201129Z","shell.execute_reply":"2023-05-05T16:20:57.779308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import classification_report\n\nprint(classification_report(y_test_1, y_pred_1))","metadata":{"execution":{"iopub.status.busy":"2023-05-05T16:21:28.667917Z","iopub.execute_input":"2023-05-05T16:21:28.668314Z","iopub.status.idle":"2023-05-05T16:21:29.010123Z","shell.execute_reply.started":"2023-05-05T16:21:28.668283Z","shell.execute_reply":"2023-05-05T16:21:29.009046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimage_directory = '/kaggle/input/tomato/train/Tomato_Yellow_Leaf_Curl_Virus'\nimg_size = 224\n\nimages = [] \nfor filename in os.listdir(image_directory):\n    path = os.path.join(image_directory, filename)\n    img = Image.open(path)\n    img = img.resize((img_size, img_size))\n    images.append(img)\n\nimages = np.array([np.array(img) for img in images])\nimages = images / 255.0\n\npredictions = model.predict(images)\n\n# Select image to display\nimg_index = 0\n\n# Get predicted class label\nclass_label = np.argmax(predictions[img_index])\n\n# Display image and predicted class label\nplt.imshow(images[img_index])\nplt.axis('off')\nplt.title('Predicted class: ' + str(class_label))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-05T16:21:34.015662Z","iopub.execute_input":"2023-05-05T16:21:34.016239Z","iopub.status.idle":"2023-05-05T16:21:54.753450Z","shell.execute_reply.started":"2023-05-05T16:21:34.016187Z","shell.execute_reply":"2023-05-05T16:21:54.751391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(len(images)):\n    predicted_class = np.argmax(predictions[i])\n    class_probability = predictions[i, predicted_class]\n    print(f'Predicted class for {i+1}.jpg : {labels[predicted_class]}')\n    print('Class probability:', class_probability)","metadata":{"execution":{"iopub.status.busy":"2023-05-05T16:22:03.344005Z","iopub.execute_input":"2023-05-05T16:22:03.345240Z","iopub.status.idle":"2023-05-05T16:22:03.421924Z","shell.execute_reply.started":"2023-05-05T16:22:03.345190Z","shell.execute_reply":"2023-05-05T16:22:03.421029Z"},"trusted":true},"execution_count":null,"outputs":[]}]}