{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-08-17T01:35:57.309047Z","iopub.execute_input":"2023-08-17T01:35:57.309568Z","iopub.status.idle":"2023-08-17T01:35:57.334670Z","shell.execute_reply.started":"2023-08-17T01:35:57.309512Z","shell.execute_reply":"2023-08-17T01:35:57.333377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install obonet","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_preprocessed = pd.read_csv('/kaggle/input/proprocessed-abstract-train/preprocessed_data.csv')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_preprocessed = pd.read_csv('/kaggle/input/preprocessed-data-testdi/preprocessed_data_test.csv')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_preprocessed","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_preprocessed","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import obonet\nimport re\nimport nltk\nfrom nltk.corpus import stopwords\nimport string\n# Specify the path to your OBO file\nobo_file_path = '/kaggle/input/cafa-5-protein-function-prediction/Train/go-basic.obo'\n\n# Read the OBO file\ngraph = obonet.read_obo(obo_file_path)\n\nterms = [data.get('name') for _, data in graph.nodes.items()]\n\n# Combine all terms into a single string\nall_terms_text = ' '.join(terms)\n\n# Clean the text\ncleaned_text = re.sub(r'\\W', ' ', all_terms_text.lower())  # Remove non-alphanumeric characters\ncleaned_text = re.sub(r'\\s+', ' ', cleaned_text)  # Remove extra whitespaces\n\n# Tokenize the text\ntokens = nltk.word_tokenize(cleaned_text)\n\n# Remove stopwords\nstopwords = set(stopwords.words('english'))\nfiltered_words = [word for word in tokens if word.lower() not in stopwords and word not in string.punctuation and not word.isdigit() and len(word)>2]\n\n# Remove duplicate words\nfiltered_words_all = list(set(filtered_words))\n\n#print(filtered_words)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_go_vocab = pd.DataFrame(filtered_words_all, columns=[\"vocab\"])\ndf_go_vocab.to_csv('/kaggle/working/Go_vocab_terms.csv', index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_go_vocab","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"set_a = set(test_preprocessed['Protein ID'])\nset_b = set(train_preprocessed['Protein ID'])\n\n# Find elements in set_a but not in set_b\ndiff = set_a - set_b\n\n# Convert the result back to a list (if desired)\ndiff_list = list(diff)\n\n# Print the result\nprint(len(diff_list))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_test_preprocessed = pd.concat([train_preprocessed, test_preprocessed], axis=0, ignore_index=True)\nprint(train_test_preprocessed)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_test_preprocessed.drop_duplicates(subset=['Protein ID'], inplace=True)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_test_preprocessed","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom scipy.sparse import save_npz\nabstracts_df = train_test_preprocessed\nprint('creating_tfidf')\n\n# Create the TfidfVectorizer\nvectorizer = TfidfVectorizer(vocabulary=filtered_words_all)\nvectorizer.fit(abstracts_df['Preprocessed Abstract'])\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tfidf_train_vectors = vectorizer.transform(train_preprocessed['Preprocessed Abstract'])\ntfidf_test_vectors = vectorizer.transform(test_preprocessed['Preprocessed Abstract'])\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Convert the TF-IDF vectors to an array\ntrain_vectors = tfidf_train_vectors.toarray()\ntest_vectors = tfidf_test_vectors.toarray()\n\n# Update the abstracts dataframe with the embedding vectors\ntrain_preprocessed['Embedding Vector'] = list(train_vectors)\ntest_preprocessed['Embedding Vector'] = list(test_vectors)\n\n\n","metadata":{"execution":{"iopub.status.busy":"2023-08-17T00:03:16.914901Z","iopub.execute_input":"2023-08-17T00:03:16.915376Z"}}},{"cell_type":"code","source":"# Save the TF-IDF sparse matrices\nsave_npz('/kaggle/working/tfidf_go_sparse_matrix_train.npz', tfidf_train_vectors)\nsave_npz('/kaggle/working/tfidf_go_sparse_matrix_test.npz', tfidf_test_vectors)\n\n# Save the protein IDs for both dataframes\ntrain_preprocessed['Protein ID'].to_csv('/kaggle/working/protein_ids_train.csv', index=False)\ntest_preprocessed['Protein ID'].to_csv('/kaggle/working/protein_ids_test.csv', index=False)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_ids_np = np.load('/kaggle/input/train-labels-sorted-zong/Ankh_train_labels_sorted.npy')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_ids_df = pd.DataFrame(train_ids_np, columns = ['ID'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_ids_df\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"embed_ids = pd.read_csv('/kaggle/input/abstract-embeds-final/protein_ids_train_sparse.csv')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"embed_ids","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from scipy.sparse import load_npz\nsparse_matrix_train = load_npz('/kaggle/input/abstract-embeds-final/tfidf_go_sparse_matrix_train.npz')\n\ndf_npz = pd.DataFrame.sparse.from_spmatrix(sparse_matrix_train)\ndf_npz['Protein_ID'] = embed_ids['Protein ID'].values\n\n# Convert series_train_protein_ids to DataFrame\ndf_ids = train_ids_df\n\n# Reset the index of df_npz to allow the merge\n#df_npz_reset = df_npz.reset_index()\n\n# Perform the merge with a left join\ndf_train = pd.merge(df_ids, df_npz, how='left', left_on='ID', right_on = 'Protein_ID')\n\n# Fill NaN values with zeros\ndf_train[df_npz.columns] = df_train[df_npz.columns].fillna(0)\n\n# Set 'ID' as the index of the DataFrame again\ndf_train.set_index('Protein_ID', inplace=True)\ndf_train = df_train.drop('ID', axis=1)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Get the feature names (words) from the original TfidfVectorizer\nfeature_names = vectorizer.get_feature_names_out()\n\n# Select the row from df_train that corresponds to the given Protein ID\nprotein_id = 'A0A009IHW8'\nrow = df_train.loc[protein_id]\n\n# Get the TF-IDF values for that row\ntfidf_values = row[:-1]  # Assuming the last column is 'Protein_ID'\n\n# Extract the words that have non-zero TF-IDF values\nnon_zero_indices = tfidf_values[tfidf_values != 0].index\nnon_zero_words = [feature_names[i] for i in non_zero_indices]\n\nprint(f\"Words with non-zero TF-IDF values for Protein ID '{protein_id}': {non_zero_words}\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_non_zero_words(protein_id, df, vectorizer):\n    # Get the feature names (words) from the original TfidfVectorizer\n    feature_names = vectorizer.get_feature_names_out()\n\n    # Select the row from df that corresponds to the given Protein ID\n    row = df.loc[protein_id]\n\n    # Get the TF-IDF values for that row\n    tfidf_values = row[:-1]  # Assuming the last column is 'Protein_ID'\n\n    # Extract the words and their TF-IDF values that have non-zero TF-IDF values\n    non_zero_indices = tfidf_values[tfidf_values != 0].index\n    non_zero_words = [(feature_names[i], tfidf_values[i]) for i in non_zero_indices]\n\n    # Sort the words in descending order of their TF-IDF values\n    sorted_words = sorted(non_zero_words, key=lambda x: x[1], reverse=True)\n\n    return sorted_words\n\n# Example usage:\nprotein_id = 'Q5K4F8'\nsorted_words = get_non_zero_words(protein_id, df_train, vectorizer)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Test_IDS","metadata":{"execution":{"iopub.status.busy":"2023-08-17T00:45:44.845981Z","iopub.execute_input":"2023-08-17T00:45:44.846608Z","iopub.status.idle":"2023-08-17T00:45:44.852719Z","shell.execute_reply.started":"2023-08-17T00:45:44.846569Z","shell.execute_reply":"2023-08-17T00:45:44.851402Z"}}},{"cell_type":"code","source":"test_ids = np.load('/kaggle/input/test-ids-sorted-zong/t5_labels_sorted.npy')\ntest_ids_df =  pd.DataFrame(test_ids, columns = ['ID'])","metadata":{"execution":{"iopub.status.busy":"2023-08-17T01:31:52.315007Z","iopub.execute_input":"2023-08-17T01:31:52.315409Z","iopub.status.idle":"2023-08-17T01:31:52.436965Z","shell.execute_reply.started":"2023-08-17T01:31:52.315378Z","shell.execute_reply":"2023-08-17T01:31:52.435939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ids_df","metadata":{"execution":{"iopub.status.busy":"2023-08-17T01:31:52.906218Z","iopub.execute_input":"2023-08-17T01:31:52.906626Z","iopub.status.idle":"2023-08-17T01:31:52.934469Z","shell.execute_reply.started":"2023-08-17T01:31:52.906595Z","shell.execute_reply":"2023-08-17T01:31:52.932928Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"embed_ids_test = pd.read_csv('/kaggle/input/abstract-embeds-final/protein_ids_test_sparse.csv')","metadata":{"execution":{"iopub.status.busy":"2023-08-17T01:32:20.472279Z","iopub.execute_input":"2023-08-17T01:32:20.472708Z","iopub.status.idle":"2023-08-17T01:32:20.569125Z","shell.execute_reply.started":"2023-08-17T01:32:20.472677Z","shell.execute_reply":"2023-08-17T01:32:20.567823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from scipy.sparse import load_npz\nsparse_matrix_test = load_npz('/kaggle/input/abstract-embeds-final/tfidf_go_sparse_matrix_test.npz')\n\ndf_npz = pd.DataFrame.sparse.from_spmatrix(sparse_matrix_test)\ndf_npz['Protein_ID'] = embed_ids_test['Protein ID'].values\n\n# Convert series_test_protein_ids to DataFrame\ndf_ids = test_ids_df\n\n# Reset the index of df_npz to allow the merge\n#df_npz_reset = df_npz.reset_index()\n\n# Perform the merge with a left join\ndf_test = pd.merge(df_ids, df_npz, how='left', left_on='ID', right_on = 'Protein_ID')\n\n# Fill NaN values with zeros\ndf_test[df_npz.columns] = df_test[df_npz.columns].fillna(0)\n\n#Index 631 and 632 are duplicates. So drop one. Both are protein A0A1D6E0S8 and have the same embedding vector as well.\ndf_test = df_test.drop(632)\n\n# Set 'ID' as the index of the DataFrame again\ndf_test.set_index('Protein_ID', inplace=True)\ndf_test = df_test.drop('ID', axis=1)\n","metadata":{"execution":{"iopub.status.busy":"2023-08-17T01:32:21.183071Z","iopub.execute_input":"2023-08-17T01:32:21.183584Z","iopub.status.idle":"2023-08-17T01:35:11.329228Z","shell.execute_reply.started":"2023-08-17T01:32:21.183478Z","shell.execute_reply":"2023-08-17T01:35:11.327996Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test","metadata":{"execution":{"iopub.status.busy":"2023-08-17T01:35:11.331904Z","iopub.execute_input":"2023-08-17T01:35:11.332352Z","iopub.status.idle":"2023-08-17T01:35:11.557827Z","shell.execute_reply.started":"2023-08-17T01:35:11.332319Z","shell.execute_reply":"2023-08-17T01:35:11.556500Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test","metadata":{"execution":{"iopub.status.busy":"2023-08-17T01:36:03.565110Z","iopub.execute_input":"2023-08-17T01:36:03.565561Z","iopub.status.idle":"2023-08-17T01:36:03.756009Z","shell.execute_reply.started":"2023-08-17T01:36:03.565510Z","shell.execute_reply":"2023-08-17T01:36:03.754616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sorted_words = get_non_zero_words('Q60590', df_test, vectorizer)","metadata":{"execution":{"iopub.status.busy":"2023-08-17T01:32:08.854915Z","iopub.status.idle":"2023-08-17T01:32:08.855953Z","shell.execute_reply.started":"2023-08-17T01:32:08.855652Z","shell.execute_reply":"2023-08-17T01:32:08.855680Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sorted_words","metadata":{"execution":{"iopub.status.busy":"2023-08-17T01:32:08.857669Z","iopub.status.idle":"2023-08-17T01:32:08.858522Z","shell.execute_reply.started":"2023-08-17T01:32:08.858235Z","shell.execute_reply":"2023-08-17T01:32:08.858263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.save('/kaggle/working/abstract_embeds_train_sorted_all.npy', df_train.values)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#np.save('/kaggle/working/abstract_embeds_test_sorted_all.npy', df_test.values)","metadata":{"execution":{"iopub.status.busy":"2023-08-17T01:36:10.654184Z","iopub.execute_input":"2023-08-17T01:36:10.654636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}