{"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":"import tensorflow as tf\nfrom tensorflow.keras.layers import Layer, Input\nimport numpy as np\nimport pandas as pd\nimport json\nfrom Levenshtein import distance\n\n# Print the versions of TensorFlow and Python\nprint(\"Tensorflow\", tf.__version__)\n!python --version\n\n# Define constants\nbasedir = \"/kaggle/working/\"\nNUM_CHARACTERS = 59\nSEL_FEATURES = ['x_right_hand_0','y_right_hand_0']","metadata":{"execution":{"iopub.status.busy":"2023-06-03T02:53:39.77112Z","iopub.execute_input":"2023-06-03T02:53:39.771584Z","iopub.status.idle":"2023-06-03T02:53:51.34054Z","shell.execute_reply.started":"2023-06-03T02:53:39.771548Z","shell.execute_reply":"2023-06-03T02:53:51.338947Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Function to load data\ndef load_data(path):\n    try:\n        return pd.read_csv(path)\n    except FileNotFoundError:\n        print(f\"File not found at {path}\")\n        return None\n\n# Load training data\ndf_train = load_data('/kaggle/input/asl-fingerspelling/train.csv')","metadata":{"execution":{"iopub.status.busy":"2023-06-03T02:53:51.343147Z","iopub.execute_input":"2023-06-03T02:53:51.344615Z","iopub.status.idle":"2023-06-03T02:53:51.525989Z","shell.execute_reply.started":"2023-06-03T02:53:51.344572Z","shell.execute_reply":"2023-06-03T02:53:51.524608Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Function to load JSON mappings\ndef load_json(path):\n    try:\n        with open(path, 'r') as f:\n            return json.load(f)\n    except FileNotFoundError:\n        print(f\"File not found at {path}\")\n        return None\n\n# Load JSON mappings\nc2p = load_json('/kaggle/input/asl-fingerspelling/character_to_prediction_index.json')\np2c = {p: c for c, p in c2p.items()}\n\n# Compute total length of all phrases in the training set\nally = df_train['phrase'].values\ntotaly = sum([len(y) for y in ally])\n\n# Function to evaluate a constant prediction on the training set\ndef eval_string(s):\n    d = 0\n    for y in ally:\n        d += distance(s, y)\n    return (totaly - d) / totaly","metadata":{"execution":{"iopub.status.busy":"2023-06-03T02:53:51.527494Z","iopub.execute_input":"2023-06-03T02:53:51.528047Z","iopub.status.idle":"2023-06-03T02:53:51.558899Z","shell.execute_reply.started":"2023-06-03T02:53:51.528009Z","shell.execute_reply":"2023-06-03T02:53:51.557628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Greedy algorithm to find the best constant prediction string\ndef find_best_str():\n    best_str = ''\n    best_score = 0\n    chars = list(c2p.keys())\n\n    for i in range(20): # max length\n        inner_best = best_str\n        inner_best_score = best_score\n\n        for position in range(len(best_str)+1): # at all insertion points\n            for newchar in chars:               # try all characters\n                new_str = best_str[:position] + str(newchar) + best_str[position:]\n                score = eval_string(new_str)\n\n                if score > inner_best_score:\n                    inner_best = new_str\n                    inner_best_score = score\n                    print(f'New best @ {len(inner_best)}=\"{inner_best}\", score {inner_best_score:.4f}')\n\n        if best_score >= inner_best_score:\n            print('No improvement, best is', best_str)\n            return best_str, best_score\n\n        best_str = inner_best\n        best_score = inner_best_score\n        print(f'Best str @ {len(best_str)}=\"{best_str}\", score {best_score:.4f}')\n\n    return best_str, best_score\n\nbest_str, best_score = find_best_str()","metadata":{"execution":{"iopub.status.busy":"2023-06-03T02:53:51.561465Z","iopub.execute_input":"2023-06-03T02:53:51.562438Z","iopub.status.idle":"2023-06-03T02:58:37.519448Z","shell.execute_reply.started":"2023-06-03T02:53:51.562396Z","shell.execute_reply":"2023-06-03T02:58:37.518296Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Function to convert the best string into one-hot encoded format\ndef convert_to_one_hot(s):\n    const_pred = np.zeros((len(s), NUM_CHARACTERS))\n    for i, c in enumerate(s):\n        const_pred[i, c2p[c]] = 1\n    return const_pred\n\nconst_pred = convert_to_one_hot(best_str)","metadata":{"execution":{"iopub.status.busy":"2023-06-03T02:58:37.52085Z","iopub.execute_input":"2023-06-03T02:58:37.521291Z","iopub.status.idle":"2023-06-03T02:58:37.527644Z","shell.execute_reply.started":"2023-06-03T02:58:37.52126Z","shell.execute_reply":"2023-06-03T02:58:37.526496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define a custom TensorFlow layer that always returns the constant prediction\nclass ConstantLayer(Layer):\n    def __init__(self, constant_vector, name=None):\n        super(ConstantLayer, self).__init__(name=name)\n        self.constant_vector = tf.Variable(initial_value=constant_vector, trainable=False, dtype=tf.float32)\n\n    def call(self, inputs):\n        return self.constant_vector\n\n# Build and compile the model\ninput_layer = Input(shape=(len(SEL_FEATURES),), name='inputs')\noutput_layer = ConstantLayer(const_pred, name='outputs')(input_layer)\nmodel = tf.keras.models.Model(inputs=input_layer, outputs=output_layer)\n\n# Convert the model to TFLite format\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\ntflite_model = converter.convert()\n","metadata":{"execution":{"iopub.status.busy":"2023-06-03T02:58:37.529332Z","iopub.execute_input":"2023-06-03T02:58:37.530069Z","iopub.status.idle":"2023-06-03T02:58:38.99893Z","shell.execute_reply.started":"2023-06-03T02:58:37.530034Z","shell.execute_reply":"2023-06-03T02:58:38.997838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Save the TFLite model to a file\ndef save_model(path, model):\n    try:\n        with open(path, 'wb') as f:\n            f.write(model)\n    except Exception as e:\n        print(f\"Unable to save the model due to: {e}\")\n\nmodel_path = 'model.tflite'\nsave_model(model_path, tflite_model)\n\n# Package the TFLite model and inference args into a ZIP file for submission\n!zip submission.zip  './model.tflite' './inference_args.json'","metadata":{"execution":{"iopub.status.busy":"2023-06-03T02:58:39.000491Z","iopub.execute_input":"2023-06-03T02:58:39.00086Z","iopub.status.idle":"2023-06-03T02:58:40.122258Z","shell.execute_reply.started":"2023-06-03T02:58:39.000826Z","shell.execute_reply":"2023-06-03T02:58:40.120715Z"},"trusted":true},"execution_count":null,"outputs":[]}]}