{"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\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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport matplotlib\nimport cv2\n\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nfrom keras.utils import to_categorical, Sequence\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization\nfrom keras.optimizers import RMSprop,Adam","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path = '/kaggle/input/hpa-single-cell-image-classification/'\n#os.listdir(path)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.read_csv(path+'train.csv')\nids = [\"../input/hpa-single-cell-image-classification/train/\" + fname + '_green.png' for fname in data['ID']]\nnum_classes = 19\ndef get_labels(labels):\n    new_labels = []\n    for label in labels:\n        label = label.split('|')\n        label = list(map(int, label))\n        label = to_categorical(label, num_classes=num_classes)\n        label = label.sum(axis=0)\n        new_labels.append(label)\n    return new_labels\nlabels = get_labels(data['Label'])\nnum_images = 1000","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data['Label']","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train, X_valid, y_train, y_valid = train_test_split(ids[:num_images],labels[:num_images], \n                                                      test_size = 0.2)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train[:2],y_train[:2]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMG_SIZE = 64\n\ndef process_image(image_path, img_size = IMG_SIZE):\n  \"\"\"\n  Takes an image file path and turns the image into a Tensor. \n  \"\"\"\n  # Read in an image file\n  image = tf.io.read_file(image_path)\n  # Turn the jpeg image into numerical Tensor with 3 colour channels (Red, Green, Blue)\n  image = tf.image.decode_jpeg(image, channels = 3)\n  # Convert the colour channel values from 0-255 to 0-1 values\n  image = tf.image.convert_image_dtype(image, tf.float32)\n  # Resize the image to our desired value (224, 224)\n  image = tf.image.resize(image,size = [img_size, img_size])\n  return image","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_image_label(image_path, label):\n  \"\"\"\n  Takes an image file path name and the assosciated label,\n  processes the image and reutrns a typle of (image, label).\n  \"\"\"\n  image = process_image(image_path)\n  return image,label","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BATCH_SIZE = 64\n\ndef create_data_batches(X , y = None, batch_size = BATCH_SIZE, valid_data = False, test_data = False):\n  \"\"\"\n  Creates batches of data out of image (X) and label (y) pairs.\n  Shuffles the data if it's training data but doesn't shuffle if it's validation data.\n  Also accepts test data as input (no labels).\n  \"\"\"\n  if test_data:\n    print('Creating test data batches........')\n    data = tf.data.Dataset.from_tensor_slices((tf.constant(X)))\n    data_batch = data.map(process_image).batch(batch_size)\n    return data_batch\n  \n  elif valid_data:\n    print('Creating valid data batches...........')\n    data = tf.data.Dataset.from_tensor_slices((tf.constant(X),tf.constant(y)))\n    data_batch = data.map(get_image_label).batch(batch_size)\n    return data_batch\n  \n  else:\n    print('Creating training data batches...............')\n    data = tf.data.Dataset.from_tensor_slices((tf.constant(X),tf.constant(y)))\n    data = data.shuffle(buffer_size = len(X))\n    data_batch = data.map(get_image_label).batch(batch_size)\n    return data_batch","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = create_data_batches(X_train,y_train)\nvalid_data = create_data_batches(X_valid,y_valid, valid_data=True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_size = 64\nimg_channel = 3","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"metrics = [tf.keras.metrics.AUC(name='auc', multi_label=True)]\nlearning_rate = 1e-3","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.layers import Conv2D,Dropout\nfrom keras.layers import MaxPool2D","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\nmodel.add(tf.keras.layers.Conv2D(64, (3,3), activation = 'relu', padding = 'Same',input_shape = (img_size, img_size, img_channel))),\nmodel.add(tf.keras.layers.MaxPooling2D(2, 2)),\nmodel.add(tf.keras.layers.Dropout(0.25)),\nmodel.add(Flatten())\nmodel.add(Dense(64, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.1))\nmodel.add(Dense(num_classes, activation='sigmoid'))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.output","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=Adam(lr=learning_rate), loss=\"binary_crossentropy\", metrics=metrics)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"early_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_accuracy', patience=3)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(train_data,validation_data=valid_data,epochs=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def save_model(model,suffix = 'None'):\n  \"\"\"\n  Saves a given model in a models directory and appends a suffix (string).\n  \"\"\"\n  modeldir = './'\n  model_path = modeldir + '-' + suffix + '.h5' # save format of model\n  print(f'Saving model to: {model_path}')\n  model.save(model_path)\n  return model_path","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"save_model(model,suffix = 'model-1')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_path = './-model-1.h5'\nloaded_model = tf.keras.models.load_model(model_path)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"id_names = [ids for ids in os.listdir('../input/hpa-single-cell-image-classification/test/')]\ntest_ids = []\nfor each_id in id_names:\n    if '_green.png' in each_id:\n        test_ids.append(each_id)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ids","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data = create_data_batches(test_ids, test_data= True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loaded_model.predict(test_data)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}