{"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":"# Set the hyperparameters\nlayers = 3\nnodes = 512\nact_func = 'relu'\nbatch_norm = False\noptimizer = 'Adam'  # Non-functional\neta = 0.001\nl2 = None\ndropout = None\nbatch_size = 5120\nepochs = 20\nnum_of_go_terms = 1500","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:06:04.955621Z","iopub.execute_input":"2023-07-19T19:06:04.956127Z","iopub.status.idle":"2023-07-19T19:06:04.992952Z","shell.execute_reply.started":"2023-07-19T19:06:04.956082Z","shell.execute_reply":"2023-07-19T19:06:04.991686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set up tensorflow\nimport os\nrandom_seed = 42\nos.environ['PYTHONHASHSEED'] = str(random_seed)\nos.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'\nos.environ['TF_GPU_ALLOCATOR'] = 'cuda_malloc_async'\n\n# Import libraries\nimport time\nimport random\nimport gc\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport progressbar\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Flatten, Dense, Activation, BatchNormalization, Dropout\nfrom keras import backend as K\n\n# Set random seeds\ntf.random.set_seed(random_seed)\nnp.random.seed(random_seed)\nrandom.seed(random_seed)","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:06:04.994761Z","iopub.execute_input":"2023-07-19T19:06:04.995114Z","iopub.status.idle":"2023-07-19T19:06:15.957311Z","shell.execute_reply.started":"2023-07-19T19:06:04.995086Z","shell.execute_reply":"2023-07-19T19:06:15.956203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Read the data\ntrain_terms = pd.read_csv(\"/kaggle/input/cafa-5-protein-function-prediction/Train/train_terms.tsv\", sep=\"\\t\")\n\n# # Explore the data\n# print(train_terms.shape)\n# train_terms.head()\n# train_terms.info()\n# train_terms.describe()","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:06:15.958632Z","iopub.execute_input":"2023-07-19T19:06:15.959397Z","iopub.status.idle":"2023-07-19T19:06:19.460854Z","shell.execute_reply.started":"2023-07-19T19:06:15.959357Z","shell.execute_reply":"2023-07-19T19:06:19.459036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"### Prepare X_train ###\n\n# Load the protein IDs\ntrain_protein_ids = np.load('/kaggle/input/t5embeds/train_ids.npy')\n\n# Load the embeddings\ntrain_embeddings = np.load('/kaggle/input/t5embeds/train_embeds.npy')\n\n# Create the training features from the embeddings\nX_train = pd.DataFrame(train_embeddings)\n\n# Convert column names to strings\nX_train.columns = X_train.columns.astype(str)\n\n# Convert to float32\nX_train = X_train.astype('float32')\n\n# Save the training features\nX_train.to_parquet(f'/kaggle/working/X_train.parquet')","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:06:19.46405Z","iopub.execute_input":"2023-07-19T19:06:19.464446Z","iopub.status.idle":"2023-07-19T19:07:07.82082Z","shell.execute_reply.started":"2023-07-19T19:06:19.464415Z","shell.execute_reply":"2023-07-19T19:07:07.819252Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clean up memory\ndel train_embeddings\ndel X_train\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:07:07.822334Z","iopub.execute_input":"2023-07-19T19:07:07.822741Z","iopub.status.idle":"2023-07-19T19:07:08.107094Z","shell.execute_reply.started":"2023-07-19T19:07:07.822699Z","shell.execute_reply":"2023-07-19T19:07:08.10511Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"### Prepare y_train ###\n\n# Get the first M labels\ngo_terms = train_terms['term'].value_counts().index[:num_of_go_terms].tolist()\n\n# Convert Go terms to series for performance\ngo_terms = pd.Series(go_terms)\n\n# Get train_terms data for the top M labels only\ntrain_terms_updated = train_terms.loc[train_terms['term'].isin(go_terms)]\ntrain_terms_updated.shape\n\n# Get the number of rows (N)\ntrain_size_N = train_protein_ids.shape[0]\ntrain_size_M = len(go_terms)\n\n# Create an empty matrix (N x M) for the labels\ny_train = np.zeros((train_size_N, num_of_go_terms))\n\n# Convert from numpy to pandas series for better handling\ntrain_protein_ids = pd.Series(train_protein_ids)\n\n# Create the progress bar\nbar = progressbar.ProgressBar(\n    maxval=num_of_go_terms,\n    widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])\n\n# Create a matrix of labels for each protein\nfor i in range(num_of_go_terms):\n\n    # Get the corresponding train_terms data for the current GO term\n    train_go_terms = train_terms_updated[train_terms_updated['term'] == go_terms[i]]\n\n    # Get all unique protein ids for the current GO term\n    related_protein_ids = train_go_terms['EntryID'].unique()\n\n    # Fill in the column with 1 if the protein is related to the current label, else 0\n    y_train[:, i] = train_protein_ids.isin(related_protein_ids).astype(float)\n    \n    # Update the progress bar\n    bar.update(i+1)\n\n# End the progress bar \nbar.finish()\n\n# Convert labels into aa pandas dataframe\ny_train = pd.DataFrame(data=y_train, columns=go_terms)\n\n# Convert to float32\ny_train = y_train.astype('float32')\n\n# Save labels to disk\ngo_terms = pd.DataFrame(go_terms, columns=['term'])\ngo_terms.to_parquet(f'/kaggle/working/go_terms.parquet')\n\n# Save the training data to disk\ny_train.to_parquet(f'/kaggle/working/y_train.parquet')","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:07:08.108764Z","iopub.execute_input":"2023-07-19T19:07:08.109158Z","iopub.status.idle":"2023-07-19T19:17:28.254855Z","shell.execute_reply.started":"2023-07-19T19:07:08.109128Z","shell.execute_reply":"2023-07-19T19:17:28.252458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clean up memory\ndel train_terms\ndel train_protein_ids\ndel train_terms_updated\ndel go_terms\ndel train_go_terms\ndel related_protein_ids\ndel y_train\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:17:28.258137Z","iopub.execute_input":"2023-07-19T19:17:28.258777Z","iopub.status.idle":"2023-07-19T19:17:29.425653Z","shell.execute_reply.started":"2023-07-19T19:17:28.25867Z","shell.execute_reply":"2023-07-19T19:17:29.421257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"### Prepare X_test ###\n\n# Get the test embeddings\ntest_embeddings = np.load('/kaggle/input/t5embeds/test_embeds.npy')\ntest_embeddings.shape\n\n# Convert test_embeddings to dataframe\nX_test = pd.DataFrame(test_embeddings)\n\n# Convert column names to strings\nX_test.columns = X_test.columns.astype(str)\n\n# Convert to float32\nX_test = X_test.astype('float32')\n\n# Save the test features\nX_test.to_parquet(f'/kaggle/working/X_test.parquet')","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:17:29.430204Z","iopub.execute_input":"2023-07-19T19:17:29.430984Z","iopub.status.idle":"2023-07-19T19:18:17.886656Z","shell.execute_reply.started":"2023-07-19T19:17:29.43092Z","shell.execute_reply":"2023-07-19T19:18:17.885082Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clean up memory\ndel test_embeddings\ndel X_test\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:18:17.889299Z","iopub.execute_input":"2023-07-19T19:18:17.890359Z","iopub.status.idle":"2023-07-19T19:18:18.338909Z","shell.execute_reply.started":"2023-07-19T19:18:17.890314Z","shell.execute_reply":"2023-07-19T19:18:18.337069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load features and labels from disk\nX_train = pd.read_parquet('/kaggle/working/X_train.parquet')\ny_train = pd.read_parquet(f'/kaggle/working/y_train.parquet')\n\n# Convert to float32\nX_train = X_train.astype('float32')\ny_train = y_train.astype('float32')\n\n# Get the input and output shapes\ninput_shape = [X_train.shape[1]]\noutput_shape = y_train.shape[1]\n\n# Create the model\nmodel = Sequential()\n\n# Add input layer\nmodel.add(BatchNormalization(input_shape=input_shape, name='input'))\nprint('Using batch normalization on input')\n\n# Add the hidden layers\nfor layer in range(layers):\n\n    # Add the hidden layer\n    if l2 is not None:\n        model.add(Dense(\n            units=nodes,\n            kernel_regularizer=tf.keras.regularizers.l2(l2)),\n            name=f'hidden_{layer}')\n        print('Using L2 regularization')\n    else:\n        model.add(Dense(units=nodes, name=f'hidden_{layer}'))\n        print('No L2 regularization')\n\n    # Add batch normalization\n    if batch_norm:\n        model.add(BatchNormalization())\n        print('Using batch norm on hidden layer')\n\n    # Add the activation function\n    model.add(Activation(act_func, name=f'activation_{layer}'))\n\n    # Add dropout\n    if dropout is not None:\n        model.add(Dropout(dropout))\n        print('Using dropout in hidden layer')\n\n# Add the output layer\nmodel.add(Dense(units=output_shape, activation='sigmoid', name='output'))\n\n# Compile the model\nmodel.compile(\n    optimizer=tf.keras.optimizers.Adam(\n        learning_rate=eta),\n    loss='binary_crossentropy')\n\n# Summarize the model\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:18:18.343354Z","iopub.execute_input":"2023-07-19T19:18:18.343795Z","iopub.status.idle":"2023-07-19T19:18:22.995053Z","shell.execute_reply.started":"2023-07-19T19:18:18.343749Z","shell.execute_reply":"2023-07-19T19:18:22.993107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train the model\nhistory = model.fit(\n    X_train, y_train,\n    #validation_split=0.2,\n    batch_size=batch_size,\n    epochs=epochs,\n    verbose=2)\n\n# Save the model\nmodel.save(f'/kaggle/working/model.h5')","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:18:22.996452Z","iopub.execute_input":"2023-07-19T19:18:22.996934Z","iopub.status.idle":"2023-07-19T19:23:56.779601Z","shell.execute_reply.started":"2023-07-19T19:18:22.996891Z","shell.execute_reply":"2023-07-19T19:23:56.77844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clean up memory\ndel X_train\ndel y_train\ndel model\ndel history\ntf.keras.backend.clear_session()\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:23:56.78138Z","iopub.execute_input":"2023-07-19T19:23:56.78187Z","iopub.status.idle":"2023-07-19T19:23:57.28472Z","shell.execute_reply.started":"2023-07-19T19:23:56.781825Z","shell.execute_reply":"2023-07-19T19:23:57.283858Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the model\nmodel = tf.keras.models.load_model('/kaggle/working/model.h5')\n\n# Load the test features\nX_test = pd.read_parquet('/kaggle/working/X_test.parquet')\n\n# Convert to float32\nX_test = X_test.astype('float32')\n\n# Make the predictions\npredictions = model.predict(X_test, batch_size=1024)\n\n# Convert to float32\npredictions = predictions.astype('float32')","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:23:57.286057Z","iopub.execute_input":"2023-07-19T19:23:57.286481Z","iopub.status.idle":"2023-07-19T19:24:06.500349Z","shell.execute_reply.started":"2023-07-19T19:23:57.286452Z","shell.execute_reply":"2023-07-19T19:24:06.499327Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clean up memory\ndel X_test\ntf.keras.backend.clear_session()\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:24:06.501548Z","iopub.execute_input":"2023-07-19T19:24:06.502333Z","iopub.status.idle":"2023-07-19T19:24:06.817924Z","shell.execute_reply.started":"2023-07-19T19:24:06.5023Z","shell.execute_reply":"2023-07-19T19:24:06.816644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create the submission table\nsubmission = pd.DataFrame(columns = ['Protein Id', 'GO Term Id','Prediction'])\n\n# Load the protein IDs\ntest_protein_ids = np.load('/kaggle/input/t5embeds/test_ids.npy')\n\n# Load the GO terms\ngo_terms = pd.read_parquet(f'/kaggle/working/go_terms.parquet')\ngo_terms = go_terms['term'].values.tolist()\n\n# Expand (broadcast) the list of protein IDs\nl = []\nfor k in list(test_protein_ids):\n    l += [k] * predictions.shape[1]\n\n# Create submission table\nsubmission['Protein Id'] = l\nsubmission['GO Term Id'] = go_terms * predictions.shape[0]\nsubmission['Prediction'] = predictions.ravel()","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:24:06.819428Z","iopub.execute_input":"2023-07-19T19:24:06.819892Z","iopub.status.idle":"2023-07-19T19:25:29.963478Z","shell.execute_reply.started":"2023-07-19T19:24:06.819852Z","shell.execute_reply":"2023-07-19T19:25:29.962401Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Save the submission file\nsubmission.to_csv(\n    f'submission.tsv',\n    sep='\\t',\n    float_format='%.3f',\n    index=False,\n    header=False)","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:25:29.964872Z","iopub.execute_input":"2023-07-19T19:25:29.965197Z","iopub.status.idle":"2023-07-19T19:38:12.10844Z","shell.execute_reply.started":"2023-07-19T19:25:29.965169Z","shell.execute_reply":"2023-07-19T19:38:12.107114Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clean up memory\ndel predictions\ndel l\ndel test_protein_ids\ndel go_terms\ndel submission\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:38:12.109907Z","iopub.execute_input":"2023-07-19T19:38:12.110267Z","iopub.status.idle":"2023-07-19T19:38:15.318682Z","shell.execute_reply.started":"2023-07-19T19:38:12.110237Z","shell.execute_reply":"2023-07-19T19:38:15.31785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\n\n# Get a copy of the global variables dictionary\nglobal_vars = globals().copy()\n\n# Iterate over all variables in memory\nfor var_name, var_value in global_vars.items():\n    # Exclude special variables and modules\n    if not var_name.startswith('__') and not hasattr(var_value, '__call__'):\n        # Get the size of the variable\n        var_size = sys.getsizeof(var_value)\n        # Print the variable name and its size\n        print(f\"Variable: {var_name} | Size: {var_size} bytes\")","metadata":{"execution":{"iopub.status.busy":"2023-07-19T19:38:15.31992Z","iopub.execute_input":"2023-07-19T19:38:15.320408Z","iopub.status.idle":"2023-07-19T19:38:15.329315Z","shell.execute_reply.started":"2023-07-19T19:38:15.32038Z","shell.execute_reply":"2023-07-19T19:38:15.327104Z"},"trusted":true},"execution_count":null,"outputs":[]}]}