{"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-19T00:52:57.339172Z","iopub.execute_input":"2023-07-19T00:52:57.339624Z","iopub.status.idle":"2023-07-19T00:52:57.345936Z","shell.execute_reply.started":"2023-07-19T00:52:57.339576Z","shell.execute_reply":"2023-07-19T00:52:57.345136Z"},"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-19T00:52:57.347687Z","iopub.execute_input":"2023-07-19T00:52:57.348374Z","iopub.status.idle":"2023-07-19T00:52:57.374342Z","shell.execute_reply.started":"2023-07-19T00:52:57.348343Z","shell.execute_reply":"2023-07-19T00:52:57.373432Z"},"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-19T00:52:57.376222Z","iopub.execute_input":"2023-07-19T00:52:57.376816Z","iopub.status.idle":"2023-07-19T00:53:01.550595Z","shell.execute_reply.started":"2023-07-19T00:52:57.376783Z","shell.execute_reply":"2023-07-19T00:53:01.549285Z"},"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-19T00:53:01.552158Z","iopub.execute_input":"2023-07-19T00:53:01.552584Z","iopub.status.idle":"2023-07-19T00:53:48.356684Z","shell.execute_reply.started":"2023-07-19T00:53:01.552548Z","shell.execute_reply":"2023-07-19T00:53:48.355689Z"},"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-19T00:53:48.359253Z","iopub.execute_input":"2023-07-19T00:53:48.359908Z","iopub.status.idle":"2023-07-19T00:53:48.606127Z","shell.execute_reply.started":"2023-07-19T00:53:48.359876Z","shell.execute_reply":"2023-07-19T00:53:48.604985Z"},"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-19T00:53:48.607693Z","iopub.execute_input":"2023-07-19T00:53:48.608152Z","iopub.status.idle":"2023-07-19T01:14:59.200508Z","shell.execute_reply.started":"2023-07-19T00:53:48.608121Z","shell.execute_reply":"2023-07-19T01:14:59.196572Z"},"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-19T01:14:59.203091Z","iopub.execute_input":"2023-07-19T01:14:59.204658Z","iopub.status.idle":"2023-07-19T01:15:00.075447Z","shell.execute_reply.started":"2023-07-19T01:14:59.204584Z","shell.execute_reply":"2023-07-19T01:15:00.074571Z"},"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-19T01:15:00.076826Z","iopub.execute_input":"2023-07-19T01:15:00.077132Z","iopub.status.idle":"2023-07-19T01:15:48.291405Z","shell.execute_reply.started":"2023-07-19T01:15:00.077106Z","shell.execute_reply":"2023-07-19T01:15:48.290071Z"},"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-19T01:15:48.293237Z","iopub.execute_input":"2023-07-19T01:15:48.29398Z","iopub.status.idle":"2023-07-19T01:15:48.551233Z","shell.execute_reply.started":"2023-07-19T01:15:48.293938Z","shell.execute_reply":"2023-07-19T01:15:48.549893Z"},"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-19T01:15:48.553422Z","iopub.execute_input":"2023-07-19T01:15:48.554038Z","iopub.status.idle":"2023-07-19T01:15:54.997822Z","shell.execute_reply.started":"2023-07-19T01:15:48.554007Z","shell.execute_reply":"2023-07-19T01:15:54.996538Z"},"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-19T01:15:55.001971Z","iopub.execute_input":"2023-07-19T01:15:55.002342Z","iopub.status.idle":"2023-07-19T01:21:45.613048Z","shell.execute_reply.started":"2023-07-19T01:15:55.002312Z","shell.execute_reply":"2023-07-19T01:21:45.611875Z"},"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-19T01:21:45.61584Z","iopub.execute_input":"2023-07-19T01:21:45.616211Z","iopub.status.idle":"2023-07-19T01:21:45.971343Z","shell.execute_reply.started":"2023-07-19T01:21:45.61618Z","shell.execute_reply":"2023-07-19T01:21:45.970486Z"},"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-19T01:21:45.972748Z","iopub.execute_input":"2023-07-19T01:21:45.973954Z","iopub.status.idle":"2023-07-19T01:21:56.511262Z","shell.execute_reply.started":"2023-07-19T01:21:45.973909Z","shell.execute_reply":"2023-07-19T01:21:56.510072Z"},"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-19T01:21:56.512916Z","iopub.execute_input":"2023-07-19T01:21:56.513375Z","iopub.status.idle":"2023-07-19T01:21:56.793644Z","shell.execute_reply.started":"2023-07-19T01:21:56.513333Z","shell.execute_reply":"2023-07-19T01:21:56.79251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame(columns = ['Protein Id', 'GO Term Id','Prediction'])\ntest_protein_ids = np.load('/kaggle/input/t5embeds/test_ids.npy')\n\ngo_terms = pd.read_parquet(f'/kaggle/working/go_terms.parquet')\ngo_terms = go_terms['term'].values.tolist()\n\nl = []\nfor k in list(test_protein_ids):\n    l += [ k] * predictions.shape[1]   \n\nsubmission['Protein Id'] = l\nsubmission['GO Term Id'] = go_terms * predictions.shape[0]\nsubmission['Prediction'] = predictions.ravel()\nsubmission.to_csv(\"submission.tsv\",header=False, index=False, sep=\"\\t\")","metadata":{"execution":{"iopub.status.busy":"2023-07-19T01:21:56.795637Z","iopub.execute_input":"2023-07-19T01:21:56.79607Z","iopub.status.idle":"2023-07-19T01:38:50.607303Z","shell.execute_reply.started":"2023-07-19T01:21:56.796032Z","shell.execute_reply":"2023-07-19T01:38:50.605886Z"},"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-19T01:38:50.609642Z","iopub.execute_input":"2023-07-19T01:38:50.610161Z","iopub.status.idle":"2023-07-19T01:38:53.499846Z","shell.execute_reply.started":"2023-07-19T01:38:50.610117Z","shell.execute_reply":"2023-07-19T01:38:53.498721Z"},"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-19T01:38:53.501115Z","iopub.execute_input":"2023-07-19T01:38:53.501536Z","iopub.status.idle":"2023-07-19T01:38:53.515804Z","shell.execute_reply.started":"2023-07-19T01:38:53.501499Z","shell.execute_reply":"2023-07-19T01:38:53.51474Z"},"trusted":true},"execution_count":null,"outputs":[]}]}