{"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-15T16:13:20.712095Z","iopub.execute_input":"2023-07-15T16:13:20.712694Z","iopub.status.idle":"2023-07-15T16:13:20.767341Z","shell.execute_reply.started":"2023-07-15T16:13:20.71264Z","shell.execute_reply":"2023-07-15T16:13:20.766129Z"},"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\n\n# Set random seeds\ntf.random.set_seed(random_seed)\nnp.random.seed(random_seed)\nrandom.seed(random_seed)\n\n# 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-15T16:13:20.769631Z","iopub.execute_input":"2023-07-15T16:13:20.770452Z","iopub.status.idle":"2023-07-15T16:13:35.749873Z","shell.execute_reply.started":"2023-07-15T16:13:20.77042Z","shell.execute_reply":"2023-07-15T16:13:35.748679Z"},"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')\ntrain_protein_ids.shape\n\n# Load the embeddings\ntrain_embeddings = np.load('/kaggle/input/t5embeds/train_embeds.npy')\ntrain_embeddings.shape\n\n# Create the training features from the embeddings\nX_train = pd.DataFrame(train_embeddings)\nX_train.columns = X_train.columns.astype(str)\nX_train.shape\n\n# Save the training features\nX_train.to_parquet('/kaggle/working/X_train.parquet')","metadata":{"execution":{"iopub.status.busy":"2023-07-15T16:13:35.755837Z","iopub.execute_input":"2023-07-15T16:13:35.756169Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clean up memory\ndel train_embeddings\ndel X_train\ngc.collect()","metadata":{"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)\ngo_terms.shape\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))\ny_train.shape\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# Save labels to disk\ngo_terms = pd.DataFrame(go_terms, columns=['term'])\ngo_terms.to_parquet(f'/kaggle/working/go_terms_{num_of_go_terms}.parquet')\n\n# Save the training data to disk\ny_train.to_parquet(f'/kaggle/working/y_train_{num_of_go_terms}.parquet')","metadata":{"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":{"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\ncolumn_num = test_embeddings.shape[1]\nX_test = pd.DataFrame(test_embeddings)\nX_test.columns = X_test.columns.astype(str)\nX_test.shape\n\n# Save the test features\nX_test.to_parquet('/kaggle/working/X_test.parquet')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clean up memory\ndel test_embeddings\ndel X_test\ngc.collect()","metadata":{"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_{num_of_go_terms}.parquet')\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\n# if batch_norm:\nmodel.add(BatchNormalization(input_shape=input_shape, name='input'))\nprint('Using batch normalization on input')\n# else:\n#     model.add(Flatten(input_shape=input_shape, name='input'))\n#     print('No 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":{"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":{"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":{"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# Make the predictions\npredictions = model.predict(X_test, batch_size=1024)\nprint(predictions.shape)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clean up memory\ndel X_test\ntf.keras.backend.clear_session()\ngc.collect()","metadata":{"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_{num_of_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":{"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":{"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":{"trusted":true},"execution_count":null,"outputs":[]}]}