{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-05-23T11:33:35.492911Z","iopub.execute_input":"2021-05-23T11:33:35.493469Z","iopub.status.idle":"2021-05-23T11:33:37.974010Z","shell.execute_reply.started":"2021-05-23T11:33:35.493432Z","shell.execute_reply":"2021-05-23T11:33:37.972911Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#importing libraries\nimport numpy as np\nimport cv2\nimport os\nimport pandas as pd\nfrom PIL import Image\nimport keras \nnp.random.seed(1000)\n%matplotlib inline\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nfrom tqdm import tqdm\nimport tensorflow as tf\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Model,Sequential, Input, load_model\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization, AveragePooling2D, GlobalAveragePooling2D, MaxPooling2D\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ModelCheckpoint, ReduceLROnPlateau\nfrom keras.applications import DenseNet121","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:37.975802Z","iopub.execute_input":"2021-05-23T11:33:37.976132Z","iopub.status.idle":"2021-05-23T11:33:37.987304Z","shell.execute_reply.started":"2021-05-23T11:33:37.976100Z","shell.execute_reply":"2021-05-23T11:33:37.986485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport glob\nimport math\nfrom PIL import Image\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\nfrom keras.utils import to_categorical","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:37.988869Z","iopub.execute_input":"2021-05-23T11:33:37.989181Z","iopub.status.idle":"2021-05-23T11:33:38.002154Z","shell.execute_reply.started":"2021-05-23T11:33:37.989149Z","shell.execute_reply":"2021-05-23T11:33:38.000993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#数据路径\ndata_dir = \"../input/plant-pathology-2021-fgvc8\"\n\n#获取指定目录下的所有图片\ntrain_image_path = glob.glob(os.path.join(data_dir, \"train_images/*.jpg\"))\n\n#读取数据csv文件\nlabel_df = pd.read_csv(os.path.join(data_dir, \"train.csv\"))\n\n# Number od trainin images\nprint(\"Number of training images: {}\".format(len(train_image_path)))","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.004194Z","iopub.execute_input":"2021-05-23T11:33:38.004626Z","iopub.status.idle":"2021-05-23T11:33:38.106281Z","shell.execute_reply.started":"2021-05-23T11:33:38.004589Z","shell.execute_reply":"2021-05-23T11:33:38.105366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#返回列的所有唯一值（labels）\nlabels = label_df.labels.unique()\nprint(labels)\nprint(len(labels))","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.107527Z","iopub.execute_input":"2021-05-23T11:33:38.107813Z","iopub.status.idle":"2021-05-23T11:33:38.114500Z","shell.execute_reply.started":"2021-05-23T11:33:38.107786Z","shell.execute_reply":"2021-05-23T11:33:38.113641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Count number of data for each labels\nlabel_count = label_df.labels.value_counts()\nprint(label_count)\nlabel_ratio = label_df.labels.value_counts(normalize=True, sort=True)\nprint(label_ratio)","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.115791Z","iopub.execute_input":"2021-05-23T11:33:38.116097Z","iopub.status.idle":"2021-05-23T11:33:38.141561Z","shell.execute_reply.started":"2021-05-23T11:33:38.116064Z","shell.execute_reply":"2021-05-23T11:33:38.140439Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir= '../input/plant-pathology-2021-fgvc8/train_images'\ntest_dir =  '../input/plant-pathology-2021-fgvc8/test_images'\ntrain = pd.read_csv('../input/plant-pathology-2021-fgvc8/train.csv')\ntrain\n","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.142852Z","iopub.execute_input":"2021-05-23T11:33:38.143148Z","iopub.status.idle":"2021-05-23T11:33:38.171122Z","shell.execute_reply.started":"2021-05-23T11:33:38.143119Z","shell.execute_reply":"2021-05-23T11:33:38.170187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/plant-pathology-2021-fgvc8/train.csv' ,dtype=str)\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.173515Z","iopub.execute_input":"2021-05-23T11:33:38.173813Z","iopub.status.idle":"2021-05-23T11:33:38.200384Z","shell.execute_reply.started":"2021-05-23T11:33:38.173783Z","shell.execute_reply":"2021-05-23T11:33:38.199447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nlabelencoder = LabelEncoder()\n# 将类别数据数字化\ntrain['labels_type'] = labelencoder.fit_transform(train['labels'])\ntrain","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.202124Z","iopub.execute_input":"2021-05-23T11:33:38.202430Z","iopub.status.idle":"2021-05-23T11:33:38.222733Z","shell.execute_reply.started":"2021-05-23T11:33:38.202402Z","shell.execute_reply":"2021-05-23T11:33:38.221985Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/plant-pathology-2021-fgvc8/train.csv' ,dtype=str)\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.223886Z","iopub.execute_input":"2021-05-23T11:33:38.224399Z","iopub.status.idle":"2021-05-23T11:33:38.254851Z","shell.execute_reply.started":"2021-05-23T11:33:38.224366Z","shell.execute_reply":"2021-05-23T11:33:38.254067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nlabelencoder = LabelEncoder()\n# Assigning numerical values and storing in another column\ndf['labels_type'] = labelencoder.fit_transform(df['labels'])\ndf","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.255915Z","iopub.execute_input":"2021-05-23T11:33:38.256373Z","iopub.status.idle":"2021-05-23T11:33:38.277312Z","shell.execute_reply.started":"2021-05-23T11:33:38.256335Z","shell.execute_reply":"2021-05-23T11:33:38.276572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ref = df.labels.unique()\nref","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.278467Z","iopub.execute_input":"2021-05-23T11:33:38.278917Z","iopub.status.idle":"2021-05-23T11:33:38.291215Z","shell.execute_reply.started":"2021-05-23T11:33:38.278873Z","shell.execute_reply":"2021-05-23T11:33:38.290473Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.labels_type.unique()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.292421Z","iopub.execute_input":"2021-05-23T11:33:38.292886Z","iopub.status.idle":"2021-05-23T11:33:38.302226Z","shell.execute_reply.started":"2021-05-23T11:33:38.292835Z","shell.execute_reply":"2021-05-23T11:33:38.301502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rng = 42\ntrain_csv = df.sample(frac=0.8, random_state=rng)\ntest_csv = df.loc[~df.index.isin(train_csv.index)]\ntrain_csv.head()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.303423Z","iopub.execute_input":"2021-05-23T11:33:38.303904Z","iopub.status.idle":"2021-05-23T11:33:38.325369Z","shell.execute_reply.started":"2021-05-23T11:33:38.303862Z","shell.execute_reply":"2021-05-23T11:33:38.324368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\ntrain_augmenter=ImageDataGenerator(\n    rescale=1./255, \n    #rotation range and fill mode only\n    samplewise_center=True, \n    samplewise_std_normalization=True, \n    horizontal_flip = True, \n    vertical_flip = True, \n    height_shift_range= 0.05, \n    width_shift_range=0.1, \n    rotation_range=45, \n    shear_range = 0.1,\n    fill_mode = 'nearest',\n    zoom_range=0.10,\n    #preprocessing_function=function_name,\n    )\n\ntest_augmenter=ImageDataGenerator(\n    rescale=1./255\n    )\ntrain_csv","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.326651Z","iopub.execute_input":"2021-05-23T11:33:38.326959Z","iopub.status.idle":"2021-05-23T11:33:38.344575Z","shell.execute_reply.started":"2021-05-23T11:33:38.326929Z","shell.execute_reply":"2021-05-23T11:33:38.343406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nIMAGE_SIZE = 64\ndef read_image(filepath):\n    return cv2.imread(os.path.join(data_dir, filepath))\n#调整图像到目标大小\ndef resize_image(image, image_size):\n    return cv2.resize(image.copy(), image_size, interpolation=cv2.INTER_AREA)","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.346112Z","iopub.execute_input":"2021-05-23T11:33:38.346426Z","iopub.status.idle":"2021-05-23T11:33:38.352741Z","shell.execute_reply.started":"2021-05-23T11:33:38.346397Z","shell.execute_reply":"2021-05-23T11:33:38.351548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Image_path = '/kaggle/input/plant-pathology-2021-fgvc8/train_images'\nbatch_size=16\nIMG_size=64\ntrain_generator=train_augmenter.flow_from_dataframe(\ndataframe=train_csv,\ndirectory=Image_path,\n#save_to_dir='augmented',\n#save_prefix='_aug'\n#save_format='jpg'\nx_col='image',\ny_col='labels',\nbatch_size=batch_size,\nseed=42,\nshuffle=True,\nclass_mode='categorical',\ntarget_size=(64, 64),\n)","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:38.354469Z","iopub.execute_input":"2021-05-23T11:33:38.354926Z","iopub.status.idle":"2021-05-23T11:33:44.181374Z","shell.execute_reply.started":"2021-05-23T11:33:38.354882Z","shell.execute_reply":"2021-05-23T11:33:44.180341Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# image path for the testing dataset\nImage_path = '/kaggle/input/plant-pathology-2021-fgvc8/train_images'\ntest_generator=test_augmenter.flow_from_dataframe(\ndataframe=test_csv,\ndirectory=Image_path,\n#save_to_dir='augmented',\n#save_prefix='_aug'\n#save_format='jpg'\nx_col='image',\ny_col='labels',\nbatch_size=batch_size,\nseed=42,\nclass_mode='categorical',\ntarget_size=(64, 64),\n)","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:44.182888Z","iopub.execute_input":"2021-05-23T11:33:44.183495Z","iopub.status.idle":"2021-05-23T11:33:45.643776Z","shell.execute_reply.started":"2021-05-23T11:33:44.183451Z","shell.execute_reply":"2021-05-23T11:33:45.642671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"INPUT_SHAPE = (64, 64, 3)\ndef build_model():\n    model = Sequential()\n\n    model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', \n                     input_shape=INPUT_SHAPE))\n    model.add(BatchNormalization(axis=1))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n\n    model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))\n    model.add(BatchNormalization(axis=1))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n\n    #model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))\n    #model.add(MaxPooling2D(pool_size=(2, 2)))\n\n    model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))\n    model.add(BatchNormalization(axis=1))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Conv2D(32, kernel_size=(3, 3), activation='relu'))\n    model.add(BatchNormalization(axis=1))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n\n    model.add(Flatten())\n    model.add(Dense(512, activation='relu'))\n    model.add(Dropout(0.2))\n    model.add(Dense(512, activation='relu'))\n    model.add(Dropout(0.2))\n    model.add(Dense(12, activation='softmax'))\n\n    opt = tf.keras.optimizers.Adam(learning_rate=0.0001)\n    model.compile(loss='categorical_crossentropy',optimizer=opt,metrics=['accuracy'])\n    model.summary()\n    return model","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:45.644899Z","iopub.execute_input":"2021-05-23T11:33:45.645175Z","iopub.status.idle":"2021-05-23T11:33:45.658485Z","shell.execute_reply.started":"2021-05-23T11:33:45.645148Z","shell.execute_reply":"2021-05-23T11:33:45.657310Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = build_model()\nhistory = model.fit(train_generator,epochs=4, steps_per_epoch = 190)","metadata":{"execution":{"iopub.status.busy":"2021-05-23T11:33:45.659913Z","iopub.execute_input":"2021-05-23T11:33:45.660220Z","iopub.status.idle":"2021-05-23T12:07:39.980554Z","shell.execute_reply.started":"2021-05-23T11:33:45.660192Z","shell.execute_reply":"2021-05-23T12:07:39.979491Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('model.h5')","metadata":{"execution":{"iopub.status.busy":"2021-05-23T12:07:39.982795Z","iopub.execute_input":"2021-05-23T12:07:39.983315Z","iopub.status.idle":"2021-05-23T12:07:40.073154Z","shell.execute_reply.started":"2021-05-23T12:07:39.983240Z","shell.execute_reply":"2021-05-23T12:07:40.072066Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import img_to_array\nfrom keras.preprocessing.image import load_img\nimport glob\ntest = glob.glob('/kaggle/input/plant-pathology-2021-fgvc8/test_images/' +'*'+'.jpg')\ntest","metadata":{"execution":{"iopub.status.busy":"2021-05-23T12:07:40.074694Z","iopub.execute_input":"2021-05-23T12:07:40.075180Z","iopub.status.idle":"2021-05-23T12:07:40.087417Z","shell.execute_reply.started":"2021-05-23T12:07:40.075134Z","shell.execute_reply":"2021-05-23T12:07:40.086281Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = pd.read_csv('/kaggle/input/plant-pathology-2021-fgvc8/sample_submission.csv')\nsample['labels'][0]","metadata":{"execution":{"iopub.status.busy":"2021-05-23T12:07:40.091023Z","iopub.execute_input":"2021-05-23T12:07:40.091348Z","iopub.status.idle":"2021-05-23T12:07:40.107290Z","shell.execute_reply.started":"2021-05-23T12:07:40.091316Z","shell.execute_reply":"2021-05-23T12:07:40.106296Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_real_samples(X1):\n    X1 = X1/ 255\n    return [X1]","metadata":{"execution":{"iopub.status.busy":"2021-05-23T12:07:40.108723Z","iopub.execute_input":"2021-05-23T12:07:40.109039Z","iopub.status.idle":"2021-05-23T12:07:40.113340Z","shell.execute_reply.started":"2021-05-23T12:07:40.109009Z","shell.execute_reply":"2021-05-23T12:07:40.112288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\nfor i in range(len(test)):\n    inp = load_img(test[i])\n    img =inp.resize(( 64, 64), Image.ANTIALIAS)\n    gh1 = img_to_array(img)\n    ph = load_real_samples(gh1)\n    ph1 = np.array(ph)\n    pred = model.predict(ph1)\n    predc = ref[np.argmax(pred[0,:])]\n    sample['labels'][i] = predc\n    print(predc)","metadata":{"execution":{"iopub.status.busy":"2021-05-23T12:28:17.948745Z","iopub.execute_input":"2021-05-23T12:28:17.949169Z","iopub.status.idle":"2021-05-23T12:28:19.104562Z","shell.execute_reply.started":"2021-05-23T12:28:17.949135Z","shell.execute_reply":"2021-05-23T12:28:19.103141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample.to_csv('submission.csv', index = False)","metadata":{"execution":{"iopub.status.busy":"2021-05-23T12:28:21.214911Z","iopub.execute_input":"2021-05-23T12:28:21.215318Z","iopub.status.idle":"2021-05-23T12:28:21.224166Z","shell.execute_reply.started":"2021-05-23T12:28:21.215286Z","shell.execute_reply":"2021-05-23T12:28:21.223341Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}