{"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 pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense , Activation, Dropout,Flatten\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\nfrom tensorflow.keras.utils import to_categorical,load_img,img_to_array\nfrom keras.backend import categorical_crossentropy\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Dense, Dropout\nfrom keras.applications.mobilenet import MobileNet, preprocess_input\nfrom sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay\nfrom tensorflow.keras.layers import Dropout, Dense,BatchNormalization, Flatten, MaxPool2D\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, Callback","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-06-23T11:27:47.723236Z","iopub.execute_input":"2022-06-23T11:27:47.724055Z","iopub.status.idle":"2022-06-23T11:27:56.202809Z","shell.execute_reply.started":"2022-06-23T11:27:47.723983Z","shell.execute_reply":"2022-06-23T11:27:56.201824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def scheduler(epoch):\n    if epoch <= 20:\n        return 0.01\n    elif epoch > 20 and epoch <= 30:\n        return 0.001 \n    else:\n        return 0.0001\nimport tensorflow as tf\nlr_callbacks = tf.keras.callbacks.LearningRateScheduler(scheduler)\n","metadata":{"execution":{"iopub.status.busy":"2022-06-23T11:29:45.670062Z","iopub.execute_input":"2022-06-23T11:29:45.670444Z","iopub.status.idle":"2022-06-23T11:29:45.677445Z","shell.execute_reply.started":"2022-06-23T11:29:45.670413Z","shell.execute_reply":"2022-06-23T11:29:45.675671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class cfg:\n    target_size=(300,300)\n    file = '../input/cassava123/Cassava_disease'\n    n_classes=5\n    input_shape=(300,300,3)\n    epochs=80\n    verbose=1 #hiển thị quá trình train\n    batch_size=16","metadata":{"execution":{"iopub.status.busy":"2022-06-23T11:29:44.009041Z","iopub.execute_input":"2022-06-23T11:29:44.009949Z","iopub.status.idle":"2022-06-23T11:29:44.016874Z","shell.execute_reply.started":"2022-06-23T11:29:44.009916Z","shell.execute_reply":"2022-06-23T11:29:44.015150Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = ImageDataGenerator(rescale=1./255,\n                               validation_split=0.2,\n                               rotation_range=20,\n                               width_shift_range=0.25,\n                               height_shift_range=0.25,    \n                               shear_range=0.25,\n                               zoom_range=0.25)\nvalidation_generator = ImageDataGenerator(rescale=1./255,\n                                    validation_split=0.2,\n                                    rotation_range=20,\n                                    width_shift_range=0.25,\n                                    height_shift_range=0.25,    \n                                    shear_range=0.25,\n                                    zoom_range=0.25)\n\ntrain_dataset=train_generator.flow_from_directory(cfg.file,\n                                     target_size=cfg.target_size,\n                                     batch_size=16,\n                                     class_mode='categorical',\n                                     subset=\"training\",\n                                     shuffle=True)\nvalidation_dataset=validation_generator.flow_from_directory(cfg.file,\n                                              target_size=cfg.target_size,\n                                              batch_size=16,\n                                              class_mode='categorical',\n                                              subset=\"validation\",\n                                              shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2022-06-23T11:29:49.201881Z","iopub.execute_input":"2022-06-23T11:29:49.202259Z","iopub.status.idle":"2022-06-23T11:29:49.525557Z","shell.execute_reply.started":"2022-06-23T11:29:49.202216Z","shell.execute_reply":"2022-06-23T11:29:49.523730Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"  def build_model():\n        model = Sequential()\n        model.add(Conv2D(32, (3, 3), input_shape=(300,300,3)))\n        model.add(Activation('relu'))\n        model.add(MaxPooling2D(pool_size=(2, 2)))\n\n        model.add(Conv2D(32, (3, 3)))\n        model.add(Activation('relu'))\n        model.add(MaxPooling2D(pool_size=(2, 2)))\n\n        model.add(Conv2D(64, (3, 3)))\n        model.add(Activation('relu'))\n        model.add(MaxPooling2D(pool_size=(2, 2)))\n        model.add(Conv2D(64, (3, 3)))\n        model.add(Activation('relu'))\n        model.add(MaxPooling2D(pool_size=(2, 2)))\n        model.add(Conv2D(64, (3, 3)))\n        model.add(Activation('relu'))\n        model.add(MaxPooling2D(pool_size=(2, 2)))\n\n        # the model so far outputs 3D feature maps (height, width, features)\n\n        model.add(Flatten())  # this converts our 3D feature maps to 1D feature vectors\n        model.add(Dense(1280))\n        model.add(Activation('relu'))\n        model.add(Dropout(0.5))\n        model.add(Dense(5))\n        model.add(Activation('softmax'))\n\n        model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])\n    \n        return model","metadata":{"execution":{"iopub.status.busy":"2022-06-23T11:29:58.892542Z","iopub.execute_input":"2022-06-23T11:29:58.893003Z","iopub.status.idle":"2022-06-23T11:29:58.906470Z","shell.execute_reply.started":"2022-06-23T11:29:58.892972Z","shell.execute_reply":"2022-06-23T11:29:58.905342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model=build_model()","metadata":{"execution":{"iopub.status.busy":"2022-06-23T11:30:02.264843Z","iopub.execute_input":"2022-06-23T11:30:02.265256Z","iopub.status.idle":"2022-06-23T11:30:05.960918Z","shell.execute_reply.started":"2022-06-23T11:30:02.265227Z","shell.execute_reply":"2022-06-23T11:30:05.959965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.compile(optimizer='adam',loss='categorical_crossentropy', metrics=['accuracy']) #categorical_crossentropy\nhistory=model.fit(train_dataset, batch_size=16, epochs=80, verbose=1,\n                  validation_data=validation_dataset)#, callbacks=[lr_callbacks]","metadata":{"execution":{"iopub.status.busy":"2022-06-23T11:30:11.885509Z","iopub.execute_input":"2022-06-23T11:30:11.885936Z","iopub.status.idle":"2022-06-23T12:14:50.164952Z","shell.execute_reply.started":"2022-06-23T11:30:11.885905Z","shell.execute_reply":"2022-06-23T12:14:50.163780Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = 50\n# Draw plot\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epochs')\nplt.legend(['train','Validation'])\nplt.show()\n\n# plt.figure(2,figsize=(7,5))\n# plt.plot(xc,train_acc)\n# plt.plot(xc,val_acc)\n# plt.xlabel('num of Epochs')\n# plt.ylabel('accuracy')\n# plt.title('train_acc vs val_acc')\n# plt.grid(True)\n# plt.legend(['train','val'],loc=4)\n# #print plt.style.available # use bmh, classic,ggplot for big pictures\n# plt.style.use(['classic'])","metadata":{"execution":{"iopub.status.busy":"2022-06-23T12:15:09.948982Z","iopub.execute_input":"2022-06-23T12:15:09.949507Z","iopub.status.idle":"2022-06-23T12:15:10.321754Z","shell.execute_reply.started":"2022-06-23T12:15:09.949464Z","shell.execute_reply":"2022-06-23T12:15:10.320769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# SAVE MODEL","metadata":{}},{"cell_type":"code","source":"from keras.models import load_model\n\nmodel.save('model.h5')  # creates a HDF5 file 'my_model.h5'\n# del model  # deletes the existing model\n\n# returns a compiled model\n# identical to the previous one\n# model = load_model('my_model.h5')","metadata":{"execution":{"iopub.status.busy":"2022-06-20T06:41:15.445183Z","iopub.execute_input":"2022-06-20T06:41:15.44596Z","iopub.status.idle":"2022-06-20T06:41:15.745092Z","shell.execute_reply.started":"2022-06-20T06:41:15.4459Z","shell.execute_reply":"2022-06-20T06:41:15.744239Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.utils import load_img, img_to_array\nimport numpy as np\nimport matplotlib.pyplot as plt\nfilename = \"../input/cassava-leaf-disease-classification/train_images/1043184548.jpg\"\n\nimg = load_img(filename,target_size=(300,300))\nimg_show = plt.imshow(img)\nplt.show()\nimg = img_to_array(img)\nimg = img.reshape(1,300,300,3)\nimg = img.astype('float32')\nimg = img/255\nkq=np.argmax(model.predict(img),axis=-1)\nif(kq==0):\n    print(\"Cassava Bacterial Blight (CBB)\")\nif(kq==1):\n    print(\"Cassava Brown Streak Disease (CBSD)\")\nif(kq==2):\n    print(\"Cassava Green Mottle (CGM)\")\nif(kq==3):\n    print(\"Cassava Mosaic Disease (CMD)\")\nif(kq==4):\n    print(\"Healthy\")","metadata":{"execution":{"iopub.status.busy":"2022-06-23T12:15:22.555084Z","iopub.execute_input":"2022-06-23T12:15:22.555525Z","iopub.status.idle":"2022-06-23T12:15:23.043533Z","shell.execute_reply.started":"2022-06-23T12:15:22.555493Z","shell.execute_reply":"2022-06-23T12:15:23.042513Z"},"trusted":true},"execution_count":null,"outputs":[]}]}