{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":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)\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport seaborn as sns\nimport tensorflow as tf\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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"df = pd.read_csv('../input/conways-reverse-game-of-life-2020/train.csv')\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x = df.iloc[:,1].value_counts()\nsns.barplot(x.index, x.values)\nplt.title('Delta distribution')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Helper Functions","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\ndef create_model():\n    model = tf.keras.Sequential([\n    tf.keras.layers.InputLayer(input_shape=(625,1)),\n    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64,return_sequences=True)),\n    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64,return_sequences=True)),\n    tf.keras.layers.Dense(1, activation='sigmoid')\n    ])\n    \n    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy','mae'])\n    \n    return model\n\n\"\"\"\ndef create_model():\n    model = tf.keras.Sequential([\n    tf.keras.layers.InputLayer(input_shape=(25,25,1)),\n    tf.keras.layers.Conv2D(625,3,padding='same'),\n    tf.keras.layers.GlobalMaxPooling2D(),\n    #tf.keras.layers.GlobalAveragePooling1D(),\n    tf.keras.layers.Lambda(lambda x: tf.expand_dims(x,axis=2)),\n    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64,return_sequences=True)),\n    #tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32,return_sequences=True)),\n    tf.keras.layers.Dense(1, activation='sigmoid')\n    ])\n    \n    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy','mae'])\n    \n    return model\n\"\"\"\n\n\ndef create_dataset(df):\n    \n    X = df.iloc[:,627:]\n    y = df.iloc[:,2:627]\n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.00000001, random_state=42)\n    \n    X_train = np.expand_dims(X_train,axis=2)\n    #X_train = X_train.values.reshape(X_train.values.shape[0],25,25,1)\n    \n    BUFFER_SIZE = len(X_train)\n    \n    dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)).shuffle(BUFFER_SIZE)\n    dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)\n    \n    return dataset\n\nx = create_model()\nx.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Training","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"## Creating Separate Model for each Delta\n\nBATCH_SIZE = 64\nmodels = []\nhistories = []\nEPOCHS = 15\n\nfor delta in range(5):\n    \n    data = df[df.delta==delta+1]\n    dataset = create_dataset(data)\n    model = create_model()\n    \n    print(\"For Delta: {}\".format(delta+1))\n    print(\"______________________________\")\n    \n    history = model.fit(dataset,epochs=EPOCHS)\n    \n    histories.append(history)\n    models.append(model)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Prediction","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test = pd.read_csv('../input/conways-reverse-game-of-life-2020/test.csv')\n\nsubmission_cols = df.iloc[:,2:627].columns\nthreshold = 0.5\ndf_created = False\n\nfor delta in range(5):\n    \n    print(\"Predicting output for Delta: {}\".format(delta+1))\n    \n    data = df_test[df_test.delta==delta+1]\n    x = np.expand_dims(data.iloc[:,2:].values,axis=2)\n    \n    pred = models[delta].predict(x)[:, :, 0]\n    pred = np.where(pred>threshold,1,0)\n    \n    ## Creating Dataframe of Predictions\n    if not df_created:\n        result = pd.DataFrame(pred,columns=submission_cols)\n        id_col = data['id'].reset_index(drop=True)\n        result.insert(0,\"id\",list(id_col.values))\n        df_created = True\n    else:\n        temp = pd.DataFrame(pred,columns=submission_cols)\n        id_col = data['id'].reset_index(drop=True)\n        temp.insert(0,\"id\",list(id_col.values))\n        result = pd.concat([result,temp], axis=0,ignore_index=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Submission","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"result = result.sort_values(by='id')\nresult.to_csv('submission.csv',index=False)\n\nresult","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### If there is any mistake in the code, please let me know in the comment section I would really appreciate that. Thank you!","execution_count":null},{"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}