{"cells":[{"metadata":{},"cell_type":"markdown","source":"### Why LSTMs?\n\nIdea is to somehow encode surrounding information with CNNs and then passing this to a LSTM for encoding the sequence\n\n### Adding a sense of Seqence to the Network\n\nMaybe combine CNN+LSTM or something new","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"Something like CNN+Sequences or Auto-regressive CNNs with final target","execution_count":null},{"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\nimport gc\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 5GB 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":"import tensorflow as tf\nfrom tensorflow.keras import layers as L\n\nfrom matplotlib import pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(\"/kaggle/input/conways-reverse-game-of-life-2020/train.csv\")\ntest_df = pd.read_csv(\"/kaggle/input/conways-reverse-game-of-life-2020/test.csv\")\n\nsample_submission = pd.read_csv(\"/kaggle/input/conways-reverse-game-of-life-2020/sample_submission.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head(2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"start_features = [f for f in train_df.columns if \"start\" in f]\nstop_features = [f for f in train_df.columns if \"stop\" in f]\n\nfeatures_in = stop_features+[\"delta\"]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Let's plot a sample","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"idx = 3\n\nfig, (ax1, ax2) = plt.subplots(1, 2)\nfig.suptitle(f'Delta: {train_df.loc[idx, \"delta\"]}')\nax1.imshow(1-(train_df.loc[idx, start_features].values).reshape(25, 25), cmap=\"gray\")\nax1.set_title(\"Start Setting\")\nax2.imshow(1-(train_df.loc[idx, stop_features].values).reshape(25, 25), cmap=\"gray\")\nax2.set_title(\"Stop Setting\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Keras dataset Sequence","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"bs=1\n\ntr_df = tf.data.Dataset.from_tensor_slices((\n    (train_df[\"delta\"].values, train_df[stop_features].values.reshape(-1, 25, 25, 1).astype(float)), \n    train_df[start_features].values.reshape(-1, 25, 25, 1).astype(float)))\n\ntr_df = tr_df.batch(bs)\n\n\ntst_df = tf.data.Dataset.from_tensor_slices((\n    (test_df[\"delta\"].values, test_df[stop_features].values.reshape(-1, 25, 25, 1).astype(float)), ))\n\ntst_df = tst_df.batch(bs)\n\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tst_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class LifeModel(tf.keras.Model):\n    \n    def __init__(self):\n        super(LifeModel, self).__init__()\n        \n        \n        self.encoder = L.Conv2D(8, kernel_size=(3,3), padding=\"SAME\")\n        self.memory = tf.keras.models.Sequential([\n            L.Conv2D(8, kernel_size=(3,3), padding=\"SAME\"),\n            L.BatchNormalization(),\n            L.ReLU(),\n            \n            L.Conv2D(8, kernel_size=(3,3), padding=\"SAME\"),\n            L.BatchNormalization(),\n            L.ReLU(),\n        ])\n        self.decoder = L.Conv2D(1, kernel_size=(3,3), padding=\"SAME\")\n        \n    def call(self, inputs):\n        \n        #print(inputs)\n        \n        delta = inputs[0]\n        stop_state = inputs[1]\n        \n        print(tf.reshape(delta, (-1,1)))\n        \n        x = self.encoder(stop_state-0.5)\n        x = tf.nn.relu(x)\n        \n        print(x.shape)\n        \n        #TODO: make this custom for each delta in a batch. \n        #Maybe a custom train_step in keras  model\n        stacked = tf.identity(x)\n        for i in range(tf.reduce_max(delta)):\n            x = self.memory(x)        \n        \n        #stacked = L.GlobalAveragePooling2D()(stacked)\n        x = self.decoder(x)\n        #x = tf.nn.relu(x)\n        x = tf.math.sigmoid(x)\n        \n        return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = LifeModel()\nmodel.compile(loss=\"bce\", optimizer=tf.keras.optimizers.Adam(), metrics=[\"accuracy\"])\n\n#ps = model(tr_data[0])\n#ps.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"model.fit(tr_df, epochs=5)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Let's take some samples","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"tr_data = next(iter(tr_df))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ps = model(tr_data[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ps.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"idx = 5\n\nfig, (ax1, ax2, ax3) = plt.subplots(1, 3)\nfig.suptitle(\"Delta: \"+str(tr_data[0][0][idx]))\n\nax1.imshow(1-(tr_data[0][1][idx].numpy().reshape(25, 25)), cmap=\"gray\")\nax1.set_title(\"Stop Setting\")\n\nax2.imshow(1-(tr_data[1][idx].numpy().reshape(25, 25)), cmap=\"gray\")\nax2.set_title(\"Start Setting\")\n\nax3.imshow(1-(ps[idx]>=0.5).numpy().reshape(25, 25), cmap=\"gray\")\nax3.set_title(\"Predicted Setting\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Generating output","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"ps = model.predict(tst_df, verbose=1)\nplt.imshow(1-(ps[0]>=0.5).reshape(25, 25), cmap=\"gray\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"THRESH = 0.5\n\nps_=(ps>=THRESH).astype(int).reshape(test_df.shape[0], -1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ps_.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = test_df[[\"id\"]].copy()\ntmp = pd.DataFrame(ps_, columns=start_features)\nsub = sub.join(tmp)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.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}