{"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 = 1000","metadata":{"execution":{"iopub.status.busy":"2023-08-07T02:06:29.576697Z","iopub.execute_input":"2023-08-07T02:06:29.57715Z","iopub.status.idle":"2023-08-07T02:06:29.583126Z","shell.execute_reply.started":"2023-08-07T02:06:29.577116Z","shell.execute_reply":"2023-08-07T02:06:29.582025Z"},"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\nimport cupy as cp\nimport cudf\n\n# Set random seeds\nrandom.seed(random_seed)\nnp.random.seed(random_seed)\ntf.random.set_seed(random_seed)\ncp.random.seed(0)","metadata":{"execution":{"iopub.status.busy":"2023-08-07T02:06:29.590956Z","iopub.execute_input":"2023-08-07T02:06:29.59135Z","iopub.status.idle":"2023-08-07T02:06:29.606263Z","shell.execute_reply.started":"2023-08-07T02:06:29.591322Z","shell.execute_reply":"2023-08-07T02:06:29.604935Z"},"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 = cp.load('/kaggle/input/t5embeds/train_embeds.npy')\n\n# Create the training features from the embeddings\nX_train = cudf.DataFrame.from_records(cp.asnumpy(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-08-07T02:06:29.608812Z","iopub.execute_input":"2023-08-07T02:06:29.609225Z","iopub.status.idle":"2023-08-07T02:06:47.194872Z","shell.execute_reply.started":"2023-08-07T02:06:29.609192Z","shell.execute_reply":"2023-08-07T02:06:47.193462Z"},"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-08-07T02:06:47.197511Z","iopub.execute_input":"2023-08-07T02:06:47.197976Z","iopub.status.idle":"2023-08-07T02:06:47.642451Z","shell.execute_reply.started":"2023-08-07T02:06:47.197935Z","shell.execute_reply":"2023-08-07T02:06:47.641512Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"### Prepare y_train ###\n\n# Read the GO terms\ntrain_terms = cudf.read_csv(\"/kaggle/input/cafa-5-protein-function-prediction/Train/train_terms.tsv\", sep=\"\\t\")\n\n# Get the first M labels\ngo_terms = train_terms['term'].value_counts().index[:num_of_go_terms].to_arrow().to_pylist()\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    \n# Group train_terms_updated by 'term' and get the corresponding unique 'EntryID's for each label\ngo_terms_to_proteins_map = train_terms_updated.groupby('term')['EntryID'].unique()\n\n# Create a matrix of proteins and Go terms\nfor i, label in enumerate(go_terms):\n\n    # Get the proteins related to the current GO term\n    go_term_related_proteins = go_terms_to_proteins_map.loc[label] if label in go_terms_to_proteins_map else []\n\n    # Fill the corresponding column in the matrix\n    y_train[:, i] = train_protein_ids.isin(go_term_related_proteins)\n\n    # Increment the counter\n    i += 1\n\n    # Update the progress bar\n    bar.update(i)\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-08-07T02:06:47.644172Z","iopub.execute_input":"2023-08-07T02:06:47.6446Z","iopub.status.idle":"2023-08-07T02:07:33.277462Z","shell.execute_reply.started":"2023-08-07T02:06:47.644565Z","shell.execute_reply":"2023-08-07T02:07:33.276213Z"},"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 go_terms_to_proteins_map\ndel go_term_related_proteins\ndel y_train\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-08-07T02:07:33.282235Z","iopub.execute_input":"2023-08-07T02:07:33.282979Z","iopub.status.idle":"2023-08-07T02:07:33.617912Z","shell.execute_reply.started":"2023-08-07T02:07:33.282933Z","shell.execute_reply":"2023-08-07T02:07:33.616961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"### Prepare X_test ###\n\n# Get the test embeddings\ntest_embeddings = cp.load('/kaggle/input/t5embeds/test_embeds.npy')\ntest_embeddings.shape\n\n# Convert test_embeddings to dataframe\nX_test = cudf.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-08-07T02:07:33.619575Z","iopub.execute_input":"2023-08-07T02:07:33.619962Z","iopub.status.idle":"2023-08-07T02:07:40.240848Z","shell.execute_reply.started":"2023-08-07T02:07:33.619925Z","shell.execute_reply":"2023-08-07T02:07:40.239467Z"},"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-08-07T02:07:40.247632Z","iopub.execute_input":"2023-08-07T02:07:40.251149Z","iopub.status.idle":"2023-08-07T02:07:40.707675Z","shell.execute_reply.started":"2023-08-07T02:07:40.251109Z","shell.execute_reply":"2023-08-07T02:07:40.706591Z"},"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-08-07T02:07:40.711486Z","iopub.execute_input":"2023-08-07T02:07:40.711865Z","iopub.status.idle":"2023-08-07T02:07:45.178495Z","shell.execute_reply.started":"2023-08-07T02:07:40.711838Z","shell.execute_reply":"2023-08-07T02:07:45.177689Z"},"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-08-07T02:07:45.179622Z","iopub.execute_input":"2023-08-07T02:07:45.179948Z","iopub.status.idle":"2023-08-07T02:08:14.197359Z","shell.execute_reply.started":"2023-08-07T02:07:45.179916Z","shell.execute_reply":"2023-08-07T02:08:14.196258Z"},"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-08-07T02:08:14.198674Z","iopub.execute_input":"2023-08-07T02:08:14.199035Z","iopub.status.idle":"2023-08-07T02:08:14.617074Z","shell.execute_reply.started":"2023-08-07T02:08:14.198986Z","shell.execute_reply":"2023-08-07T02:08:14.616062Z"},"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 cupy array\npredictions = cp.array(predictions)\n\n# Convert to float32\npredictions = predictions.astype('float16')","metadata":{"execution":{"iopub.status.busy":"2023-08-07T02:08:14.618674Z","iopub.execute_input":"2023-08-07T02:08:14.619035Z","iopub.status.idle":"2023-08-07T02:08:19.796168Z","shell.execute_reply.started":"2023-08-07T02:08:14.618985Z","shell.execute_reply":"2023-08-07T02:08:19.79506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clean up memory\ndel X_test\ndel model\ntf.keras.backend.clear_session()\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-08-07T02:08:19.79807Z","iopub.execute_input":"2023-08-07T02:08:19.798757Z","iopub.status.idle":"2023-08-07T02:08:20.142072Z","shell.execute_reply.started":"2023-08-07T02:08:19.798723Z","shell.execute_reply":"2023-08-07T02:08:20.140946Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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# Get the shape of the submission table elements\nnum_protein_ids = test_protein_ids.shape[0]\nnum_go_terms = len(go_terms)\nnum_predictions = num_protein_ids * num_go_terms\n\n# Create the submission table\nsubmission = cudf.DataFrame(columns = ['Protein Id', 'GO Term Id','Prediction'])","metadata":{"execution":{"iopub.status.busy":"2023-08-07T02:08:20.143823Z","iopub.execute_input":"2023-08-07T02:08:20.144232Z","iopub.status.idle":"2023-08-07T02:08:20.164765Z","shell.execute_reply.started":"2023-08-07T02:08:20.144199Z","shell.execute_reply":"2023-08-07T02:08:20.163792Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Expand (broadcast) the list of protein IDs\nprotein_ids_list = []\nfor k in list(test_protein_ids):\n    protein_ids_list += [k] * predictions.shape[1]\n\n# Clean up memory\ndel test_protein_ids\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-08-07T02:08:20.169221Z","iopub.execute_input":"2023-08-07T02:08:20.169496Z","iopub.status.idle":"2023-08-07T02:08:22.625907Z","shell.execute_reply.started":"2023-08-07T02:08:20.169472Z","shell.execute_reply":"2023-08-07T02:08:22.62495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create protein ID column\nsubmission['Protein Id'] = protein_ids_list\n\n# Clean up memory\ndel protein_ids_list\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-08-07T02:08:22.62739Z","iopub.execute_input":"2023-08-07T02:08:22.627736Z","iopub.status.idle":"2023-08-07T02:08:32.876568Z","shell.execute_reply.started":"2023-08-07T02:08:22.627703Z","shell.execute_reply":"2023-08-07T02:08:32.875658Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create GO terms column\nsubmission['GO Term Id'] = go_terms * predictions.shape[0]\n\n# Clean up memory\ndel go_terms\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-08-07T02:08:32.880722Z","iopub.execute_input":"2023-08-07T02:08:32.882985Z","iopub.status.idle":"2023-08-07T02:08:45.204931Z","shell.execute_reply.started":"2023-08-07T02:08:32.882942Z","shell.execute_reply":"2023-08-07T02:08:45.203948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\n# Ravel the prediction\npredictions = predictions.ravel()\n\n# Create the predictions column\nsubmission['Prediction'] = predictions\n\n# Convert to a decimal with 3 decimal places\nsubmission['Prediction'] = submission['Prediction'].astype(cudf.Decimal32Dtype(4, 3))\n\n# Clean up memory\ndel predictions\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-08-07T02:08:45.206335Z","iopub.execute_input":"2023-08-07T02:08:45.206706Z","iopub.status.idle":"2023-08-07T02:08:45.824274Z","shell.execute_reply.started":"2023-08-07T02:08:45.206671Z","shell.execute_reply":"2023-08-07T02:08:45.823312Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\n# Save the submission file\nsubmission.to_csv(\n    f'submission.tsv',\n    sep='\\t',\n    index=False,\n    header=False,\n    chunksize=100000)\n\n# Clean up memory\ndel submission\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-08-07T02:08:45.841766Z","iopub.execute_input":"2023-08-07T02:08:45.842141Z","iopub.status.idle":"2023-08-07T02:08:58.632236Z","shell.execute_reply.started":"2023-08-07T02:08:45.842109Z","shell.execute_reply":"2023-08-07T02:08:58.631152Z"},"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-08-07T02:08:58.634083Z","iopub.execute_input":"2023-08-07T02:08:58.634484Z","iopub.status.idle":"2023-08-07T02:08:58.643549Z","shell.execute_reply.started":"2023-08-07T02:08:58.634429Z","shell.execute_reply":"2023-08-07T02:08:58.642601Z"},"trusted":true},"execution_count":null,"outputs":[]}]}