{"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)\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tqdm import tqdm\nfrom shutil import copyfile","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","collapsed":true,"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":false},"cell_type":"markdown","source":"Data preparation for binary classification (Cassava Mosaic Disease (CMD) vs others)"},{"metadata":{"trusted":true},"cell_type":"code","source":"class_i_what_to_predict = 3\n\nsource = '../input/cassava-leaf-disease-classification/train_images'\n\ndata = pd.read_csv(os.path.join('../input/cassava-leaf-disease-classification/','train.csv'))\n\ndata.groupby('label').agg({'image_id':'nunique'})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"root = './root/'\nos.mkdir(root)\n\nos.mkdir(os.path.join(root, 'train'))\ntrain_folder = root+'train/'\n\nos.mkdir(os.path.join(root, 'test'))\ntest_folder = root+'test/'\n\nos.mkdir(os.path.join(train_folder, 'class'))\nos.mkdir(os.path.join(train_folder, 'other'))\n\nos.mkdir(os.path.join(test_folder, 'class'))\nos.mkdir(os.path.join(test_folder, 'other'))\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_folder_class = './root/train/class/'\ntrain_folder_other = './root/train/other/'\n\ntest_folder_class = './root/test/class/'\ntest_folder_other = './root/test/other/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images_class = data[data['label']==class_i_what_to_predict]['image_id']\n\nimages_other = data[data['label']!=class_i_what_to_predict]['image_id']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"split_class = int(len(images_class)*0.1)\nsplit_other = int(len(images_other)*0.1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images_class = np.array(images_class)\nimages_other = np.array(images_other)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.random.shuffle(images_class)\nnp.random.shuffle(images_other)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for img in tqdm(images_class[:split_class]):\n    copyfile(os.path.join(source, img), os.path.join(test_folder_class, img))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for img in tqdm(images_class[split_class:]):\n    copyfile(os.path.join(source, img), os.path.join(train_folder_class, img))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for img in tqdm(images_other[:split_other]):\n    copyfile(os.path.join(source, img), os.path.join(test_folder_other, img))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for img in tqdm(images_other[split_other:]):\n    copyfile(os.path.join(source, img), os.path.join(train_folder_other, img))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(os.listdir(train_folder_class)))\nprint(len(os.listdir(test_folder_class)))\nprint(len(os.listdir(train_folder_other)))\nprint(len(os.listdir(test_folder_other)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Prepare data for tf"},{"metadata":{"trusted":true},"cell_type":"code","source":"#from tensorflow.keras.applications import Xception\nfrom tensorflow.keras.applications import NASNetMobile\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Dense, Flatten, MaxPooling2D, BatchNormalization, Dropout, Conv2D, Input\nfrom tensorflow.keras.optimizers import SGD\n#from tensorflow.keras.applications.xception import preprocess_input\nfrom tensorflow.keras.applications.nasnet import preprocess_input","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_folder = './root/train/'\ntest_folder = './root/test/'\n\ntrain_gen = ImageDataGenerator(\n    preprocessing_function=preprocess_input,\n    rescale=1./255.,\n    rotation_range=90,\n    width_shift_range=0.5,\n    height_shift_range=0.5,\n    shear_range=0.5,\n    zoom_range=0.5,\n    horizontal_flip=True,\n    vertical_flip=True,\n    fill_mode='nearest'\n)\n\ntest_gen = ImageDataGenerator(\n    preprocessing_function=preprocess_input,\n    rescale=1./255.\n)\n\ntrain_data_generator = train_gen.flow_from_directory(\n    directory=train_folder,\n    target_size=(224,224),\n    batch_size=64\n)\n\ntest_data_generator = test_gen.flow_from_directory(\n    directory=test_folder,\n    target_size=(224,224)\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model = NASNetMobile(\n    include_top=False,\n    weights='imagenet',\n    input_shape=(224, 224, 3),\n    pooling='max'\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model.trainable=False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential([\n    Input(shape=(224,224,3)),\n    base_model,\n    #Dense(256, activation='relu'),\n    Dense(128, activation='relu'),\n    Dense(1, activation='sigmoid')\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss='binary_crossentropy',\n    metrics=['binary_accuracy']\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(\n    train_data_generator,\n    validation_data=test_data_generator,\n    epochs=1\n)","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}