{"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\n# act_func = 'relu'\nact_func = 'elu'\nbatch_norm = False\noptimizer = 'Adam'  # Non-functional\neta = 0.001\nl2 = None\ndropout = None\nbatch_size = 5120\nepochs = 30\nnum_of_go_terms = 1500","metadata":{"execution":{"iopub.status.busy":"2023-07-31T04:36:39.554055Z","iopub.execute_input":"2023-07-31T04:36:39.554757Z","iopub.status.idle":"2023-07-31T04:36:39.563349Z","shell.execute_reply.started":"2023-07-31T04:36:39.554691Z","shell.execute_reply":"2023-07-31T04:36:39.561801Z"},"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-31T04:36:39.565981Z","iopub.execute_input":"2023-07-31T04:36:39.5664Z","iopub.status.idle":"2023-07-31T04:36:51.624551Z","shell.execute_reply.started":"2023-07-31T04:36:39.566365Z","shell.execute_reply":"2023-07-31T04:36:51.623422Z"},"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\")","metadata":{"execution":{"iopub.status.busy":"2023-07-31T04:36:51.626026Z","iopub.execute_input":"2023-07-31T04:36:51.626743Z","iopub.status.idle":"2023-07-31T04:36:55.251016Z","shell.execute_reply.started":"2023-07-31T04:36:51.626689Z","shell.execute_reply":"2023-07-31T04:36:55.249386Z"},"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-31T04:36:55.25292Z","iopub.execute_input":"2023-07-31T04:36:55.253391Z","iopub.status.idle":"2023-07-31T04:37:41.682665Z","shell.execute_reply.started":"2023-07-31T04:36:55.253354Z","shell.execute_reply":"2023-07-31T04:37:41.681111Z"},"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-31T04:37:41.685549Z","iopub.execute_input":"2023-07-31T04:37:41.685921Z","iopub.status.idle":"2023-07-31T04:37:42.627911Z","shell.execute_reply.started":"2023-07-31T04:37:41.685891Z","shell.execute_reply":"2023-07-31T04:37:42.62667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n### 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)]\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# Group train_terms_updated by 'term' and get the corresponding unique 'EntryID's for each label\nlabel_related_proteins_map = train_terms_updated.groupby('term')['EntryID'].unique()\n\nj = 1\n# Fill the train_labels array based on the mapping\nfor i, label in enumerate(go_terms):\n    label_related_proteins = label_related_proteins_map.get(label, [])\n    y_train[:, i] = train_protein_ids.isin(label_related_proteins)\n    i+=1\n    bar.update(i)\n    \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-31T04:37:42.629838Z","iopub.execute_input":"2023-07-31T04:37:42.630758Z","iopub.status.idle":"2023-07-31T04:38:24.246787Z","shell.execute_reply.started":"2023-07-31T04:37:42.630693Z","shell.execute_reply":"2023-07-31T04:38:24.245493Z"},"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 y_train\ndel label_related_proteins_map\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-07-31T04:38:24.248289Z","iopub.execute_input":"2023-07-31T04:38:24.249524Z","iopub.status.idle":"2023-07-31T04:38:25.416754Z","shell.execute_reply.started":"2023-07-31T04:38:24.249473Z","shell.execute_reply":"2023-07-31T04:38:25.415522Z"},"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-31T04:38:25.41875Z","iopub.execute_input":"2023-07-31T04:38:25.419493Z","iopub.status.idle":"2023-07-31T04:39:11.419067Z","shell.execute_reply.started":"2023-07-31T04:38:25.419448Z","shell.execute_reply":"2023-07-31T04:39:11.417115Z"},"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-31T04:39:11.421599Z","iopub.execute_input":"2023-07-31T04:39:11.422216Z","iopub.status.idle":"2023-07-31T04:39:12.485153Z","shell.execute_reply.started":"2023-07-31T04:39:11.422152Z","shell.execute_reply":"2023-07-31T04:39:12.483081Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Kernel initializer with seed\nkernel_init = tf.keras.initializers.HeNormal(seed=50301)\n\n# 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_initializer=kernel_init,\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}', kernel_initializer=kernel_init,))\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-31T05:07:00.861577Z","iopub.execute_input":"2023-07-31T05:07:00.862101Z","iopub.status.idle":"2023-07-31T05:07:09.974497Z","shell.execute_reply.started":"2023-07-31T05:07:00.862062Z","shell.execute_reply":"2023-07-31T05:07:09.972998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def exponential_decay(lr0, s):\n    def exponential_decay_fn(epoch):\n        return lr0 * 0.1**(epoch / s)\n    return exponential_decay_fn\n\nfrom keras.callbacks import ReduceLROnPlateau\n\nexponential_decay_fn = exponential_decay(lr0=0.1, s=3)\n\ncallback = tf.keras.callbacks.LearningRateScheduler(exponential_decay_fn)\n\n# 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#     callbacks=[callback],\n    verbose=2)\n\n# Save the model\nmodel.save(f'/kaggle/working/model.h5')","metadata":{"execution":{"iopub.status.busy":"2023-07-31T05:07:34.854302Z","iopub.execute_input":"2023-07-31T05:07:34.854918Z","iopub.status.idle":"2023-07-31T05:15:45.864294Z","shell.execute_reply.started":"2023-07-31T05:07:34.854876Z","shell.execute_reply":"2023-07-31T05:15:45.862571Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Epoch 30/30 <br>\n28/28 - 19s - loss: 0.0504 - 19s/epoch - 668ms/step","metadata":{}},{"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-31T04:39:16.043482Z","iopub.status.idle":"2023-07-31T04:39:16.04402Z","shell.execute_reply.started":"2023-07-31T04:39:16.043793Z","shell.execute_reply":"2023-07-31T04:39:16.043819Z"},"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-31T04:39:16.04545Z","iopub.status.idle":"2023-07-31T04:39:16.04596Z","shell.execute_reply.started":"2023-07-31T04:39:16.045738Z","shell.execute_reply":"2023-07-31T04:39:16.045768Z"},"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-31T04:39:16.048648Z","iopub.status.idle":"2023-07-31T04:39:16.049396Z","shell.execute_reply.started":"2023-07-31T04:39:16.04916Z","shell.execute_reply":"2023-07-31T04:39:16.049186Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\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('/kaggle/working/go_terms.parquet')['term'].values\n\n# Create the submission table using NumPy arrays for efficiency\nn_protein_ids = test_protein_ids.shape[0]\nn_go_terms = len(go_terms)\nn_predictions = n_protein_ids * n_go_terms\n\n# Define the dtype with 'O' for objects and 'float32' for float values\ndtype = [('Protein Id', 'O'), ('GO Term Id', 'O'), ('Prediction', 'float32')]\n\n# Create the empty array\nsubmission_data = np.empty((n_predictions,), dtype=dtype)\n\n# Create submission table using NumPy arrays\n#submission_data = np.empty((n_predictions, 3), dtype=object)\nsubmission_data['Protein Id'] = np.repeat(test_protein_ids, n_go_terms)\nsubmission_data['GO Term Id'] = np.tile(go_terms, n_protein_ids)\nsubmission_data['Prediction'] = predictions.ravel()","metadata":{"execution":{"iopub.status.busy":"2023-07-31T04:39:16.051677Z","iopub.status.idle":"2023-07-31T04:39:16.052184Z","shell.execute_reply.started":"2023-07-31T04:39:16.051973Z","shell.execute_reply":"2023-07-31T04:39:16.051995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nsubmission_data = pd.DataFrame(submission_data, columns=['Protein Id', 'GO Term Id', 'Prediction'])\nsubmission_data.to_csv(\"submission.tsv\",header=False, index=False, sep=\"\\t\")","metadata":{"execution":{"iopub.status.busy":"2023-07-31T04:39:16.053518Z","iopub.status.idle":"2023-07-31T04:39:16.054328Z","shell.execute_reply.started":"2023-07-31T04:39:16.05411Z","shell.execute_reply":"2023-07-31T04:39:16.054133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del go_terms\ndel test_protein_ids\ndel n_predictions\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-07-31T04:39:16.055843Z","iopub.status.idle":"2023-07-31T04:39:16.056256Z","shell.execute_reply.started":"2023-07-31T04:39:16.05606Z","shell.execute_reply":"2023-07-31T04:39:16.056079Z"},"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-31T04:39:16.057437Z","iopub.status.idle":"2023-07-31T04:39:16.058028Z","shell.execute_reply.started":"2023-07-31T04:39:16.05778Z","shell.execute_reply":"2023-07-31T04:39:16.057813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clean up memory\ndel predictions\n# #del l\n# #del test_protein_ids\n# #del go_terms\ndel submission_data\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-07-31T04:39:16.05986Z","iopub.status.idle":"2023-07-31T04:39:16.060297Z","shell.execute_reply.started":"2023-07-31T04:39:16.060088Z","shell.execute_reply":"2023-07-31T04:39:16.060108Z"},"trusted":true},"execution_count":null,"outputs":[]}]}