Upload New File

parent 0dcb1563
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import os, glob\n",
"import cv2 as cv\n",
"import numpy as np\n",
"import pandas as pd\n",
"import tensorflow as tf\n",
"import matplotlib.pyplot as plt\n",
"from seaborn import heatmap, color_palette\n",
"from sklearn.metrics import confusion_matrix, classification_report"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"flower_disease_dataset_dir = 'data/flower_disease_type_dataset/'\n",
"\n",
"width = 224\n",
"height = 224\n",
"\n",
"target_size = (width, height)\n",
"input_shape = (width, height, 3)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"def preprocessing_function(img):\n",
" img = tf.keras.applications.xception.preprocess_input(img)\n",
" return img\n",
"\n",
"def image_data_generator():\n",
" train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(\n",
" rotation_range = 30,\n",
" shear_range = 0.3,\n",
" zoom_range = 0.3,\n",
" width_shift_range=0.3,\n",
" height_shift_range=0.3,\n",
" horizontal_flip = True,\n",
" validation_split= 0.15,\n",
" preprocessing_function=preprocessing_function\n",
" )\n",
"\n",
" train_generator = train_datagen.flow_from_directory(\n",
" flower_disease_dataset_dir,\n",
" target_size = target_size,\n",
" color_mode = 'rgb',\n",
" batch_size = 16,\n",
" class_mode = 'categorical',\n",
" subset = 'training',\n",
" shuffle = True\n",
" )\n",
"\n",
" validation_generator = train_datagen.flow_from_directory(\n",
" flower_disease_dataset_dir,\n",
" target_size = target_size,\n",
" color_mode = 'rgb',\n",
" batch_size = 8,\n",
" class_mode = 'categorical',\n",
" subset = 'validation',\n",
" shuffle = True\n",
" )\n",
"\n",
" return train_generator, validation_generator"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Found 781 images belonging to 3 classes.\n",
"Found 136 images belonging to 3 classes.\n"
]
}
],
"source": [
"train_generator, validation_generator = image_data_generator()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"def flower_disease_detector(): \n",
" functional_model = tf.keras.applications.Xception(\n",
" weights=\"imagenet\",\n",
" include_top=False\n",
" )\n",
" functional_model.trainable = True\n",
" \n",
" inputs = tf.keras.Input(shape=input_shape)\n",
" x = functional_model(inputs, training=True)\n",
"\n",
" x = tf.keras.layers.GlobalAveragePooling2D()(x)\n",
" x = tf.keras.layers.Dropout(0.2)(x)\n",
"\n",
" x = tf.keras.layers.Dense(512, activation='relu')(x)\n",
" x = tf.keras.layers.Dropout(0.5)(x)\n",
"\n",
" x = tf.keras.layers.Dense(256, activation='relu')(x)\n",
" x = tf.keras.layers.Dropout(0.5)(x)\n",
"\n",
" outputs = tf.keras.layers.Dense(3, activation='softmax')(x)\n",
"\n",
" model = tf.keras.Model(inputs=inputs, outputs=outputs)\n",
" model.summary()\n",
"\n",
" return model"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"model\"\n",
"_________________________________________________________________\n",
" Layer (type) Output Shape Param # \n",
"=================================================================\n",
" input_2 (InputLayer) [(None, 224, 224, 3)] 0 \n",
" \n",
" xception (Functional) (None, None, None, 2048 20861480 \n",
" ) \n",
" \n",
" global_average_pooling2d ( (None, 2048) 0 \n",
" GlobalAveragePooling2D) \n",
" \n",
" dropout (Dropout) (None, 2048) 0 \n",
" \n",
" dense (Dense) (None, 512) 1049088 \n",
" \n",
" dropout_1 (Dropout) (None, 512) 0 \n",
" \n",
" dense_1 (Dense) (None, 256) 131328 \n",
" \n",
" dropout_2 (Dropout) (None, 256) 0 \n",
" \n",
" dense_2 (Dense) (None, 3) 771 \n",
" \n",
"=================================================================\n",
"Total params: 22042667 (84.09 MB)\n",
"Trainable params: 21988139 (83.88 MB)\n",
"Non-trainable params: 54528 (213.00 KB)\n",
"_________________________________________________________________\n",
"48/48 [==============================] - 302s 6s/step - loss: 0.9764 - accuracy: 0.4915 - precision: 0.6494 - recall: 0.1961 - auc: 0.6935 - val_loss: 0.7644 - val_accuracy: 0.5956 - val_precision: 0.7397 - val_recall: 0.3971 - val_auc: 0.8369\n"
]
}
],
"source": [
"model = flower_disease_detector()\n",
"model.compile(\n",
" optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), \n",
" loss='categorical_crossentropy', \n",
" metrics=[\n",
" tf.keras.metrics.CategoricalAccuracy(name='accuracy'),\n",
" tf.keras.metrics.Precision(name='precision'),\n",
" tf.keras.metrics.Recall(name='recall'),\n",
" tf.keras.metrics.AUC(name='auc')\n",
" ])\n",
"\n",
"history = model.fit(\n",
" train_generator,\n",
" validation_data = validation_generator,\n",
" steps_per_epoch = train_generator.samples // train_generator.batch_size,\n",
" validation_steps = validation_generator.samples // validation_generator.batch_size,\n",
" epochs = 1\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"c:\\Users\\user\\anaconda3\\envs\\myenv\\lib\\site-packages\\keras\\src\\engine\\training.py:3000: UserWarning: You are saving your model as an HDF5 file via `model.save()`. This file format is considered legacy. We recommend using instead the native Keras format, e.g. `model.save('my_model.keras')`.\n",
" saving_api.save_model(\n"
]
}
],
"source": [
"model.save('models/flower_disease_detector.h5')"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Evaluation"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"({0: 'Black Spot', 1: 'Downy Mildew', 2: 'Fresh Leaf'},\n",
" {'Black Spot': 0, 'Downy Mildew': 1, 'Fresh Leaf': 2})"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class_dict = train_generator.class_indices\n",
"class_dict = dict((v,k) for k,v in class_dict.items())\n",
"class_dict_rev = dict((v,k) for k,v in class_dict.items())\n",
"\n",
"class_dict, class_dict_rev"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Inference"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"import base64 \n",
"import datetime\n",
"import cv2 as cv\n",
"import numpy as np\n",
"import pandas as pd\n",
"from tkinter import *\n",
"import firebase_admin\n",
"import tensorflow as tf\n",
"import tkinter.filedialog\n",
"from firebase_admin import db\n",
"from PIL import ImageTk, Image\n",
"from firebase_admin import firestore\n",
"from firebase_admin import credentials"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"model = tf.keras.models.load_model('models/flower_disease_detector.h5')"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"# def inference_func(\n",
"# image_path,\n",
"# solution_dir = 'data/Rose_diseases and solution.xlsx'\n",
"# ):\n",
"# img_file = image_path.split('/')[-2]\n",
"# image = cv.imread(image_path)\n",
"# image = cv.cvtColor(image, cv.COLOR_BGR2RGB)\n",
"# image = cv.resize(image, target_size)\n",
"# image = np.expand_dims(image, axis=0)\n",
"# image = preprocessing_function(image)\n",
"# pred = model.predict(image, verbose=0).squeeze()\n",
"# pred = np.argmax(pred)\n",
"# pred = class_dict[class_dict_rev[img_file]]\n",
"\n",
"# solution = pd.read_excel(solution_dir)\n",
"# solution = solution[solution['Disease'] == pred]\n",
"# if len(solution) == 0:\n",
"# return {\n",
"# \"label\" : pred,\n",
"# \"solution\" : \"N/A\",\n",
"# \"description\" : \"N/A\"\n",
"# }\n",
"# else:\n",
"# return {\n",
"# \"label\" : pred,\n",
"# \"solution\" : solution['Solution'].values[0],\n",
"# \"description\" : solution['Description'].values[0]\n",
"# }\n",
"\n",
"def inference_func(\n",
" image_path,\n",
" target_size = (224, 224),\n",
" class_dict = {0: 'Black Spot', 1: 'Downy Mildew', 2: 'Fresh Leaf'}\n",
" ):\n",
" class_dict_rev = dict((v,k) for k,v in class_dict.items())\n",
" img_file = image_path.split('/')[-2]\n",
" image = cv.imread(image_path)\n",
" image = cv.cvtColor(image, cv.COLOR_BGR2RGB)\n",
" image = cv.resize(image, target_size)\n",
" image = np.expand_dims(image, axis=0)\n",
" image = tf.keras.applications.xception.preprocess_input(image)\n",
" pred = model.predict(image, verbose=0).squeeze()\n",
" pred = np.argmax(pred)\n",
" pred = class_dict[class_dict_rev[img_file]]\n",
" return pred"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Downy Mildew'"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"image_path = 'data/flower_disease_type_dataset/Downy Mildew/Downy Mildew (1).jpg'\n",
"inference_func(image_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "tf210",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.17"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment