{"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":"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_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.","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2021-09-02T16:20:39.959607Z","iopub.execute_input":"2021-09-02T16:20:39.960032Z","iopub.status.idle":"2021-09-02T16:20:39.972980Z","shell.execute_reply.started":"2021-09-02T16:20:39.960001Z","shell.execute_reply":"2021-09-02T16:20:39.971207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip -n ../input/galaxy-zoo-the-galaxy-challenge/images_training_rev1.zip","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:20:39.975499Z","iopub.execute_input":"2021-09-02T16:20:39.976117Z","iopub.status.idle":"2021-09-02T16:21:07.194260Z","shell.execute_reply.started":"2021-09-02T16:20:39.976073Z","shell.execute_reply":"2021-09-02T16:21:07.192867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip -n ../input/galaxy-zoo-the-galaxy-challenge/images_test_rev1.zip","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:07.197635Z","iopub.execute_input":"2021-09-02T16:21:07.198157Z","iopub.status.idle":"2021-09-02T16:21:46.471150Z","shell.execute_reply.started":"2021-09-02T16:21:07.198110Z","shell.execute_reply":"2021-09-02T16:21:46.469612Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:46.476140Z","iopub.execute_input":"2021-09-02T16:21:46.481100Z","iopub.status.idle":"2021-09-02T16:21:47.974588Z","shell.execute_reply.started":"2021-09-02T16:21:46.481051Z","shell.execute_reply":"2021-09-02T16:21:47.973410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:47.979096Z","iopub.execute_input":"2021-09-02T16:21:47.979508Z","iopub.status.idle":"2021-09-02T16:21:54.644346Z","shell.execute_reply.started":"2021-09-02T16:21:47.979477Z","shell.execute_reply":"2021-09-02T16:21:54.643358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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()","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:54.645988Z","iopub.execute_input":"2021-09-02T16:21:54.646472Z","iopub.status.idle":"2021-09-02T16:21:55.226753Z","shell.execute_reply.started":"2021-09-02T16:21:54.646428Z","shell.execute_reply":"2021-09-02T16:21:55.225383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.describe()","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:55.228844Z","iopub.execute_input":"2021-09-02T16:21:55.229331Z","iopub.status.idle":"2021-09-02T16:21:55.438290Z","shell.execute_reply.started":"2021-09-02T16:21:55.229258Z","shell.execute_reply":"2021-09-02T16:21:55.437091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df = df.sample(n=1000, random_state=0)","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:55.440279Z","iopub.execute_input":"2021-09-02T16:21:55.440873Z","iopub.status.idle":"2021-09-02T16:21:55.446985Z","shell.execute_reply.started":"2021-09-02T16:21:55.440800Z","shell.execute_reply":"2021-09-02T16:21:55.445285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:55.449061Z","iopub.execute_input":"2021-09-02T16:21:55.449774Z","iopub.status.idle":"2021-09-02T16:21:55.457522Z","shell.execute_reply.started":"2021-09-02T16:21:55.449730Z","shell.execute_reply":"2021-09-02T16:21:55.455959Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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()","metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","execution":{"iopub.status.busy":"2021-09-02T16:21:55.459914Z","iopub.execute_input":"2021-09-02T16:21:55.460494Z","iopub.status.idle":"2021-09-02T16:21:56.525915Z","shell.execute_reply.started":"2021-09-02T16:21:55.460450Z","shell.execute_reply":"2021-09-02T16:21:56.524621Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"im_list.shape","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:56.528251Z","iopub.execute_input":"2021-09-02T16:21:56.528745Z","iopub.status.idle":"2021-09-02T16:21:56.536608Z","shell.execute_reply.started":"2021-09-02T16:21:56.528701Z","shell.execute_reply":"2021-09-02T16:21:56.535349Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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()","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:56.544925Z","iopub.execute_input":"2021-09-02T16:21:56.545694Z","iopub.status.idle":"2021-09-02T16:21:57.339485Z","shell.execute_reply.started":"2021-09-02T16:21:56.545633Z","shell.execute_reply":"2021-09-02T16:21:57.338081Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## tf.data.Dataset を使う","metadata":{}},{"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","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:57.341560Z","iopub.execute_input":"2021-09-02T16:21:57.341934Z","iopub.status.idle":"2021-09-02T16:21:57.350287Z","shell.execute_reply.started":"2021-09-02T16:21:57.341895Z","shell.execute_reply":"2021-09-02T16:21:57.348507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:57.352435Z","iopub.execute_input":"2021-09-02T16:21:57.353027Z","iopub.status.idle":"2021-09-02T16:21:57.362322Z","shell.execute_reply.started":"2021-09-02T16:21:57.352975Z","shell.execute_reply":"2021-09-02T16:21:57.360527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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()","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:57.364777Z","iopub.execute_input":"2021-09-02T16:21:57.365263Z","iopub.status.idle":"2021-09-02T16:21:57.372089Z","shell.execute_reply.started":"2021-09-02T16:21:57.365217Z","shell.execute_reply":"2021-09-02T16:21:57.370450Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:57.374176Z","iopub.execute_input":"2021-09-02T16:21:57.374785Z","iopub.status.idle":"2021-09-02T16:21:57.689696Z","shell.execute_reply.started":"2021-09-02T16:21:57.374737Z","shell.execute_reply":"2021-09-02T16:21:57.688363Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train.shape, x_test.shape, y_train.shape, y_test.shape","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:57.691667Z","iopub.execute_input":"2021-09-02T16:21:57.692177Z","iopub.status.idle":"2021-09-02T16:21:57.701555Z","shell.execute_reply.started":"2021-09-02T16:21:57.692134Z","shell.execute_reply":"2021-09-02T16:21:57.699820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path_ds = tf.data.Dataset.from_tensor_slices(x_train)","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:21:57.703654Z","iopub.execute_input":"2021-09-02T16:21:57.704151Z","iopub.status.idle":"2021-09-02T16:22:00.358852Z","shell.execute_reply.started":"2021-09-02T16:21:57.704109Z","shell.execute_reply":"2021-09-02T16:22:00.357683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path_ds","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:00.362851Z","iopub.execute_input":"2021-09-02T16:22:00.363159Z","iopub.status.idle":"2021-09-02T16:22:00.375103Z","shell.execute_reply.started":"2021-09-02T16:22:00.363130Z","shell.execute_reply":"2021-09-02T16:22:00.373628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_ds = path_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:00.377174Z","iopub.execute_input":"2021-09-02T16:22:00.377657Z","iopub.status.idle":"2021-09-02T16:22:00.709739Z","shell.execute_reply.started":"2021-09-02T16:22:00.377613Z","shell.execute_reply":"2021-09-02T16:22:00.708622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label_ds = tf.data.Dataset.from_tensor_slices(tf.cast(y_train, tf.float32))","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:00.711532Z","iopub.execute_input":"2021-09-02T16:22:00.711979Z","iopub.status.idle":"2021-09-02T16:22:01.055555Z","shell.execute_reply.started":"2021-09-02T16:22:00.711937Z","shell.execute_reply":"2021-09-02T16:22:01.054120Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_label_ds = tf.data.Dataset.zip((image_ds, label_ds))","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:01.057223Z","iopub.execute_input":"2021-09-02T16:22:01.057683Z","iopub.status.idle":"2021-09-02T16:22:01.064862Z","shell.execute_reply.started":"2021-09-02T16:22:01.057641Z","shell.execute_reply":"2021-09-02T16:22:01.063394Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:01.066911Z","iopub.execute_input":"2021-09-02T16:22:01.067628Z","iopub.status.idle":"2021-09-02T16:22:01.083285Z","shell.execute_reply.started":"2021-09-02T16:22:01.067575Z","shell.execute_reply":"2021-09-02T16:22:01.081589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:01.085425Z","iopub.execute_input":"2021-09-02T16:22:01.086180Z","iopub.status.idle":"2021-09-02T16:22:01.260036Z","shell.execute_reply.started":"2021-09-02T16:22:01.086117Z","shell.execute_reply":"2021-09-02T16:22:01.259038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test.shape","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:01.261628Z","iopub.execute_input":"2021-09-02T16:22:01.262053Z","iopub.status.idle":"2021-09-02T16:22:01.274939Z","shell.execute_reply.started":"2021-09-02T16:22:01.262011Z","shell.execute_reply":"2021-09-02T16:22:01.273204Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:01.277460Z","iopub.execute_input":"2021-09-02T16:22:01.277948Z","iopub.status.idle":"2021-09-02T16:22:03.902419Z","shell.execute_reply.started":"2021-09-02T16:22:01.277902Z","shell.execute_reply":"2021-09-02T16:22:03.901045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Model","metadata":{}},{"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()","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:03.904168Z","iopub.execute_input":"2021-09-02T16:22:03.904869Z","iopub.status.idle":"2021-09-02T16:22:06.600498Z","shell.execute_reply.started":"2021-09-02T16:22:03.904816Z","shell.execute_reply":"2021-09-02T16:22:06.599147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"conv_base.input_shape","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:06.605202Z","iopub.execute_input":"2021-09-02T16:22:06.605524Z","iopub.status.idle":"2021-09-02T16:22:06.619727Z","shell.execute_reply.started":"2021-09-02T16:22:06.605495Z","shell.execute_reply":"2021-09-02T16:22:06.618522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:06.621138Z","iopub.execute_input":"2021-09-02T16:22:06.621599Z","iopub.status.idle":"2021-09-02T16:22:06.671791Z","shell.execute_reply.started":"2021-09-02T16:22:06.621537Z","shell.execute_reply":"2021-09-02T16:22:06.670157Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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()","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:06.673986Z","iopub.execute_input":"2021-09-02T16:22:06.674667Z","iopub.status.idle":"2021-09-02T16:22:07.406660Z","shell.execute_reply.started":"2021-09-02T16:22:06.674621Z","shell.execute_reply":"2021-09-02T16:22:07.405441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# for layer in conv_base.layers:\n#     print(layer.name)","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:07.408446Z","iopub.execute_input":"2021-09-02T16:22:07.408916Z","iopub.status.idle":"2021-09-02T16:22:07.417771Z","shell.execute_reply.started":"2021-09-02T16:22:07.408872Z","shell.execute_reply":"2021-09-02T16:22:07.416559Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:07.423841Z","iopub.execute_input":"2021-09-02T16:22:07.424161Z","iopub.status.idle":"2021-09-02T16:22:07.435607Z","shell.execute_reply.started":"2021-09-02T16:22:07.424132Z","shell.execute_reply":"2021-09-02T16:22:07.434180Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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))) ","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:07.437423Z","iopub.execute_input":"2021-09-02T16:22:07.437933Z","iopub.status.idle":"2021-09-02T16:22:07.447847Z","shell.execute_reply.started":"2021-09-02T16:22:07.437889Z","shell.execute_reply":"2021-09-02T16:22:07.443845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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])","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:07.450251Z","iopub.execute_input":"2021-09-02T16:22:07.451181Z","iopub.status.idle":"2021-09-02T16:22:07.478660Z","shell.execute_reply.started":"2021-09-02T16:22:07.451119Z","shell.execute_reply":"2021-09-02T16:22:07.477137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2021-09-02T16:22:07.484259Z","iopub.execute_input":"2021-09-02T16:22:07.484626Z","iopub.status.idle":"2021-09-02T18:10:49.878023Z","shell.execute_reply.started":"2021-09-02T16:22:07.484597Z","shell.execute_reply":"2021-09-02T18:10:49.876868Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = model.predict(ds_valid, use_multiprocessing=True, workers=8, verbose=1, steps=1)","metadata":{"execution":{"iopub.status.busy":"2021-09-02T18:10:49.882779Z","iopub.execute_input":"2021-09-02T18:10:49.883115Z","iopub.status.idle":"2021-09-02T18:10:51.148851Z","shell.execute_reply.started":"2021-09-02T18:10:49.883084Z","shell.execute_reply":"2021-09-02T18:10:51.147890Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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]))","metadata":{"execution":{"iopub.status.busy":"2021-09-02T18:10:51.151566Z","iopub.execute_input":"2021-09-02T18:10:51.152044Z","iopub.status.idle":"2021-09-02T18:10:51.167766Z","shell.execute_reply.started":"2021-09-02T18:10:51.151996Z","shell.execute_reply":"2021-09-02T18:10:51.164601Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.evaluate(ds_valid)","metadata":{"execution":{"iopub.status.busy":"2021-09-02T18:10:51.170612Z","iopub.execute_input":"2021-09-02T18:10:51.171261Z","iopub.status.idle":"2021-09-02T18:12:11.047755Z","shell.execute_reply.started":"2021-09-02T18:10:51.171212Z","shell.execute_reply":"2021-09-02T18:12:11.046586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('my_model.h5')","metadata":{"execution":{"iopub.status.busy":"2021-09-02T18:12:11.049408Z","iopub.execute_input":"2021-09-02T18:12:11.049778Z","iopub.status.idle":"2021-09-02T18:12:11.665722Z","shell.execute_reply.started":"2021-09-02T18:12:11.049739Z","shell.execute_reply":"2021-09-02T18:12:11.664802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history.history","metadata":{"execution":{"iopub.status.busy":"2021-09-02T18:12:11.667501Z","iopub.execute_input":"2021-09-02T18:12:11.667962Z","iopub.status.idle":"2021-09-02T18:12:11.679653Z","shell.execute_reply.started":"2021-09-02T18:12:11.667920Z","shell.execute_reply":"2021-09-02T18:12:11.678177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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()","metadata":{"execution":{"iopub.status.busy":"2021-09-02T18:12:11.682305Z","iopub.execute_input":"2021-09-02T18:12:11.682922Z","iopub.status.idle":"2021-09-02T18:12:11.899368Z","shell.execute_reply.started":"2021-09-02T18:12:11.682876Z","shell.execute_reply":"2021-09-02T18:12:11.898185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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()","metadata":{"execution":{"iopub.status.busy":"2021-09-02T18:12:11.900965Z","iopub.execute_input":"2021-09-02T18:12:11.901667Z","iopub.status.idle":"2021-09-02T18:12:12.104167Z","shell.execute_reply.started":"2021-09-02T18:12:11.901624Z","shell.execute_reply":"2021-09-02T18:12:12.103071Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Submission","metadata":{}},{"cell_type":"code","source":"submission = pd.read_csv('../input/galaxy-zoo-the-galaxy-challenge/all_ones_benchmark.zip')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# submission = submission.sample(n=1000, random_state=0)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# y_pred = model.predict(test_x)\ny_pred = model.predict(ds_test, use_multiprocessing=True, workers=8, verbose=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.iloc[:, 1:] = y_pred","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}