{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Galaxy Zoo - The Galaxy Challenge"},{"metadata":{},"cell_type":"markdown","source":"- INPUT: 299x299\n- Model: Xception\n- pooling: GlobalAverage\n- OUTPUT: 37class to reflect Decision Tree by Functional API"},{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","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 in \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 \"../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('../input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!unzip -n ../input/galaxy-zoo-the-galaxy-challenge/images_training_rev1.zip","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!unzip -n ../input/galaxy-zoo-the-galaxy-challenge/images_test_rev1.zip","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tqdm import tqdm\nimport zipfile\nimport io\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom skimage.transform import resize","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from __future__ import absolute_import, division, print_function, unicode_literals\nimport tensorflow as tf\nAUTOTUNE = tf.data.experimental.AUTOTUNE\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\nfrom tensorflow.keras.layers import Activation, Dropout, Flatten, Dense, BatchNormalization, GlobalMaxPooling2D\nfrom tensorflow.keras import backend as K","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.options.display.max_columns = 999\ndf = pd.read_csv('../input/galaxy-zoo-the-galaxy-challenge/training_solutions_rev1.zip')\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# df = df.sample(n=1000, random_state=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DATA_DIR = '../input/galaxy-zoo-the-galaxy-challenge/'\nzippath = '../input/galaxy-zoo-the-galaxy-challenge/images_training_rev1.zip'\nORIG_SIZE = 424\n# IMG_SIZE = 224\nIMG_SIZE = 299\n# IMG_SIZE = 424\n\nbatch_size = 32\n# batch_size = 16","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"# load zip\nzippath = '../input/galaxy-zoo-the-galaxy-challenge/images_training_rev1.zip'\nz = zipfile.ZipFile(zippath)\n\n# load image from zip\n# imgname = 'images_training_rev1/100008.jpg'\nimgname = 'images_training_rev1/100023.jpg'\nim = Image.open(io.BytesIO(z.read(imgname)))\nim_list = np.asarray(im)\nplt.imshow(im_list)\nplt.show()\n\nz.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"im_list.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(16,4))\nfor i in range(3):\n    plt.subplot(1,3,i+1)\n    plt.imshow(im_list[:,:,i])\n    plt.colorbar()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## tf.data.Dataset を使う"},{"metadata":{"trusted":true},"cell_type":"code","source":"def preprocess_image(image, augment_flag=False):\n    image = tf.image.decode_jpeg(image, channels=3)\n#     image = tf.image.resize(image, (IMG_SIZE,IMG_SIZE))\n    image = tf.image.resize_with_crop_or_pad(image, IMG_SIZE, IMG_SIZE)  # 中央crop\n    if augment_flag:\n        image = tf.image.random_flip_left_right(image)  # 左右反転\n        image = tf.image.random_flip_up_down(image)     # 上下反転\n    image /= 255  # normalize to [0,1] range\n\n    return image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_and_preprocess_image(path):\n#     img_path = '../input/galaxy-zoo-the-galaxy-challenge/images_training_rev1/' + path + '.jpg'\n    img_path = 'images_training_rev1/' + path + '.jpg'\n    image = tf.io.read_file(img_path)\n    return preprocess_image(image,  augment_flag=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# import matplotlib.pyplot as plt\n\n# label = str(df.iloc[1, 0])\n# # label = '303732'\n# # img_path = '../input/galaxy-zoo-the-galaxy-challenge/images_training_rev1/' + label + '.jpg'\n\n# plt.imshow(load_and_preprocess_image(label))\n# plt.grid(False)\n# plt.title(label)\n# plt.colorbar()\n# plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n(x_train, x_test, y_train, y_test) = train_test_split(df.values[:,0].astype(int).astype(str), df.values[:,1:], test_size=0.2, random_state=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train.shape, x_test.shape, y_train.shape, y_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path_ds = tf.data.Dataset.from_tensor_slices(x_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path_ds","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_ds = path_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_ds = tf.data.Dataset.from_tensor_slices(tf.cast(y_train, tf.float32))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_label_ds = tf.data.Dataset.zip((image_ds, label_ds))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# ds = image_label_ds.cache(filename='./cache.tf-data')\n# ds = image_label_ds.cache()\nds = image_label_ds\nds = ds.apply(\n    tf.data.experimental.shuffle_and_repeat(buffer_size=1000))\nds = ds.batch(batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path_ds_valid = tf.data.Dataset.from_tensor_slices(x_test)\nimage_ds_valid = path_ds_valid.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)\nlabel_ds_valid = tf.data.Dataset.from_tensor_slices(tf.cast(y_test, tf.float32))\nds_valid = tf.data.Dataset.zip((image_ds_valid, label_ds_valid))\nds_valid = ds_valid.batch(batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# for x in image_ds:\n# for x, y in image_label_ds:\nfor x, y in ds:\n#     print(x.shape)\n    print(x.shape, y.shape)\n    break","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# ネットワークの構築\nfrom tensorflow.keras.applications import VGG16, ResNet50, ResNet50V2, MobileNetV2, EfficientNetB0, InceptionResNetV2, Xception\nfrom tensorflow.keras import models, layers, regularizers\n\n# conv_base = VGG16(weights='imagenet',\n# conv_base = ResNet50(weights='imagenet',\n# conv_base = ResNet50V2(weights='imagenet',\n# conv_base = MobileNetV2(weights='imagenet',\n# conv_base = EfficientNetB0(weights='imagenet',\n# conv_base = InceptionResNetV2(weights='imagenet',\nconv_base = Xception(weights='imagenet',\n                 include_top=False, pooling='avg',\n                 input_shape=(IMG_SIZE, IMG_SIZE, 3))\nconv_base.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"conv_base.input_shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Functional API\nfrom tensorflow.keras.layers import Input, Flatten, Dense, Concatenate, Multiply\nfrom tensorflow.keras.activations import softmax, sigmoid\nfrom tensorflow.keras import Model\n\ninputs = Input(shape=(IMG_SIZE, IMG_SIZE, 3))\nx = conv_base(inputs)\nx = Flatten()(x)\nx = Dense(37, kernel_initializer='he_normal')(x)\n\n# Galaxy Zoo の Decision Tree の条件をモデルに反映\nx01 = softmax(x[:,:3])                             # Task01 合計が1.0\nx02 = Multiply()([softmax(x[:, 3: 5]), x01[:,1]])  # Task02 合計がTask01の2つ目\nx03 = Multiply()([softmax(x[:, 5: 7]), x02[:,1]])  # Task03 合計がTask02の2つ目\nx04 = Multiply()([softmax(x[:, 7: 9]), x02[:,1]])  # Task04 合計がTask02の2つ目\nx05 = Multiply()([softmax(x[:, 9:13]), x04[:,1]])  # Task05 合計がTask04の2つ目\nx06 = Multiply()([softmax(x[:,13:15]), x04[:,1]])  # Task06 合計がTask04の2つ目\nx07 = Multiply()([softmax(x[:,15:18]), x01[:,0]])  # Task07 合計がTask01の1つ目\nx08 = Multiply()([softmax(x[:,18:25]), x06[:,0]])  # Task08 合計がTask06の1つ目\nx09 = Multiply()([softmax(x[:,25:28]), x02[:,0]])  # Task09 合計がTask02の1つ目\nx10 = Multiply()([softmax(x[:,28:31]), x04[:,0]])  # Task10 合計がTask04の1つ目\nx11 = Multiply()([softmax(x[:,31:37]), x04[:,0]])  # Task11 合計がTask04の1つ目\n\noutputs = Concatenate(axis=1)([x01, x02, x03, x04, x05, x06, x07, x08, x09, x10, x11])\nmodel = Model(inputs=inputs, outputs=outputs)\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# for layer in conv_base.layers:\n#     print(layer.name)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 凍結\n# conv_base.trainable = False\n\n# 最初から特定の層までを凍結\n# conv_base.trainable = True\n# set_trainable = False\n# for layer in conv_base.layers:\n#     if layer.name == 'block14_sepconv1':\n#         set_trainable = True\n#     if set_trainable:\n#         layer.trainable = True\n#     else:\n#         layer.trainable = False\n\nlen(model.trainable_weights)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def root_mean_squared_error(y_true, y_pred):\n        return K.sqrt(K.mean(K.square(y_pred - y_true))) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# オプティマイザ構築\nfrom tensorflow.keras import optimizers\n\nmodel.compile(loss='MeanSquaredError',\n#              optimizer=optimizers.RMSprop(lr=1e-4),\n             optimizer=optimizers.RMSprop(lr=1e-3),\n#              optimizer=optimizers.Adam(lr=1e-4),\n#              optimizer=optimizers.Adam(lr=1e-3),\n#              optimizer=optimizers.SGD(lr=0.01),\n#              optimizer=optimizers.SGD(lr=0.01, momentum=0.9),\n             metrics=['acc', root_mean_squared_error])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n# history = model.fit(ds, epochs=5, steps_per_epoch=10, use_multiprocessing=True, workers=8, \n#                     validation_steps=10, validation_data=ds_valid)\nhistory = model.fit(ds, epochs=5, steps_per_epoch=x_train.shape[0]//batch_size, use_multiprocessing=True, workers=8, \n                    validation_steps=x_test.shape[0]//batch_size, validation_data=ds_valid)\n# history = model.fit(ds, epochs=20, steps_per_epoch=61578//32+1, workers=0, validation_steps=1, validation_data=ds_valid, initial_epoch=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = model.predict(ds_valid, use_multiprocessing=True, workers=8, verbose=1, steps=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"idx = 2\nprint(y_pred[idx])\nprint(sum(y_pred[idx,:3]), sum(y_pred[idx,3:5]), sum(y_pred[idx,5:7]), sum(y_pred[idx,7:9]), sum(y_pred[idx,9:13]), \n      sum(y_pred[idx,13:15]), sum(y_pred[idx,15:18]), sum(y_pred[idx,18:25]), sum(y_pred[idx,25:28]), sum(y_pred[idx,28:31]), \n      sum(y_pred[idx,31:37]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.evaluate(ds_valid)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('my_model.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history.history","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history[\"root_mean_squared_error\"], label=\"train\", ls=\"-\", marker=\"o\")\nplt.plot(history.history[\"val_root_mean_squared_error\"], label=\"test\", ls=\"-\", marker=\"x\")\nplt.ylabel(\"root_mean_squared_error\")\nplt.xlabel(\"epoch\")\nplt.legend(loc=\"best\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#acc, val_accのプロット\nplt.plot(history.history[\"acc\"], label=\"train\", ls=\"-\", marker=\"o\")\nplt.plot(history.history[\"val_acc\"], label=\"test\", ls=\"-\", marker=\"x\")\nplt.ylabel(\"Accuracy\")\nplt.ylim(0,1)\nplt.xlabel(\"epoch\")\nplt.legend(loc=\"best\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.read_csv('../input/galaxy-zoo-the-galaxy-challenge/all_ones_benchmark.zip')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# submission = submission.sample(n=1000, random_state=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_and_preprocess_test_image(path):\n#     img_path = '../input/galaxy-zoo-the-galaxy-challenge/images_test_rev1/' + path + '.jpg'\n    img_path = 'images_test_rev1/' + path + '.jpg'\n    image = tf.io.read_file(img_path)\n    return preprocess_image(image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nlabel = str(submission.iloc[0, 0])\n\nplt.imshow(load_and_preprocess_test_image(label))\nplt.grid(False)\nplt.title(label)\nprint()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path_ds_test = tf.data.Dataset.from_tensor_slices(submission.values[:,0].astype(int).astype(str))\nimage_ds_test = path_ds_test.map(load_and_preprocess_test_image, num_parallel_calls=AUTOTUNE)\nlabel_ds_test = tf.data.Dataset.from_tensor_slices(tf.cast(np.zeros((submission.shape[0], 37)), tf.float32))\nds_test = tf.data.Dataset.zip((image_ds_test, label_ds_test))\nds_test = ds_test.batch(batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# y_pred = model.predict(test_x)\ny_pred = model.predict(ds_test, use_multiprocessing=True, workers=8, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.iloc[:, 1:] = y_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv('submission.csv', index=False)","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}