{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n        \nimport tensorflow.keras.layers as L\nimport tensorflow.keras.models as M\nfrom keras.applications.resnet50 import ResNet50\nimport tensorflow as tf\n\nfrom transformers import BertConfig,TFBertModel,BertModel\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/conways-reverse-game-of-life-2020/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y = train[[x for x in train.columns if 'start' in x]].replace(0,-1)\ntrain = np.resize(train[[x for x in train.columns if 'stop' in x]].replace(0,-1).values,(50000,512))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test= pd.read_csv('/kaggle/input/conways-reverse-game-of-life-2020/train.csv')\ntest = np.resize(test[[x for x in test.columns if 'stop' in x]].replace(0,-1).values,(50000,512))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.shape,y.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_model(MAX_LEN = 512, NUM_BINS = len(np.unique(train))):\n    ids = L.Input((MAX_LEN,), dtype=tf.int32)\n    config = BertConfig() \n    config.vocab_size = NUM_BINS\n    config.num_hidden_layers = 2\n    bert_model = TFBertModel(config=config)\n\n    x = bert_model(ids)[0]\n    x = L.Flatten()(x)\n    x = L.Dense(625,activation='tanh')(x)\n    \n    model = M.Model(inputs=ids, outputs=x)\n#     optimizer = tf.keras.optimizers.Adam(learning_rate=1e-4)\n    model.compile(loss=tf.keras.losses.Hinge(reduction=\"auto\", name=\"hinge\"), optimizer='adam',metrics = 'mae')\n\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def NN():\n#     start = L.Input((625,))\n#     embed = L.Embedding(2,25,input_length=625)\n# #     image_tensor = L.Reshape((25,25,1))(start)\n    \n# #     conv = L.Conv2D(3,(3,3),padding='same')(image_tensor) \n\n# #     res = ResNet50(weights=None, include_top=False)\n# #     res.layers.pop()\n# #     for layer in res.layers:\n# #         layer.trainable = True\n# #     fe = M.Model(inputs=res.inputs, outputs=res.layers[-1].output)\n\n# #     out = fe(conv)\n# #     flat = L.Flatten()(embed)\n# #     stop = L.Dense(625,activation='tanh')(flat)\n# #     stop = L.Reshape((625,1))(stop)\n# # # #     stop = L.Activation(activation='sigmoid')(stop)\n#     stop = L.Flatten()(embed)\n# #     stop = tf.math.round(stop)\n#     stop = L.Dense(625,activation='relu')(stop)\n#     model = M.Model(start,embed)\n#     model.compile(loss='mae',optimizer='adam',metrics = 'mae')\n#     return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# with strategy.scope():\nwith tf.device('/gpu:0'):\n    clf = build_model()\n    clf.fit(train,y,epochs = 2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"clf.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# with strategy.scope():\npreds = clf.predict(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.min(preds),np.max(preds)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.unique(preds)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = np.where(preds>0,1,0).astype(int)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# preds = np.clip(np.round(preds),0,1).astype(int)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.bincount(np.where(y.values.ravel()>0,1,0).astype(int))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"26294051/4955949","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.bincount(preds.ravel().astype(int))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"31200000/50000","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.DataFrame(preds).describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = 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":"sub[[x for x in sub.columns.tolist() if 'start' in x]] = preds ","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}