{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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)\nfrom tensorflow.keras import models\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import optimizers\nimport os\nimport glob\nimport shutil\nimport sys\nimport numpy as np\nfrom skimage.io import imread\nimport matplotlib.pyplot as plt\nfrom IPython.display import Image\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\nimport keras\nimport os\n\n#for 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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Installing EfficientNet"},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -U git+https://github.com/qubvel/efficientnet","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Importing EfficientNet"},{"metadata":{"trusted":true},"cell_type":"code","source":"from efficientnet.keras import EfficientNetB0\nfrom efficientnet.keras import center_crop_and_resize, preprocess_input","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Loading Pretrained Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"width = 150\nheight = 150\ninput_shape = (height, width, 3)\n\n\nbase_model = EfficientNetB0(weights='imagenet', include_top=False, input_shape=input_shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dir = '../input/herbarium-2021-fgvc8/train/images'\ntest_dir = '../input/herbarium-2021-fgvc8/test/images'\nbatch_size = 512","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Using image data generator"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    validation_split=0.2)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n        train_dir,\n        target_size=(height, width),\n        batch_size=batch_size,\n        class_mode='categorical',\n        shuffle = True,\n        subset='training')\n\nvalidation_generator = train_datagen.flow_from_directory(\n        train_dir,\n        target_size=(height, width),\n        batch_size=batch_size,\n        class_mode='categorical',\n        shuffle = False,\n        subset='validation')\n\nprint(train_generator.class_indices)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os, os.path\nepochs = 1\nNUM_TRAIN = sum([len(files) for r, d, files in os.walk(train_dir)])\ndropout_rate = 0.2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_classes = len(os.listdir(train_dir))\n\nmodel = models.Sequential()\nmodel.add(base_model)\nmodel.add(layers.GlobalMaxPooling2D(name=\"gmp\"))\nif dropout_rate > 0:\n    model.add(layers.Dropout(dropout_rate, name=\"dropout\"))\nmodel.add(layers.Dense(num_classes, activation='softmax', name=\"out\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()\n\nbase_model.trainable = False","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Train model"},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\ntf.test.gpu_device_name()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss='categorical_crossentropy',\n              optimizer=optimizers.Adam(lr=0.01),\n              metrics=['acc'])\n\n\nhistory = model.fit(\n      train_generator,\n      steps_per_epoch= (NUM_TRAIN*0.8) //batch_size,\n      epochs=epochs,\n      validation_data=validation_generator,\n      validation_steps= (NUM_TRAIN*0.2) //batch_size,\n      verbose=1,\n      use_multiprocessing=True,\n      workers=4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('effnetB0.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}