Views
No views yet
train_sequences.fasta file is the
list of protein sequences that were trained on, and the
train_terms.tsv file contains the gene ontology protein function labels for each protein sequence. For more details on using
ESM-2 models for multi-label sequence classification, see here.
Due to the potentially complicated class weighting necessary for the hierarchical ontology, further fine-tuning will be necessary.5e-5, and achieves the following metrics:Validation Loss: 0.0027,
Validation Micro F1: 0.3672,
Validation Macro F1: 0.9967,
Validation Micro Precision: 0.6052,
Validation Macro Precision: 0.9996,
Validation Micro Recall: 0.2626,
Validation Macro Recall: 0.9966train_sequences.fasta file and the train_terms.tsv file, and provide the local paths in the code below:1import os
2import numpy as np
3import torch
4from transformers import AutoTokenizer, EsmForSequenceClassification, AdamW
5from torch.nn.functional import binary_cross_entropy_with_logits
6from sklearn.model_selection import train_test_split
7from sklearn.metrics import f1_score, precision_score, recall_score
8# from accelerate import Accelerator
9from Bio import SeqIO
10
11# Step 1: Data Preprocessing (Replace with your local paths)
12fasta_file = "/Users/amelieschreiber/.cursor-tutor/projects/python/cafa5/cafa-5-protein-function-prediction/Train/train_sequences.fasta"
13tsv_file = "/Users/amelieschreiber/.cursor-tutor/projects/python/cafa5/cafa-5-protein-function-prediction/Train/train_terms.tsv"
14
15fasta_data = {}
16tsv_data = {}
17
18for record in SeqIO.parse(fasta_file, "fasta"):
19 fasta_data[record.id] = str(record.seq)
20
21with open(tsv_file, 'r') as f:
22 for line in f:
23 parts = line.strip().split("\t")
24 tsv_data[parts[0]] = parts[1:]
25
26# tokenizer = AutoTokenizer.from_pretrained("facebook/esm2_t6_8M_UR50D")
27seq_length = 1022
28# tokenized_data = tokenizer(list(fasta_data.values()), padding=True, truncation=True, return_tensors="pt", max_length=seq_length)
29
30unique_terms = list(set(term for terms in tsv_data.values() for term in terms))go-basic.obo from here
and store the file locally, then provide the local path in the the code below:1import torch
2from transformers import AutoTokenizer, EsmForSequenceClassification
3from sklearn.metrics import precision_recall_fscore_support
4
5# 1. Parsing the go-basic.obo file
6def parse_obo_file(file_path):
7 with open(file_path, 'r') as f:
8 data = f.read().split("[Term]")
9
10 terms = []
11 for entry in data[1:]:
12 lines = entry.strip().split("\n")
13 term = {}
14 for line in lines:
15 if line.startswith("id:"):
16 term["id"] = line.split("id:")[1].strip()
17 elif line.startswith("name:"):
18 term["name"] = line.split("name:")[1].strip()
19 elif line.startswith("namespace:"):
20 term["namespace"] = line.split("namespace:")[1].strip()
21 elif line.startswith("def:"):
22 term["definition"] = line.split("def:")[1].split('"')[1]
23 terms.append(term)
24 return terms
25
26parsed_terms = parse_obo_file("go-basic.obo") # Replace `go-basic.obo` with your path
27
28# 2. Load the saved model and tokenizer
29model_path = "AmelieSchreiber/cafa_5_protein_function_prediction"
30loaded_model = EsmForSequenceClassification.from_pretrained(model_path)
31loaded_tokenizer = AutoTokenizer.from_pretrained(model_path)
32
33# 3. The predict_protein_function function
34def predict_protein_function(sequence, model, tokenizer, go_terms):
35 inputs = tokenizer(sequence, return_tensors="pt", padding=True, truncation=True, max_length=1022)
36 model.eval()
37 with torch.no_grad():
38 outputs = model(**inputs)
39 predictions = torch.sigmoid(outputs.logits)
40 predicted_indices = torch.where(predictions > 0.05)[1].tolist()
41
42 functions = []
43 for idx in predicted_indices:
44 term_id = unique_terms[idx] # Use the unique_terms list from your training script
45 for term in go_terms:
46 if term["id"] == term_id:
47 functions.append(term["name"])
48 break
49
50 return functions
51
52# 4. Predicting protein function for an example sequence
53example_sequence = "MAYLGSLVQRRLELASGDRLEASLGVGSELDVRGDRVKAVGSLDLEEGRLEQAGVSMA" # Replace with your protein sequence
54predicted_functions = predict_protein_function(example_sequence, loaded_model, loaded_tokenizer, parsed_terms)
55print(predicted_functions)