{"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":"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)\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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install -q efficientnet","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Asthetics\nimport warnings\nimport sklearn.exceptions\nwarnings.filterwarnings('ignore', category=DeprecationWarning)\nwarnings.filterwarnings('ignore', category=FutureWarning)\nwarnings.filterwarnings(\"ignore\", category=sklearn.exceptions.UndefinedMetricWarning)\n\n# General\nfrom kaggle_datasets import KaggleDatasets\nfrom glob import glob\nimport pandas as pd\nimport numpy as np\nimport os\nimport time\nimport cv2\nimport random\nimport shutil\nimport math\nimport re\npd.set_option('display.max_columns', None)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Visualizations\nfrom PIL import Image\nfrom plotly.subplots import make_subplots\nfrom plotly.offline import iplot\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport cv2\nimport plotly.graph_objs as go\nimport plotly.figure_factory as ff\nimport plotly.express as px\n%matplotlib inline\nsns.set(style=\"whitegrid\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Machine Learning\n# Pre Procesing\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\n# Models\nfrom sklearn.model_selection import train_test_split, KFold\n# Deep Learning\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nimport efficientnet.tfkeras as efn\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import EfficientNetB4\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, BatchNormalization, GlobalAveragePooling2D\nfrom tensorflow.keras.callbacks import TensorBoard, EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.losses import CategoricalCrossentropy\nimport tensorflow_addons as tfa\nfrom tensorflow_addons.metrics import F1Score, FBetaScore\nfrom tensorflow_addons.callbacks import TQDMProgressBar\nfrom tensorflow.keras.utils import plot_model\n\n#Metrics\nfrom sklearn.metrics import confusion_matrix, classification_report, roc_auc_score\n\nprint('TF',tf.__version__)\n\n# Random Seed Fixing\nRANDOM_SEED = 42\n\ndef seed_everything(seed=RANDOM_SEED):\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    random.seed(seed)\n    tf.random.set_seed(seed)\n\nseed_everything()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# From https://www.kaggle.com/xhlulu/ranzcr-efficientnet-tpu-training\ndef auto_select_accelerator():\n    TPU_DETECTED = False\n    try:\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        tf.config.experimental_connect_to_cluster(tpu)\n        tf.tpu.experimental.initialize_tpu_system(tpu)\n        strategy = tf.distribute.experimental.TPUStrategy(tpu)\n        print(\"Running on TPU:\", tpu.master())\n        TPU_DETECTED =True\n    except ValueError:\n        strategy = tf.distribute.get_strategy()\n    print(f\"Running on {strategy.num_replicas_in_sync} replicas\")\n    \n    return strategy, TPU_DETECTED","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Model Params\nKFOLDS = 4\nIMG_SIZES = [256]*KFOLDS\nBATCH_SIZES = [64]*KFOLDS\nEPOCHS = [15]*KFOLDS\nEFF_NETS = [1]*KFOLDS # WHICH EFFICIENTNET B? TO USE\n\n# Model Eval Params\nDISPLAY_PLOT = True\n\n# Inference Params\nWGTS = [1/KFOLDS]*KFOLDS","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"strategy, TPU_DETECTED = auto_select_accelerator()\nAUTO = tf.data.experimental.AUTOTUNE\nREPLICAS = strategy.num_replicas_in_sync","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm.notebook import tqdm\n\nfiles_test_g = []\nfor i,k in tqdm([(0, 1), (2, 3), (4, 5), (6, 7)]):\n    GCS_PATH = KaggleDatasets().get_gcs_path(f'cqt-g2net-test-{i}-{k}')\n    files_test_g.extend(np.sort(np.array(tf.io.gfile.glob(GCS_PATH + '/test*.tfrec'))).tolist())\nnum_train_files = len(files_test_g)\nprint('test_files:',num_train_files)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_labeled_tfrecord(example):\n    tfrec_format = {\n        'image'                        : tf.io.FixedLenFeature([], tf.string),\n        'image_id'                     : tf.io.FixedLenFeature([], tf.string),\n        'target'                       : tf.io.FixedLenFeature([], tf.int64)\n    }           \n    example = tf.io.parse_single_example(example, tfrec_format)\n    return prepare_image(example['image']), tf.reshape(tf.cast(example['target'], tf.float32), [1])\n\n\ndef read_unlabeled_tfrecord(example, return_image_id):\n    tfrec_format = {\n        'image'                        : tf.io.FixedLenFeature([], tf.string),\n        'image_id'                     : tf.io.FixedLenFeature([], tf.string),\n    }\n    example = tf.io.parse_single_example(example, tfrec_format)\n    return prepare_image(example['image']), example['image_id'] if return_image_id else 0\n\n\ndef prepare_image(img, dim=IMG_SIZES[0]):    \n    img = tf.image.resize(tf.image.decode_png(img, channels=3), size=(dim, dim))\n    img = tf.cast(img, tf.float32) / 255.0\n    img = tf.reshape(img, [dim,dim, 3])\n            \n    return img\n\ndef count_data_items(fileids):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(fileid).group(1)) \n         for fileid in fileids]\n    return np.sum(n)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_dataset(files, shuffle = False, repeat = False, \n                labeled=True, return_image_ids=True, batch_size=16, dim=IMG_SIZES[0]):\n    \n    ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)\n    ds = ds.cache()\n    \n    if repeat:\n        ds = ds.repeat()\n    \n    if shuffle: \n        ds = ds.shuffle(1024*2)\n        opt = tf.data.Options()\n        opt.experimental_deterministic = False\n        ds = ds.with_options(opt)\n        \n    if labeled: \n        ds = ds.map(read_labeled_tfrecord, num_parallel_calls=AUTO)\n    else:\n        ds = ds.map(lambda example: read_unlabeled_tfrecord(example, return_image_ids), \n                    num_parallel_calls=AUTO)      \n    \n    ds = ds.batch(batch_size * REPLICAS)\n    ds = ds.prefetch(AUTO)\n    return ds","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EFNS = [efn.EfficientNetB0, efn.EfficientNetB1, efn.EfficientNetB2, efn.EfficientNetB3, \n        efn.EfficientNetB4, efn.EfficientNetB5, efn.EfficientNetB6, efn.EfficientNetB7]\n\ndef build_model(size, ef=0):\n    inp = tf.keras.layers.Input(shape=(size, size,3))\n    base = EFNS[ef](input_shape=(size,size,3),weights='imagenet',include_top=False)\n    \n    x = base(inp)\n    \n    x = tf.keras.layers.GlobalAvgPool2D()(x)\n    \n    x = tf.keras.layers.Dropout(0.)(x)\n    \n    x = tf.keras.layers.Dense(1,activation='sigmoid')(x)\n    model = tf.keras.Model(inputs=inp, outputs=x)\n    lr_decayed_fn = tf.keras.experimental.CosineDecay(\n                              6e-4,\n                              820*1,\n    )\n\n    opt = tfa.optimizers.AdamW(lr_decayed_fn, learning_rate=7e-4)\n    loss = tf.keras.losses.BinaryCrossentropy() \n    model.compile(optimizer=opt,loss=loss,metrics=['AUC'])\n    return model","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"skf = KFold(n_splits=KFOLDS,shuffle=True,random_state=RANDOM_SEED)\noof_pred = []; oof_tar = []; oof_val = []; oof_f1 = []; oof_ids = []; oof_folds = [] \n\nfiles_test_g = np.array(files_test_g)\n\nfor fold in range(0, KFOLDS):\n    \n    print('#'*25); print('#### FOLD',fold+1)\n    # BUILD MODEL\n    K.clear_session()\n    \n    with strategy.scope():\n        model = build_model(IMG_SIZES[fold], ef=EFF_NETS[fold])\n    print('\\tLoading model...')\n    \n    model.load_weights(f'../input/cqt-g2net-efficientnetb1-tpu-training/fold-{fold}.h5')  \n    \n    print('\\tPredict...')\n    ds_test = get_dataset(files_test_g,labeled=False,return_image_ids=True,\n            repeat=False,shuffle=False,dim=IMG_SIZES[fold],batch_size=BATCH_SIZES[fold]*2)\n    \n    \n    _oof_pred = []\n    _oof_tar = []\n    for img, target in tqdm(iter(ds_test)):\n        p = model.predict(img).flatten()\n        t = target.numpy().flatten()\n        _oof_pred.extend(p.tolist())\n        _oof_tar.extend(t.tolist())\n    oof_pred.append(np.array(_oof_pred).flatten())\n    oof_ids.append(np.array(_oof_tar).flatten())\n    sns.distplot(oof_pred[-1])\n    plt.show()               \n    print('\\tFinished...')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.read_csv('../input/g2net-gravitational-wave-detection/sample_submission.csv')\nsub['id'] = [t.decode(\"utf-8\") for t in oof_ids[-1]]\nsub['target'] = np.mean(oof_pred, axis=0)\nsub = sub.sort_values('id') \nsub.head()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub.to_csv('submission.csv', index=False)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}