{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":46105,"databundleVersionId":5087314,"sourceType":"competition"},{"sourceId":8487213,"sourceType":"datasetVersion","datasetId":5063087},{"sourceId":53630,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":44982}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# **IMPROVE THE MODEL**","metadata":{}},{"cell_type":"markdown","source":"I enasamble 4 Model and, I use kfold cross-validation to traing the model, the idea of using kfold is from [here](https://www.kaggle.com/competitions/asl-signs/discussion/406684).\n\n","metadata":{}},{"cell_type":"code","source":"!pip uninstall -y tensorflow tensorflow-addons keras\n!pip install tensorflow==2.12.0 keras==2.12.0 tensorflow-addons==0.19.0","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:06:47.154432Z","iopub.execute_input":"2024-05-22T15:06:47.154769Z","iopub.status.idle":"2024-05-22T15:10:52.130620Z","shell.execute_reply.started":"2024-05-22T15:06:47.154741Z","shell.execute_reply":"2024-05-22T15:10:52.129350Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport seaborn as sn\n\nfrom tensorflow import keras\nfrom tqdm.notebook import tqdm\nfrom sklearn.model_selection import train_test_split, GroupShuffleSplit \n\nimport glob\nimport sys\nimport os\nimport math\nimport gc\nimport sys\nimport sklearn\nimport scipy\nfrom sklearn.model_selection import KFold\n\nprint(f'Tensorflow V{tf.__version__}')\nprint(f'Keras V{tf.keras.__version__}')\nprint(f'Python V{sys.version}')","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:10:52.132633Z","iopub.execute_input":"2024-05-22T15:10:52.132959Z","iopub.status.idle":"2024-05-22T15:10:59.814646Z","shell.execute_reply.started":"2024-05-22T15:10:52.132930Z","shell.execute_reply":"2024-05-22T15:10:59.813461Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"PREPROCESS_DATA = False\nTRAIN_MODEL = True\nUSE_VAL = True\n\nN_ROWS = 543\nN_DIMS = 3\nDIM_NAMES = ['x', 'y', 'z']\nSEED = 42\nNUM_CLASSES = 250\nIS_INTERACTIVE = os.environ['KAGGLE_KERNEL_RUN_TYPE'] == 'Interactive'\nVERBOSE = 1 if IS_INTERACTIVE else 2\n\nINPUT_SIZE = 12 # WAS 64\nBATCH_ALL_SIGNS_N = 1 # WAS 4\nBATCH_SIZE = 256 # WAS 1024\nN_EPOCHS = 120 # WAS 250\nLR_MAX = 0.001\nN_WARMUP_EPOCHS = 0\nWD_RATIO = 0.05\nMASK_VAL = 4237\n\nN_MODELS = 4 # WAS 1\nDEBUG = False","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:10:59.815939Z","iopub.execute_input":"2024-05-22T15:10:59.816646Z","iopub.status.idle":"2024-05-22T15:10:59.824391Z","shell.execute_reply.started":"2024-05-22T15:10:59.816611Z","shell.execute_reply":"2024-05-22T15:10:59.823380Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Prints Shape and Dtype For List Of Variables\ndef print_shape_dtype(l, names):\n    for e, n in zip(l, names):\n        print(f'{n} shape: {e.shape}, dtype: {e.dtype}')","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:10:59.827079Z","iopub.execute_input":"2024-05-22T15:10:59.827573Z","iopub.status.idle":"2024-05-22T15:11:03.317991Z","shell.execute_reply.started":"2024-05-22T15:10:59.827535Z","shell.execute_reply":"2024-05-22T15:11:03.316974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# *Landmark Indices*","metadata":{}},{"cell_type":"code","source":"# Define Landmark Indices\nUSE_TYPES = ['left_hand', 'pose', 'right_hand']\nSTART_IDX = 468\nLIPS_IDXS0 = np.array([\n    61, 185, 40, 39, 37, 0, 267, 269, 270, 409,\n    291, 146, 91, 181, 84, 17, 314, 405, 321, 375,\n    78, 191, 80, 81, 82, 13, 312, 311, 310, 415,\n    95, 88, 178, 87, 14, 317, 402, 318, 324, 308,\n])\nLEFT_HAND_IDXS0 = np.arange(468, 489)\nRIGHT_HAND_IDXS0 = np.arange(522, 543)\nLEFT_POSE_IDXS0 = np.array([502, 504, 506, 508, 510])\nRIGHT_POSE_IDXS0 = np.array([503, 505, 507, 509, 511])\nLANDMARK_IDXS_LEFT_DOMINANT0 = np.concatenate((LIPS_IDXS0, LEFT_HAND_IDXS0, LEFT_POSE_IDXS0))\nLANDMARK_IDXS_RIGHT_DOMINANT0 = np.concatenate((LIPS_IDXS0, RIGHT_HAND_IDXS0, RIGHT_POSE_IDXS0))\nHAND_IDXS0 = np.concatenate((LEFT_HAND_IDXS0, RIGHT_HAND_IDXS0), axis=0)\nN_COLS = LANDMARK_IDXS_LEFT_DOMINANT0.size\nLIPS_IDXS = np.argwhere(np.isin(LANDMARK_IDXS_LEFT_DOMINANT0, LIPS_IDXS0)).squeeze()\nLEFT_HAND_IDXS = np.argwhere(np.isin(LANDMARK_IDXS_LEFT_DOMINANT0, LEFT_HAND_IDXS0)).squeeze()\nRIGHT_HAND_IDXS = np.argwhere(np.isin(LANDMARK_IDXS_LEFT_DOMINANT0, RIGHT_HAND_IDXS0)).squeeze()\nHAND_IDXS = np.argwhere(np.isin(LANDMARK_IDXS_LEFT_DOMINANT0, HAND_IDXS0)).squeeze()\nPOSE_IDXS = np.argwhere(np.isin(LANDMARK_IDXS_LEFT_DOMINANT0, LEFT_POSE_IDXS0)).squeeze()\nprint(f'# HAND_IDXS: {len(HAND_IDXS)}, N_COLS: {N_COLS}')","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:03.319310Z","iopub.execute_input":"2024-05-22T15:11:03.319614Z","iopub.status.idle":"2024-05-22T15:11:03.333702Z","shell.execute_reply.started":"2024-05-22T15:11:03.319585Z","shell.execute_reply":"2024-05-22T15:11:03.332667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"LIPS_START = 0\nLEFT_HAND_START = LIPS_IDXS.size\nRIGHT_HAND_START = LEFT_HAND_START + LEFT_HAND_IDXS.size\nPOSE_START = RIGHT_HAND_START + RIGHT_HAND_IDXS.size\nprint(f'LIPS_START: {LIPS_START}, LEFT_HAND_START: {LEFT_HAND_START}, RIGHT_HAND_START: {RIGHT_HAND_START}, POSE_START: {POSE_START}')","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:03.335049Z","iopub.execute_input":"2024-05-22T15:11:03.335418Z","iopub.status.idle":"2024-05-22T15:11:03.345443Z","shell.execute_reply.started":"2024-05-22T15:11:03.335391Z","shell.execute_reply":"2024-05-22T15:11:03.344394Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Process Data Tensorflow","metadata":{}},{"cell_type":"code","source":"ROWS_PER_FRAME = 543  \n\ndef load_relevant_data_subset(pq_path):\n    data_columns = ['x', 'y', 'z']\n    data = pd.read_parquet(pq_path, columns=data_columns)\n    n_frames = int(len(data) / ROWS_PER_FRAME)\n    data = data.values.reshape(n_frames, ROWS_PER_FRAME, len(data_columns))\n    return data.astype(np.float32)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:03.346721Z","iopub.execute_input":"2024-05-22T15:11:03.347177Z","iopub.status.idle":"2024-05-22T15:11:03.353449Z","shell.execute_reply.started":"2024-05-22T15:11:03.347118Z","shell.execute_reply":"2024-05-22T15:11:03.352609Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class PreprocessLayer(tf.keras.layers.Layer):\n    def __init__(self):\n        super(PreprocessLayer, self).__init__()\n        normalisation_correction = tf.constant([\n                    # Add 0.50 to left hand (original right hand) and substract 0.50 of right hand (original left hand)\n                    [0] * len(LIPS_IDXS) + [0.50] * len(LEFT_HAND_IDXS) + [0.50] * len(POSE_IDXS),\n                    # Y coordinates stay intact\n                    [0] * len(LANDMARK_IDXS_LEFT_DOMINANT0),\n                    # Z coordinates stay intact\n                    [0] * len(LANDMARK_IDXS_LEFT_DOMINANT0),\n                ],\n                dtype=tf.float32,\n            )\n        self.normalisation_correction = tf.transpose(normalisation_correction, [1,0])\n        \n    def pad_edge(self, t, repeats, side):\n        if side == 'LEFT':\n            return tf.concat((tf.repeat(t[:1], repeats=repeats, axis=0), t), axis=0)\n        elif side == 'RIGHT':\n            return tf.concat((t, tf.repeat(t[-1:], repeats=repeats, axis=0)), axis=0)\n    \n    @tf.function(\n        input_signature=(tf.TensorSpec(shape=[None,N_ROWS,N_DIMS], dtype=tf.float32),),\n    )\n    def call(self, data0):\n        \n        # TRUNCATE LONG VIDEOS\n        N_FRAMES0 = tf.shape(data0)[0]\n        data0 = tf.slice(data0, [0,0,0], [tf.math.minimum(INPUT_SIZE * INPUT_SIZE,N_FRAMES0),-1,-1])\n        \n        # Number of Frames in Video\n        N_FRAMES0 = tf.shape(data0)[0]\n        \n        # Find dominant hand by comparing summed absolute coordinates\n        left_hand_sum = tf.math.reduce_sum(tf.where(tf.math.is_nan(tf.gather(data0, LEFT_HAND_IDXS0, axis=1)), 0, 1))\n        right_hand_sum = tf.math.reduce_sum(tf.where(tf.math.is_nan(tf.gather(data0, RIGHT_HAND_IDXS0, axis=1)), 0, 1))\n        left_dominant = left_hand_sum >= right_hand_sum\n        \n        # Count non NaN Hand values in each frame for the dominant hand\n        if left_dominant:\n            frames_hands_non_nan_sum = tf.math.reduce_sum(\n                    tf.where(tf.math.is_nan(tf.gather(data0, LEFT_HAND_IDXS0, axis=1)), 0, 1),\n                    axis=[1, 2],\n                )\n        else:\n            frames_hands_non_nan_sum = tf.math.reduce_sum(\n                    tf.where(tf.math.is_nan(tf.gather(data0, RIGHT_HAND_IDXS0, axis=1)), 0, 1),\n                    axis=[1, 2],\n                )\n        \n        # Find frames indices with coordinates of dominant hand\n        non_empty_frames_idxs = tf.where(frames_hands_non_nan_sum > 0)\n        non_empty_frames_idxs = tf.squeeze(non_empty_frames_idxs, axis=1)\n        # Filter frames\n        data = tf.gather(data0, non_empty_frames_idxs, axis=0)\n        \n        # Cast Indices in float32 to be compatible with Tensorflow Lite\n        non_empty_frames_idxs = tf.cast(non_empty_frames_idxs, tf.float32)\n        # Normalize to start with 0\n        non_empty_frames_idxs -= tf.reduce_min(non_empty_frames_idxs)\n        \n        # Number of Frames in Filtered Video\n        N_FRAMES = tf.shape(data)[0]\n        \n        # Gather Relevant Landmark Columns\n        if left_dominant:\n            data = tf.gather(data, LANDMARK_IDXS_LEFT_DOMINANT0, axis=1)\n        else:\n            data = tf.gather(data, LANDMARK_IDXS_RIGHT_DOMINANT0, axis=1)\n            data = (\n                    self.normalisation_correction + (\n                        (data - self.normalisation_correction) * tf.where(self.normalisation_correction != 0, -1.0, 1.0))\n                )\n        \n        # Video fits in INPUT_SIZE\n        if N_FRAMES < INPUT_SIZE:\n            # Pad With -1 to indicate padding\n            non_empty_frames_idxs = tf.pad(non_empty_frames_idxs, [[0, INPUT_SIZE-N_FRAMES]], constant_values=-1)\n            # Pad Data With Zeros\n            data = tf.pad(data, [[0, INPUT_SIZE-N_FRAMES], [0,0], [0,0]], constant_values=0)\n            # Fill NaN Values With 0\n            data = tf.where(tf.math.is_nan(data), 0.0, data)\n            return data, non_empty_frames_idxs\n        # Video needs to be downsampled to INPUT_SIZE\n        else:\n            # Repeat\n            if N_FRAMES < INPUT_SIZE**2:\n                repeats = tf.math.floordiv(INPUT_SIZE * INPUT_SIZE, N_FRAMES0)\n                data = tf.repeat(data, repeats=repeats, axis=0)\n                non_empty_frames_idxs = tf.repeat(non_empty_frames_idxs, repeats=repeats, axis=0)\n\n            # Pad To Multiple Of Input Size\n            pool_size = tf.math.floordiv(len(data), INPUT_SIZE)\n            if tf.math.mod(len(data), INPUT_SIZE) > 0:\n                pool_size += 1\n\n            if pool_size == 1:\n                pad_size = (pool_size * INPUT_SIZE) - len(data)\n            else:\n                pad_size = (pool_size * INPUT_SIZE) % len(data)\n\n            # Pad Start/End with Start/End value\n            pad_left = tf.math.floordiv(pad_size, 2) + tf.math.floordiv(INPUT_SIZE, 2)\n            pad_right = tf.math.floordiv(pad_size, 2) + tf.math.floordiv(INPUT_SIZE, 2)\n            if tf.math.mod(pad_size, 2) > 0:\n                pad_right += 1\n\n            # Pad By Concatenating Left/Right Edge Values\n            data = self.pad_edge(data, pad_left, 'LEFT')\n            data = self.pad_edge(data, pad_right, 'RIGHT')\n\n            # Pad Non Empty Frame Indices\n            non_empty_frames_idxs = self.pad_edge(non_empty_frames_idxs, pad_left, 'LEFT')\n            non_empty_frames_idxs = self.pad_edge(non_empty_frames_idxs, pad_right, 'RIGHT')\n\n            # Reshape to Mean Pool\n            data = tf.reshape(data, [INPUT_SIZE, -1, N_COLS, N_DIMS])\n            non_empty_frames_idxs = tf.reshape(non_empty_frames_idxs, [INPUT_SIZE, -1])\n\n            # Mean Pool\n            data = tf.experimental.numpy.nanmean(data, axis=1)\n            non_empty_frames_idxs = tf.experimental.numpy.nanmean(non_empty_frames_idxs, axis=1)\n\n            # Fill NaN Values With 0\n            data = tf.where(tf.math.is_nan(data), 0.0, data)\n            \n            return data, non_empty_frames_idxs\n    \npreprocess_layer = PreprocessLayer()","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:03.355051Z","iopub.execute_input":"2024-05-22T15:11:03.355430Z","iopub.status.idle":"2024-05-22T15:11:03.578955Z","shell.execute_reply.started":"2024-05-22T15:11:03.355403Z","shell.execute_reply":"2024-05-22T15:11:03.578107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_data(file_path):\n    data = load_relevant_data_subset(file_path)\n    data = preprocess_layer(data)\n    return data","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:03.580079Z","iopub.execute_input":"2024-05-22T15:11:03.580383Z","iopub.status.idle":"2024-05-22T15:11:03.584979Z","shell.execute_reply.started":"2024-05-22T15:11:03.580359Z","shell.execute_reply":"2024-05-22T15:11:03.583961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def preprocess_data():\n    # Create arrays to save data\n    X = np.zeros([N_SAMPLES, INPUT_SIZE, N_COLS, N_DIMS], dtype=np.float32)\n    y = np.zeros([N_SAMPLES], dtype=np.int32)\n    NON_EMPTY_FRAME_IDXS = np.full([N_SAMPLES, INPUT_SIZE], -1, dtype=np.float32)\n\n    # Fill X/y\n    for row_idx, (file_path, sign_ord) in enumerate(tqdm(train[['file_path', 'sign_ord']].values)):\n        if row_idx % 5000 == 0:\n            print(f'Generated {row_idx}/{N_SAMPLES}')\n\n        data, non_empty_frame_idxs = get_data(file_path)\n        X[row_idx] = data\n        y[row_idx] = sign_ord\n        NON_EMPTY_FRAME_IDXS[row_idx] = non_empty_frame_idxs\n        if np.isnan(data).sum() > 0:\n            print(row_idx)\n            return data\n\n    # Save the entire dataset\n    np.save(ROOT_DIR+'/X.npy', X)\n    np.save(ROOT_DIR+'/y.npy', y)\n    np.save(ROOT_DIR+'/NON_EMPTY_FRAME_IDXS.npy', NON_EMPTY_FRAME_IDXS)\n\n    # Create K-Folds\n    kf = KFold(n_splits=4, shuffle=True, random_state=42)\n    for fold, (_, fold_idxs) in enumerate(kf.split(X)):\n        # Get data for the current fold\n        X_fold = X[fold_idxs]\n        NON_EMPTY_FRAME_IDXS_FOLD = NON_EMPTY_FRAME_IDXS[fold_idxs]\n        y_fold = y[fold_idxs]\n\n        # Save the fold data\n        np.save(ROOT_DIR+f'/X_fold{fold}.npy', X_fold)\n        np.save(ROOT_DIR+f'/y_fold{fold}.npy', y_fold)\n        np.save(ROOT_DIR+f'/NON_EMPTY_FRAME_IDXS_FOLD{fold}.npy', NON_EMPTY_FRAME_IDXS_FOLD)\n\n        # Print the shapes of the splits\n        print(f'Fold {fold} - X_fold shape: {X_fold.shape}')\n        print(f'Fold {fold} - y_fold shape: {y_fold.shape}')","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:03.589394Z","iopub.execute_input":"2024-05-22T15:11:03.589674Z","iopub.status.idle":"2024-05-22T15:11:03.600767Z","shell.execute_reply.started":"2024-05-22T15:11:03.589650Z","shell.execute_reply":"2024-05-22T15:11:03.600022Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Read Training Data\nif (not PREPROCESS_DATA) or DEBUG:\n    train = pd.read_csv('/kaggle/input/asl-signs/train.csv').sample(int(5e3), random_state=SEED)\nelse:\n    train = pd.read_csv('/kaggle/input/asl-signs/train.csv')\n\nN_SAMPLES = len(train)\nprint(f'N_SAMPLES: {N_SAMPLES}')\nprint(train)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:03.601932Z","iopub.execute_input":"2024-05-22T15:11:03.602212Z","iopub.status.idle":"2024-05-22T15:11:03.844007Z","shell.execute_reply.started":"2024-05-22T15:11:03.602189Z","shell.execute_reply":"2024-05-22T15:11:03.843011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_file_path(path):\n    return f'/kaggle/input/asl-signs/{path}'\n\ntrain['file_path'] = train['path'].apply(get_file_path)\ntrain['sign_ord'] = train['sign'].astype('category').cat.codes\nORD2SIGN = train[['sign_ord', 'sign']].set_index('sign_ord').squeeze().to_dict()","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:03.845459Z","iopub.execute_input":"2024-05-22T15:11:03.846185Z","iopub.status.idle":"2024-05-22T15:11:03.870515Z","shell.execute_reply.started":"2024-05-22T15:11:03.846131Z","shell.execute_reply":"2024-05-22T15:11:03.869714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Preprocess All Data From Scratch\nif PREPROCESS_DATA:\n    ROOT_DIR = '/kaggle/working/processed_data_fold'\n    os.mkdir(ROOT_DIR)\n    preprocess_data()\nelse:\n    ROOT_DIR = '/kaggle/input/folds-data0/Folds_data'\n    X_train = np.load(f'{ROOT_DIR}/X.npy')\n    y_train = np.load(f'{ROOT_DIR}/y.npy')\n    NON_EMPTY_FRAME_IDXS_TRAIN = np.load(f'{ROOT_DIR}/NON_EMPTY_FRAME_IDXS_FOLD0.npy')","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:03.873562Z","iopub.execute_input":"2024-05-22T15:11:03.874055Z","iopub.status.idle":"2024-05-22T15:11:09.394196Z","shell.execute_reply.started":"2024-05-22T15:11:03.874029Z","shell.execute_reply":"2024-05-22T15:11:09.393311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Compute Landmark Means and STDs","metadata":{}},{"cell_type":"code","source":"def get_lips_mean_std():\n    # LIPS\n    LIPS_MEAN_X = np.zeros([LIPS_IDXS.size], dtype=np.float32)\n    LIPS_MEAN_Y = np.zeros([LIPS_IDXS.size], dtype=np.float32)\n    LIPS_STD_X = np.zeros([LIPS_IDXS.size], dtype=np.float32)\n    LIPS_STD_Y = np.zeros([LIPS_IDXS.size], dtype=np.float32)\n\n    for col, ll in enumerate(tqdm( np.transpose(X_train[:,:,LIPS_IDXS], [2,3,0,1]).reshape([LIPS_IDXS.size, N_DIMS, -1]) )):\n        for dim, l in enumerate(ll):\n            v = l[np.nonzero(l)]\n            if dim == 0: # X\n                LIPS_MEAN_X[col] = v.mean()\n                LIPS_STD_X[col] = v.std()\n            if dim == 1: # Y\n                LIPS_MEAN_Y[col] = v.mean()\n                LIPS_STD_Y[col] = v.std()\n\n\n    LIPS_MEAN = np.array([LIPS_MEAN_X, LIPS_MEAN_Y]).T\n    LIPS_STD = np.array([LIPS_STD_X, LIPS_STD_Y]).T\n    \n    return LIPS_MEAN, LIPS_STD\n\nLIPS_MEAN, LIPS_STD = get_lips_mean_std()","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:09.395300Z","iopub.execute_input":"2024-05-22T15:11:09.395582Z","iopub.status.idle":"2024-05-22T15:11:11.855082Z","shell.execute_reply.started":"2024-05-22T15:11:09.395558Z","shell.execute_reply":"2024-05-22T15:11:11.854070Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_left_right_hand_mean_std():\n    # LEFT HAND\n    LEFT_HANDS_MEAN_X = np.zeros([LEFT_HAND_IDXS.size], dtype=np.float32)\n    LEFT_HANDS_MEAN_Y = np.zeros([LEFT_HAND_IDXS.size], dtype=np.float32)\n    LEFT_HANDS_STD_X = np.zeros([LEFT_HAND_IDXS.size], dtype=np.float32)\n    LEFT_HANDS_STD_Y = np.zeros([LEFT_HAND_IDXS.size], dtype=np.float32)\n\n\n    for col, ll in enumerate(tqdm( np.transpose(X_train[:,:,LEFT_HAND_IDXS], [2,3,0,1]).reshape([LEFT_HAND_IDXS.size, N_DIMS, -1]) )):\n        for dim, l in enumerate(ll):\n            v = l[np.nonzero(l)]\n            if dim == 0: # X\n                LEFT_HANDS_MEAN_X[col] = v.mean()\n                LEFT_HANDS_STD_X[col] = v.std()\n            if dim == 1: # Y\n                LEFT_HANDS_MEAN_Y[col] = v.mean()\n                LEFT_HANDS_STD_Y[col] = v.std()\n\n\n    LEFT_HANDS_MEAN = np.array([LEFT_HANDS_MEAN_X, LEFT_HANDS_MEAN_Y]).T\n    LEFT_HANDS_STD = np.array([LEFT_HANDS_STD_X, LEFT_HANDS_STD_Y]).T\n    \n    return LEFT_HANDS_MEAN, LEFT_HANDS_STD\n\nLEFT_HANDS_MEAN, LEFT_HANDS_STD = get_left_right_hand_mean_std()","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:11.856380Z","iopub.execute_input":"2024-05-22T15:11:11.856680Z","iopub.status.idle":"2024-05-22T15:11:13.165940Z","shell.execute_reply.started":"2024-05-22T15:11:11.856655Z","shell.execute_reply":"2024-05-22T15:11:13.164893Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_pose_mean_std():\n    # POSE\n    POSE_MEAN_X = np.zeros([POSE_IDXS.size], dtype=np.float32)\n    POSE_MEAN_Y = np.zeros([POSE_IDXS.size], dtype=np.float32)\n    POSE_STD_X = np.zeros([POSE_IDXS.size], dtype=np.float32)\n    POSE_STD_Y = np.zeros([POSE_IDXS.size], dtype=np.float32)\n\n    #fig, axes = plt.subplots(3, 1, figsize=(15, N_DIMS*6))\n\n    for col, ll in enumerate(tqdm( np.transpose(X_train[:,:,POSE_IDXS], [2,3,0,1]).reshape([POSE_IDXS.size, N_DIMS, -1]) )):\n        for dim, l in enumerate(ll):\n            v = l[np.nonzero(l)]\n            if dim == 0: # X\n                POSE_MEAN_X[col] = v.mean()\n                POSE_STD_X[col] = v.std()\n            if dim == 1: # Y\n                POSE_MEAN_Y[col] = v.mean()\n                POSE_STD_Y[col] = v.std()\n\n\n    POSE_MEAN = np.array([POSE_MEAN_X, POSE_MEAN_Y]).T\n    POSE_STD = np.array([POSE_STD_X, POSE_STD_Y]).T\n    \n    return POSE_MEAN, POSE_STD\n\nPOSE_MEAN, POSE_STD = get_pose_mean_std()","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:13.167408Z","iopub.execute_input":"2024-05-22T15:11:13.167822Z","iopub.status.idle":"2024-05-22T15:11:13.506655Z","shell.execute_reply.started":"2024-05-22T15:11:13.167787Z","shell.execute_reply":"2024-05-22T15:11:13.505718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Loader with Augmentation","metadata":{}},{"cell_type":"code","source":"TIME_AUG_PROB = 0.25\nFRAME_DROP_PROB = 0.0\n\n# Custom sampler to get a batch containing N times all signs\ndef get_train_batch_all_signs(X, y, NON_EMPTY_FRAME_IDXS, n=BATCH_ALL_SIGNS_N):\n    # Arrays to store batch in\n    X_batch = np.zeros([NUM_CLASSES*n, INPUT_SIZE, N_COLS, N_DIMS], dtype=np.float32)\n    y_batch = np.arange(0, NUM_CLASSES, step=1/n, dtype=np.float32).astype(np.int64)\n    non_empty_frame_idxs_batch = np.zeros([NUM_CLASSES*n, INPUT_SIZE], dtype=np.float32)\n    \n    # Dictionary mapping ordinally encoded sign to corresponding sample indices\n    CLASS2IDXS = {}\n    for i in range(NUM_CLASSES):\n        CLASS2IDXS[i] = np.argwhere(y == i).squeeze().astype(np.int32)\n            \n    while True:\n        # Fill batch arrays\n        for i in range(NUM_CLASSES):\n            idxs = np.random.choice(CLASS2IDXS[i], n)\n            tmp = X[idxs].copy()\n            tmp2 = NON_EMPTY_FRAME_IDXS[idxs].copy()\n            \n            # FRAME DROP AUGMENTATION\n            if np.random.uniform(0,1)<FRAME_DROP_PROB:\n                j = np.random.randint(0,INPUT_SIZE)\n                tmp[0,j,:,:] = 0\n            \n            # TIME SCALE AUGMENTATION\n            if np.random.uniform(0,1)<TIME_AUG_PROB:\n                ct = ( NON_EMPTY_FRAME_IDXS[idxs[0]] != -1 ).sum()\n                if (ct==12):\n                    mask = np.random.choice([True, False],12)\n                    mask[0] = True\n                    mask[-1] = True\n                    c = mask.sum()\n                    tmp[0,:c,:,:] = tmp[0,mask,:,:]\n                    tmp[0,c:,:,:] = 0\n                    tmp2[0,:c] = tmp2[0,mask]\n                    tmp2[0,c:] = -1\n                elif ct>6:\n                    tmp[0,:6,:,:] = tmp[0,::2,:,:]\n                    tmp[0,6:,:,:] = 0\n                    tmp2[0,:6] = tmp2[0,::2]\n                    tmp2[0,6:] = -1\n                elif (ct<=2)&(np.random.uniform(0,1)<0.3):\n                    tmp[0,::6,:,:] = tmp[0,:2,:,:]\n                    tmp[0,1::6,:,:] = tmp[0,:2,:,:]\n                    tmp[0,2::6,:,:] = tmp[0,:2,:,:]\n                    tmp[0,3::6,:,:] = tmp[0,:2,:,:]\n                    tmp[0,4::6,:,:] = tmp[0,:2,:,:]\n                    tmp[0,5::6,:,:] = tmp[0,:2,:,:]\n                    tmp2[0,::6] = tmp2[0,:2]\n                    tmp2[0,1::6] = tmp2[0,:2]\n                    tmp2[0,2::6] = tmp2[0,:2]\n                    tmp2[0,3::6] = tmp2[0,:2]\n                    tmp2[0,4::6] = tmp2[0,:2]\n                    tmp2[0,5::6] = tmp2[0,:2]\n                elif (ct<=3)&(np.random.uniform(0,1)<0.3):\n                    tmp[0,::4,:,:] = tmp[0,:3,:,:]\n                    tmp[0,1::4,:,:] = tmp[0,:3,:,:]\n                    tmp[0,2::4,:,:] = tmp[0,:3,:,:]\n                    tmp[0,3::4,:,:] = tmp[0,:3,:,:]\n                    tmp2[0,::4] = tmp2[0,:3]\n                    tmp2[0,1::4] = tmp2[0,:3]\n                    tmp2[0,2::4] = tmp2[0,:3]\n                    tmp2[0,3::4] = tmp2[0,:3]\n                elif (ct<=4)&(np.random.uniform(0,1)<0.3):\n                    tmp[0,::3,:,:] = tmp[0,:4,:,:]\n                    tmp[0,1::3,:,:] = tmp[0,:4,:,:]\n                    tmp[0,2::3,:,:] = tmp[0,:4,:,:]\n                    tmp2[0,::3] = tmp2[0,:4]\n                    tmp2[0,1::3] = tmp2[0,:4]\n                    tmp2[0,2::3] = tmp2[0,:4]\n                else:\n                    tmp[0,::2,:,:] = tmp[0,:6,:,:]\n                    tmp[0,1::2,:,:] = tmp[0,:6,:,:]\n                    tmp2[0,::2] = tmp2[0,:6]\n                    tmp2[0,1::2] = tmp2[0,:6]\n            \n            X_batch[i*n:(i+1)*n] = tmp\n            non_empty_frame_idxs_batch[i*n:(i+1)*n] = tmp2\n        \n        yield { 'frames': X_batch, 'non_empty_frame_idxs': non_empty_frame_idxs_batch }, y_batch","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:13.508038Z","iopub.execute_input":"2024-05-22T15:11:13.508425Z","iopub.status.idle":"2024-05-22T15:11:13.536915Z","shell.execute_reply.started":"2024-05-22T15:11:13.508398Z","shell.execute_reply":"2024-05-22T15:11:13.535855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Config","metadata":{}},{"cell_type":"code","source":"LAYER_NORM_EPS = 1e-6\n\nLIPS_UNITS = 224 \nHANDS_UNITS = 224 \nPOSE_UNITS = 224 \nUNITS = 376 \n\n# Transformer\nNUM_BLOCKS = 3 \nMLP_RATIO = 3 \n\nEMBEDDING_DROPOUT = 0.10\nMLP_DROPOUT_RATIO = 0.30 \nCLASSIFIER_DROPOUT_RATIO = 0.10\nINIT_HE_UNIFORM = tf.keras.initializers.he_uniform\nINIT_GLOROT_UNIFORM = tf.keras.initializers.glorot_uniform\nINIT_ZEROS = tf.keras.initializers.constant(0.0)\n\nGELU = tf.keras.activations.gelu","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:13.538090Z","iopub.execute_input":"2024-05-22T15:11:13.538435Z","iopub.status.idle":"2024-05-22T15:11:13.551603Z","shell.execute_reply.started":"2024-05-22T15:11:13.538409Z","shell.execute_reply":"2024-05-22T15:11:13.550267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Define Transformer Model","metadata":{}},{"cell_type":"code","source":"def scaled_dot_product(q,k,v, softmax, attention_mask):\n    #calculates Q . K(transpose)\n    qkt = tf.matmul(q,k,transpose_b=True)\n    #caculates scaling factor\n    dk = tf.math.sqrt(tf.cast(q.shape[-1],dtype=tf.float32))\n    scaled_qkt = qkt/dk\n    softmax = softmax(scaled_qkt, mask=attention_mask)\n    \n    z = tf.matmul(softmax,v)\n    #shape: (m,Tx,depth), same shape as q,k,v\n    return z\n\nclass MultiHeadAttention(tf.keras.layers.Layer):\n    def __init__(self,d_model,num_of_heads):\n        super(MultiHeadAttention,self).__init__()\n        self.d_model = d_model\n        self.num_of_heads = num_of_heads\n        self.depth = d_model//num_of_heads\n        self.wq = [tf.keras.layers.Dense(self.depth) for i in range(num_of_heads)]\n        self.wk = [tf.keras.layers.Dense(self.depth) for i in range(num_of_heads)]\n        self.wv = [tf.keras.layers.Dense(self.depth) for i in range(num_of_heads)]\n        self.wo = tf.keras.layers.Dense(d_model)\n        self.softmax = tf.keras.layers.Softmax()\n        \n    def call(self,x, attention_mask):\n        \n        multi_attn = []\n        for i in range(self.num_of_heads):\n            Q = self.wq[i](x)\n            K = self.wk[i](x)\n            V = self.wv[i](x)\n            multi_attn.append(scaled_dot_product(Q,K,V, self.softmax, attention_mask))\n            \n        multi_head = tf.concat(multi_attn,axis=-1)\n        multi_head_attention = self.wo(multi_head)\n        return multi_head_attention","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:13.552688Z","iopub.execute_input":"2024-05-22T15:11:13.552934Z","iopub.status.idle":"2024-05-22T15:11:13.564495Z","shell.execute_reply.started":"2024-05-22T15:11:13.552913Z","shell.execute_reply":"2024-05-22T15:11:13.563688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Full Transformer\nclass Transformer(tf.keras.Model):\n    def __init__(self, num_blocks):\n        super(Transformer, self).__init__(name='transformer')\n        self.num_blocks = num_blocks\n    \n    def build(self, input_shape):\n        self.ln_1s = []\n        self.mhas = []\n        self.ln_2s = []\n        self.mlps = []\n        # Make Transformer Blocks\n        for i in range(self.num_blocks):\n            # Multi Head Attention\n            self.mhas.append(MultiHeadAttention(UNITS, 8))\n            # Multi Layer Perception\n            self.mlps.append(tf.keras.Sequential([\n                tf.keras.layers.Dense(UNITS * MLP_RATIO, activation=GELU, kernel_initializer=INIT_GLOROT_UNIFORM),\n                tf.keras.layers.Dropout(MLP_DROPOUT_RATIO),\n                tf.keras.layers.Dense(UNITS, kernel_initializer=INIT_HE_UNIFORM),\n            ]))\n        \n    def call(self, x, attention_mask):\n        # Iterate input over transformer blocks\n        for mha, mlp in zip(self.mhas, self.mlps):\n            x = x + mha(x, attention_mask)\n            x = x + mlp(x)\n    \n        return x","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:13.565703Z","iopub.execute_input":"2024-05-22T15:11:13.566065Z","iopub.status.idle":"2024-05-22T15:11:13.575840Z","shell.execute_reply.started":"2024-05-22T15:11:13.566035Z","shell.execute_reply":"2024-05-22T15:11:13.574973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class LandmarkEmbedding(tf.keras.Model):\n    def __init__(self, units, name):\n        super(LandmarkEmbedding, self).__init__(name=f'{name}_embedding')\n        self.units = units\n        \n    def build(self, input_shape):\n        # Embedding for missing landmark in frame, initizlied with zeros\n        self.empty_embedding = self.add_weight(\n            name=f'{self.name}_empty_embedding',\n            shape=[self.units],\n            initializer=INIT_ZEROS,\n        )\n        # Embedding\n        self.dense = tf.keras.Sequential([\n            tf.keras.layers.Dense(self.units, name=f'{self.name}_dense_1', use_bias=False, kernel_initializer=INIT_GLOROT_UNIFORM),\n            tf.keras.layers.Activation(GELU),\n            tf.keras.layers.Dense(self.units, name=f'{self.name}_dense_2', use_bias=False, kernel_initializer=INIT_HE_UNIFORM),\n        ], name=f'{self.name}_dense')\n\n    def call(self, x):\n        return tf.where(\n                # Checks whether landmark is missing in frame\n                tf.reduce_sum(x, axis=2, keepdims=True) == 0,\n                # If so, the empty embedding is used\n                self.empty_embedding,\n                # Otherwise the landmark data is embedded\n                self.dense(x),\n            )","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:13.576961Z","iopub.execute_input":"2024-05-22T15:11:13.577294Z","iopub.status.idle":"2024-05-22T15:11:13.588348Z","shell.execute_reply.started":"2024-05-22T15:11:13.577270Z","shell.execute_reply":"2024-05-22T15:11:13.587349Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Embedding(tf.keras.Model):\n    def __init__(self):\n        super(Embedding, self).__init__()\n        \n    def get_diffs(self, l):\n        S = l.shape[2]\n        other = tf.expand_dims(l, 3)\n        other = tf.repeat(other, S, axis=3)\n        other = tf.transpose(other, [0,1,3,2])\n        diffs = tf.expand_dims(l, 3) - other\n        diffs = tf.reshape(diffs, [-1, INPUT_SIZE, S*S])\n        return diffs\n\n    def build(self, input_shape):\n        # Positional Embedding, initialized with zeros\n        self.positional_embedding = tf.keras.layers.Embedding(INPUT_SIZE+1, UNITS, embeddings_initializer=INIT_ZEROS)\n        # Embedding layer for Landmarks\n        self.lips_embedding = LandmarkEmbedding(LIPS_UNITS, 'lips')\n        self.left_hand_embedding = LandmarkEmbedding(HANDS_UNITS, 'left_hand')\n        self.pose_embedding = LandmarkEmbedding(POSE_UNITS, 'pose')\n        # Landmark Weights\n        self.landmark_weights = tf.Variable(tf.zeros([3], dtype=tf.float32), name='landmark_weights')\n        # Fully Connected Layers for combined landmarks\n        self.fc = tf.keras.Sequential([\n            tf.keras.layers.Dense(UNITS, name='fully_connected_1', use_bias=False, kernel_initializer=INIT_GLOROT_UNIFORM),\n            tf.keras.layers.Activation(GELU),\n            tf.keras.layers.Dense(UNITS, name='fully_connected_2', use_bias=False, kernel_initializer=INIT_HE_UNIFORM),\n        ], name='fc')\n\n\n    def call(self, lips0, left_hand0, pose0, non_empty_frame_idxs, training=False):\n        # Lips\n        lips_embedding = self.lips_embedding(lips0)\n        # Left Hand\n        left_hand_embedding = self.left_hand_embedding(left_hand0)\n        # Pose\n        pose_embedding = self.pose_embedding(pose0)\n        # Merge Embeddings of all landmarks with mean pooling\n        x = tf.stack((\n            lips_embedding, left_hand_embedding, pose_embedding,\n        ), axis=3)\n        x = x * tf.nn.softmax(self.landmark_weights)\n        x = tf.reduce_sum(x, axis=3)\n        # Fully Connected Layers\n        x = self.fc(x)\n        # Add Positional Embedding\n        max_frame_idxs = tf.clip_by_value(\n                tf.reduce_max(non_empty_frame_idxs, axis=1, keepdims=True),\n                1,\n                np.PINF,\n            )\n        normalised_non_empty_frame_idxs = tf.where(\n            tf.math.equal(non_empty_frame_idxs, -1.0),\n            INPUT_SIZE,\n            tf.cast(\n                non_empty_frame_idxs / max_frame_idxs * INPUT_SIZE,\n                tf.int32,\n            ),\n        )\n        x = x + self.positional_embedding(normalised_non_empty_frame_idxs)\n        \n        return x","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:13.589805Z","iopub.execute_input":"2024-05-22T15:11:13.590086Z","iopub.status.idle":"2024-05-22T15:11:13.604485Z","shell.execute_reply.started":"2024-05-22T15:11:13.590063Z","shell.execute_reply":"2024-05-22T15:11:13.603607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Loss Function","metadata":{}},{"cell_type":"code","source":"def scce_with_ls(y_true, y_pred):\n    # One Hot Encode Sparsely Encoded Target Sign\n    y_true = tf.cast(y_true, tf.int32)\n    y_true = tf.one_hot(y_true, NUM_CLASSES, axis=1)\n    y_true = tf.squeeze(y_true, axis=2)\n    # Categorical Crossentropy with native label smoothing support\n    return tf.keras.losses.categorical_crossentropy(y_true, y_pred, label_smoothing=0.25)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:13.605778Z","iopub.execute_input":"2024-05-22T15:11:13.606174Z","iopub.status.idle":"2024-05-22T15:11:13.615807Z","shell.execute_reply.started":"2024-05-22T15:11:13.606125Z","shell.execute_reply":"2024-05-22T15:11:13.614876Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build Model","metadata":{}},{"cell_type":"code","source":"def get_model():\n    # Inputs\n    frames = tf.keras.layers.Input([INPUT_SIZE, N_COLS, N_DIMS], dtype=tf.float32, name='frames')\n    non_empty_frame_idxs = tf.keras.layers.Input([INPUT_SIZE], dtype=tf.float32, name='non_empty_frame_idxs')\n    # Padding Mask\n    mask0 = tf.cast(tf.math.not_equal(non_empty_frame_idxs, -1), tf.float32)\n    mask = tf.expand_dims(mask0, axis=2)\n\n    x = frames\n    x = tf.slice(x, [0,0,0,0], [-1,INPUT_SIZE, N_COLS, 2])\n    # LIPS\n    lips = tf.slice(x, [0,0,LIPS_START,0], [-1,INPUT_SIZE, 40, 2])\n    lips = tf.where(\n            tf.math.equal(lips, 0.0),\n            0.0,\n            (lips - LIPS_MEAN) / LIPS_STD,\n        )\n    # LEFT HAND\n    left_hand = tf.slice(x, [0,0,40,0], [-1,INPUT_SIZE, 21, 2])\n    left_hand = tf.where(\n            tf.math.equal(left_hand, 0.0),\n            0.0,\n            (left_hand - LEFT_HANDS_MEAN) / LEFT_HANDS_STD,\n        )\n    # POSE\n    pose = tf.slice(x, [0,0,61,0], [-1,INPUT_SIZE, 5, 2])\n    pose = tf.where(\n            tf.math.equal(pose, 0.0),\n            0.0,\n            (pose - POSE_MEAN) / POSE_STD,\n        )\n    \n    # Flatten\n    lips = tf.reshape(lips, [-1, INPUT_SIZE, 40*2])\n    left_hand = tf.reshape(left_hand, [-1, INPUT_SIZE, 21*2])\n    pose = tf.reshape(pose, [-1, INPUT_SIZE, 5*2])\n        \n    # Embedding\n    x = Embedding()(lips, left_hand, pose, non_empty_frame_idxs)\n    x = Transformer(NUM_BLOCKS)(x, mask)\n    \n    # Pooling\n    x = tf.reduce_sum(x * mask, axis=1) / tf.reduce_sum(mask, axis=1)\n    # Classifier Dropout\n    x = tf.keras.layers.Dropout(CLASSIFIER_DROPOUT_RATIO)(x)\n    # Classification Layer\n    x = tf.keras.layers.Dense(NUM_CLASSES, activation=tf.keras.activations.softmax, kernel_initializer=INIT_GLOROT_UNIFORM)(x)\n    \n    outputs = x\n    \n    # Create Tensorflow Model\n    model = tf.keras.models.Model(inputs=[frames, non_empty_frame_idxs], outputs=outputs)\n    \n    # Sparse Categorical Cross Entropy With Label Smoothing\n    loss = scce_with_ls\n    optimizer = tfa.optimizers.AdamW(learning_rate=1e-3, weight_decay=1e-5, clipnorm=1.0)\n    # TopK Metrics\n    metrics = [\n        tf.keras.metrics.SparseCategoricalAccuracy(name='acc'),\n        tf.keras.metrics.SparseTopKCategoricalAccuracy(k=5, name='top_5_acc'),\n        tf.keras.metrics.SparseTopKCategoricalAccuracy(k=10, name='top_10_acc'),\n    ]\n    \n    model.compile(loss=loss, optimizer=optimizer, metrics=metrics)\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:13.617131Z","iopub.execute_input":"2024-05-22T15:11:13.617600Z","iopub.status.idle":"2024-05-22T15:11:13.637242Z","shell.execute_reply.started":"2024-05-22T15:11:13.617571Z","shell.execute_reply":"2024-05-22T15:11:13.636280Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Learning Rate Scheduler","metadata":{}},{"cell_type":"code","source":"def lrfn(current_step, num_warmup_steps, lr_max, num_cycles=0.50, num_training_steps=N_EPOCHS):\n    if current_step < num_warmup_steps:\n        if WARMUP_METHOD == 'log':\n            return lr_max * 0.10 ** (num_warmup_steps - current_step)\n        else:\n            return lr_max * 2 ** -(num_warmup_steps - current_step)\n    else:\n        progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))\n        return max(0.0, 0.5 * (1.0 + math.cos(math.pi * float(num_cycles) * 2.0 * progress))) * lr_max\n\nLR_SCHEDULE = [lrfn(step, num_warmup_steps=N_WARMUP_EPOCHS, lr_max=LR_MAX, num_cycles=0.50, num_training_steps=N_EPOCHS) for step in range(N_EPOCHS)]\nlr_callback = tf.keras.callbacks.LearningRateScheduler(lambda step: LR_SCHEDULE[min(step, len(LR_SCHEDULE)-1)], verbose=1)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:13.638639Z","iopub.execute_input":"2024-05-22T15:11:13.638977Z","iopub.status.idle":"2024-05-22T15:11:13.649436Z","shell.execute_reply.started":"2024-05-22T15:11:13.638940Z","shell.execute_reply":"2024-05-22T15:11:13.648480Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Weight Decay Callback","metadata":{}},{"cell_type":"code","source":"# Custom callback to update weight decay with learning rate\nclass WeightDecayCallback(tf.keras.callbacks.Callback):\n    def __init__(self, wd_ratio=WD_RATIO):\n        self.step_counter = 0\n        self.wd_ratio = wd_ratio\n    \n    def on_epoch_begin(self, epoch, logs=None):\n        model.optimizer.weight_decay = model.optimizer.learning_rate * self.wd_ratio\n        #print(f'learning rate: {model.optimizer.learning_rate.numpy():.2e}, weight decay: {model.optimizer.weight_decay.numpy():.2e}')","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:13.650696Z","iopub.execute_input":"2024-05-22T15:11:13.651002Z","iopub.status.idle":"2024-05-22T15:11:13.658643Z","shell.execute_reply.started":"2024-05-22T15:11:13.650977Z","shell.execute_reply":"2024-05-22T15:11:13.657694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train 4 Models","metadata":{}},{"cell_type":"code","source":"ROOT_DIR = '/kaggle/input/folds-data0/Folds_data'\n\nfolds_data = {}\nfor i in range(4):\n    folds_data[i] = {\n        'X': np.load(f'{ROOT_DIR}/X_fold{i}.npy'),\n        'y': np.load(f'{ROOT_DIR}/y_fold{i}.npy'),\n        'NON_EMPTY_FRAME_IDXS': np.load(f'{ROOT_DIR}/NON_EMPTY_FRAME_IDXS_FOLD{i}.npy')\n    }","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:13.660014Z","iopub.execute_input":"2024-05-22T15:11:13.660723Z","iopub.status.idle":"2024-05-22T15:11:19.064984Z","shell.execute_reply.started":"2024-05-22T15:11:13.660685Z","shell.execute_reply":"2024-05-22T15:11:19.063986Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm import tqdm\n\nif TRAIN_MODEL:\n    models = []\n    \n    for k in range(4):\n        print('#'*25)\n        print('### Training Model', k, '...')\n        print('#'*25)\n\n        # Clear all models in GPU\n        VERBOSE = 0\n        VERBOSE2 = 0\n        if k == 0:\n            tf.keras.backend.clear_session()\n            VERBOSE = 2\n            VERBOSE2 = 1\n\n        # Determine validation fold\n        val_fold = k\n        train_folds = [f for f in range(4) if f != val_fold]\n        \n        # Print the fold file name used for validation\n        print(f'Validation fold for model {k}: fold{val_fold}')\n\n        # Collect training and validation data\n        X_train = np.concatenate([folds_data[f]['X'] for f in train_folds], axis=0)\n        y_train = np.concatenate([folds_data[f]['y'] for f in train_folds], axis=0)\n        NON_EMPTY_FRAME_IDXS_TRAIN = np.concatenate([folds_data[f]['NON_EMPTY_FRAME_IDXS'] for f in train_folds], axis=0)\n        \n        X_val = folds_data[val_fold]['X']\n        y_val = folds_data[val_fold]['y']\n        NON_EMPTY_FRAME_IDXS_VAL = folds_data[val_fold]['NON_EMPTY_FRAME_IDXS']\n\n        validation_data = ({'frames': X_val, 'non_empty_frame_idxs': NON_EMPTY_FRAME_IDXS_VAL}, y_val)\n\n        # Get new fresh model\n        model = get_model()\n\n        # Actual Training\n        lr_callback = tf.keras.callbacks.LearningRateScheduler(lambda step: LR_SCHEDULE[step], verbose=VERBOSE2)\n        \n        with tqdm(total=N_EPOCHS, desc=f'Training Model {k}') as pbar:\n            class ProgressCallback(tf.keras.callbacks.Callback):\n                def on_epoch_end(self, epoch, logs=None):\n                    pbar.update(1)\n        \n            history = model.fit(\n                x=get_train_batch_all_signs(X_train, y_train, NON_EMPTY_FRAME_IDXS_TRAIN),\n                steps_per_epoch=len(X_train) // (NUM_CLASSES * BATCH_ALL_SIGNS_N),\n                epochs=N_EPOCHS,\n                batch_size=BATCH_SIZE,\n                validation_data=validation_data,\n                callbacks=[\n                    lr_callback,\n                    WeightDecayCallback(),\n                    ProgressCallback()\n                ],\n                verbose=VERBOSE,\n            )\n\n        # Save Model Weights\n        model.save_weights(f'model{k}.h5')\n        models.append(model)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:19.070673Z","iopub.execute_input":"2024-05-22T15:11:19.070984Z","iopub.status.idle":"2024-05-22T15:11:19.077373Z","shell.execute_reply.started":"2024-05-22T15:11:19.070957Z","shell.execute_reply":"2024-05-22T15:11:19.076387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Create Submission\n\nSubmission code loosley based on [this notebook](https://www.kaggle.com/code/dschettler8845/gislr-learn-eda-baseline#baseline) by [Darien Schettler\n](https://www.kaggle.com/dschettler8845)","metadata":{}},{"cell_type":"code","source":"# TFLite model for submission\nclass TFLiteModel(tf.Module):\n    def __init__(self, models):\n        super(TFLiteModel, self).__init__()\n\n        # Load the feature generation and main models\n        self.preprocess_layer = preprocess_layer\n        self.models = models\n    \n    @tf.function(input_signature=[tf.TensorSpec(shape=[None, N_ROWS, N_DIMS], dtype=tf.float32, name='inputs')])\n    def __call__(self, inputs):\n        # Preprocess Data\n        x, non_empty_frame_idxs = self.preprocess_layer(inputs)\n        # Add Batch Dimension\n        x = tf.expand_dims(x, axis=0)\n        non_empty_frame_idxs = tf.expand_dims(non_empty_frame_idxs, axis=0)\n        \n        # Make Prediction\n        outputs = []\n        for k in range(len(self.models)):\n            output = self.models[k]({ 'frames': x, 'non_empty_frame_idxs': non_empty_frame_idxs })\n            # Squeeze Output 1x250 -> 250\n            output = tf.squeeze(output, axis=0)\n            outputs.append(output)\n        outputs = tf.math.reduce_mean( outputs, axis=0 )\n\n        # Return a dictionary with the output tensor\n        return {'outputs': outputs}\n\n# Define TF Lite Model\ntflite_keras_model = TFLiteModel(models)\n\n# Sanity Check\ndemo_raw_data = load_relevant_data_subset(train['file_path'].values[5])\nprint(f'demo_raw_data shape: {demo_raw_data.shape}, dtype: {demo_raw_data.dtype}')\ndemo_output = tflite_keras_model(demo_raw_data)[\"outputs\"]\nprint(f'demo_output shape: {demo_output.shape}, dtype: {demo_output.dtype}')\ndemo_prediction = demo_output.numpy().argmax()\nprint(f'demo_prediction: {demo_prediction}, correct: {train.iloc[0][\"sign_ord\"]}')","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:19.978915Z","iopub.status.idle":"2024-05-22T15:11:19.979408Z","shell.execute_reply.started":"2024-05-22T15:11:19.979135Z","shell.execute_reply":"2024-05-22T15:11:19.979171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create Model Converter\nkeras_model_converter = tf.lite.TFLiteConverter.from_keras_model(tflite_keras_model)\n\n# QUANTIZE\nQUANTIZE = 'fp16'\nif QUANTIZE in [\"int8\", \"fp16\"]:\n    keras_model_converter.optimizations = [tf.lite.Optimize.DEFAULT]\n    if QUANTIZE == \"fp16\":\n        keras_model_converter.target_spec.supported_types = [tf.float16]\n\n# Convert Model\ntflite_model = keras_model_converter.convert()\n# Write Model\nwith open('/kaggle/working/model.tflite', 'wb') as f:\n    f.write(tflite_model)\n    \n# Zip Model\n!zip submission.zip /kaggle/working/model.tflite","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:19.982762Z","iopub.status.idle":"2024-05-22T15:11:19.983273Z","shell.execute_reply.started":"2024-05-22T15:11:19.983014Z","shell.execute_reply":"2024-05-22T15:11:19.983034Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Verify TFLite model can be loaded and used for prediction\n!pip install tflite-runtime\nimport tflite_runtime.interpreter as tflite\n\ninterpreter = tflite.Interpreter(\"/kaggle/working/model.tflite\")\nfound_signatures = list(interpreter.get_signature_list().keys())\nprediction_fn = interpreter.get_signature_runner(\"serving_default\")\n\noutput = prediction_fn(inputs=demo_raw_data)\nsign = output['outputs'].argmax()\n\nprint(\"PRED : \", ORD2SIGN.get(sign), f'[{sign}]')\nprint(\"TRUE : \", train.sign.values[0], f'[{train.sign_ord.values[0]}]')","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:11:19.985230Z","iopub.status.idle":"2024-05-22T15:11:19.985701Z","shell.execute_reply.started":"2024-05-22T15:11:19.985463Z","shell.execute_reply":"2024-05-22T15:11:19.985482Z"},"trusted":true},"execution_count":null,"outputs":[]}]}