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-3 -1 -2 -4 7 -1 -1 -4 -3 -2 -2 -1 -2 -4
S 1 -1 1 0 -1 0 0 0 -1 -2 -2 0 -1 -2 -1 4 1 -3 -2 -2 0 0 0 -4
T 0 -1 0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -2 -1 1 5 -2 -2 0 -1 -1 0 -4
W -3 -3 -4 -4 -2 -2 -3 -2 -2 -3 -2 -3 -1 1 -4 -3 -2 11 2 -3 -4 -3 -2 -4
Y -2 -2 -2 -3 -2 -1 -2 -3 2 -1 -1 -2 -1 3 -3 -2 -2 2 7 -1 -3 -2 -1 -4
V 0 -3 -3 -3 -1 -2 -2 -3 -3 3 1 -2 1 -1 -2 -2 0 -3 -1 4 -3 -2 -1 -4
B -2 -1 3 4 -3 0 1 -1 0 -3 -4 0 -3 -3 -2 0 -1 -4 -3 -3 4 1 -1 -4
Z -1 0 0 1 -3 3 4 -2 0 -3 -3 1 -1 -3 -1 0 -1 -3 -2 -2 1 4 -1 -4
X 0 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2 0 0 -2 -1 -1 -1 -1 -1 -4
* -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 1
# ProfileModel
\ No newline at end of file
# SPIN (Scaling the Profile of lIfe by fuNction)
## 🚀 Overview
We implemented SPIN, a Transformer model inspired by ESM-2, for functionally classify proteins and predicting domain span from homologous sequences.
We experimented with two Protein families: Thioredoxin (TRX) and Cryptochrome/photolyase (CPF). We identify functional classes and subclasses with ProfileView (https://doi.org/10.1101/717249), handling thousands of sequences at a time to create comprehensive groups.
Our goal is to achieve large-scale classification of millions of proteins from extensive databases and ongoing high-throughput sequencing efforts. Moreover, it identifies conserved residues that are crucial for subfamilies, providing insights into the functional nuances of protein subclasses.
**Architecture**:
<p align="center">
<img src="images/architecture.png" width="100%" alt="arch">
</p>
**Results**:
Train 80%, Val 10 %, Test 10%
| | Sequences | Classes | Train Accuracy | Train F1 | Val Accuracy | Val F1 | Test Accuracy | Test F1 | Dom Start (± 3) | Dom End (± 3) |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| TRX | 28601 | 8 | 0.957 ± 0.03 | 0.957 ± 0.03 | 0.906 ± 0.01 | 0.906 ± 0.01 | 0.895 ± 0.01 | 0.895 ± 0.01 | 0.823 | 0.819 |
| CPF | 14295 | 8 | 0.987 ± 0.004 | 0.987 ± 0.004 | 0.982 ± 0.002 | 0.982 ± 0.002 | 0.976 ± 0.004 | 0.976 ± 0.004 | 0.963 | 0.909 |
---
## 🛠️ Usage
Get started with just a few steps:
### 1️⃣ Clone the repository
```bash
git clone http://gitlab.lcqb.upmc.fr/andrea.mancini/SPIN.git
```
### 2️⃣ Install dependencies
```bash
conda create -n spin
conda activate spin
pip install -r requirements.txt
```
### 3️⃣ Download pretrained models
| Model | # Classes | # tokens | # Epoch | #Val F1 score | # Checkpoint |
|-----------|-----------|----------|---------|---------------|--------------|
| TRX model | 8 | 1024 | 7 | 0.92 | [🔗 Download](https://.pt) |
| CPF model | 8 | 1024 | 4 | 0.98 | [🔗 Download](https://.pt) |
### 4️⃣ Create dataset from ProfileView tree
Example of dataset.csv:
| id_seq (string) | sequence (string) | start (int) Opt. | end (int) Opt. | group (string\|int) |
|----------------------|-------------------|------------------|----------------|---------------------|
| tr\|F0RTT8 | MSEIIVTEANFEQEVLK | 7 | 83 | TRX-1 |
```bash
create_dataset.py -f path_to_fasta -t path_to_nhx --depth val (optional) --nodes "Internal Node IDs list of subtrees" --class "Class IDs (only if passing a node list)"
```
### 5️⃣ Train the model
```bash
training.py -f path_to_csv --epochs 10 --batchsize 8 -v 2
```
### 7️⃣ Predict
```bash
predict.py -f path_to_csv --ckptpath checkpoint.tar
```
### Example Jupyter nb
Open demo.ipynb for an example of inference with TRX
\ No newline at end of file
......@@ -39,10 +39,6 @@ def define_classes_at_depth(fasta_path, tree: Tree, depth):
len_nodes = len(node_list)
class_ids = [getattr(node,'repr_model') for node in node_list if getattr(node,'repr_model') is not None]
if len(class_ids) < len_nodes:
class_ids = [node.name for node in node_list]
node2seqs = {class_ids[i]:node.get_leaf_names() for i,node in enumerate(node_list)}
......@@ -61,10 +57,6 @@ def define_classes_from_list(fasta_path, tree: Tree, node_ids_list, class_ids=No
len_nodes = len(node_list)
if not class_ids:
class_ids = [getattr(node,'repr_model') for node in node_list if getattr(node,'repr_model') is not None]
if len(class_ids) < len_nodes:
class_ids = [node.name for node in node_list]
node2seqs = {class_ids[i]:node.get_leaf_names() for i,node in enumerate(node_list)}
......
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"from pathlib import Path"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"def get_sequences_from_fasta(header_list, fasta_path):\n",
"\n",
" f = open(fasta_path, 'r')\n",
"\n",
" fasta_txt = f.read()\n",
" data = [(seq.split()[0],\"\".join(seq.split('\\n')[1:])) for seq in fasta_txt.split('>')[1:]]\n",
"\n",
" f.close()\n",
"\n",
" founded_seqs = ([],[])\n",
" for head_in_file, seq in data:\n",
"\n",
" if not head_in_file in header_list:\n",
" founded_seqs[0].append(head_in_file)\n",
" founded_seqs[1].append(seq.replace('\\n',''))\n",
"\n",
" return founded_seqs"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"def get_header(fasta_path):\n",
" \n",
" f = open(fasta_path, 'r')\n",
" fasta_txt = f.read()\n",
" header = [seq.split()[0] for seq in fasta_txt.split('>')[1:]]\n",
" f.close()\n",
"\n",
" return header"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"def save_to_csv(seq_ids, sequences, ofpath):\n",
"\n",
" dataset_dict = {'id_seq': seq_ids, 'sequence': sequences}\n",
"\n",
" path = Path(ofpath)\n",
"\n",
" if not path.parent.exists():\n",
" path.parent.mkdir(parents=True, exist_ok=True)\n",
"\n",
" pd.DataFrame.from_dict(dataset_dict).to_csv(path, index=True)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"main_fasta = \"/home/andrea/Project/TRX/TRX_30k/seq_to_classify.fasta_rep_seq.fasta\"\n",
"csv_path = \"/home/andrea/Project/TRX/TRX_30k/data_sequence_startend.csv\"\n",
"\n",
"df = pd.read_csv(csv_path, sep=',')\n",
"df.drop_duplicates(subset='sequence', inplace=True)\n",
"\n",
"header_list = df['id_seq'].values.tolist()\n",
"\n",
"head_seq_tuple = get_sequences_from_fasta(header_list, main_fasta)\n",
"\n",
"save_to_csv(head_seq_tuple[0], head_seq_tuple[1], \"/home/andrea/Project/TRX/TRX_30k/data_to_infer.csv\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"\n",
"a = {\"ciao\":[1,34,53,5,3,53], \"tuo\": [34,3,51,4512,4]}\n",
"\n",
"pd"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "bioenv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
import torch
from typing import List, Optional
import torch.nn as nn
from transformers import EsmForSequenceClassification
from peft import LoraConfig, TaskType, get_peft_model
from transformers import EsmModel
from config import ModelArgs
def get_model(args: ModelArgs) -> nn.Module:
class DomainSpanESM(nn.Module):
def __init__(self, config: ModelArgs):
super().__init__()
esm = EsmForSequenceClassification.from_pretrained(args.esm_name, num_labels=args.num_class)
self.config = config
for param in esm.esm.parameters():
self.esm = EsmModel.from_pretrained(self.config.version, add_pooling_layer=False)
for param in self.esm.parameters():
param.requires_grad = False
peft_config = LoraConfig(
task_type=TaskType.SEQ_CLS, inference_mode=False, r=args.lora_rank, lora_alpha=args.lora_alpha, lora_dropout=args.lora_dropout, target_modules= ["query","key","value"],
warm_layers = self.esm.encoder.layer[-6:]
for param in warm_layers.parameters():
param.requires_grad = True
hidd_size = self.esm.config.hidden_size
in_size = hidd_size
out_size = hidd_size #128
self.clf_head = nn.Sequential(
nn.Dropout(self.config.dropout),
nn.Linear(in_size, out_size),
nn.Tanh(),
nn.Dropout(self.config.dropout),
nn.Linear(out_size, len(self.config.labels))
)
model = get_peft_model(esm, peft_config) # transform our classifier into a peft model
model.print_trainable_parameters()
self.span_outputs = nn.Linear(hidd_size, 2)
self.init_weights()
def init_weights(self):
torch.nn.init.xavier_uniform_(self.clf_head[1].weight)
torch.nn.init.xavier_uniform_(self.clf_head[-1].weight)
# torch.nn.init.xavier_uniform_(self.fc.weight)
torch.nn.init.xavier_uniform_(self.span_outputs.weight)
def forward(self, inputs, start=None, end=None):
last_hidd = self.esm(**inputs)[0]
last_hidd = last_hidd[:,1:,:] # remove cls token
# x = last_hidd[:,0,:]
span_logits = self.span_outputs(last_hidd)
start_logits, end_logits = span_logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous()
end_logits = end_logits.squeeze(-1).contiguous()
span_loss = 0.0
if start is not None and end is not None:
# sometimes the start/end positions are outside our model inputs, we ignore these terms
ignored_index = start_logits.size(1)
start = start.clamp(0, ignored_index)
end = end.clamp(0, ignored_index)
ce_span = nn.CrossEntropyLoss(ignore_index=ignored_index)
start_loss = ce_span(start_logits, start)
end_loss = ce_span(end_logits, end)
span_loss = (start_loss + end_loss) / 2.
start_pred_pos = torch.argmax(start_logits, dim=-1)
end_pred_pos = torch.argmax(end_logits, dim=-1)
mask = torch.zeros_like(last_hidd, dtype=torch.bool, requires_grad=False)
for i, (s,e) in enumerate(zip(start_pred_pos, end_pred_pos)):
if s < e:
mask[i,s:e+1,:] = True
else:
mask[i,:,:] = inputs['attention_mask'][i,1:].unsqueeze(-1)
eps = 1e-8
x = torch.sum(last_hidd * mask, dim=1) / (torch.sum(mask, dim=1) + eps)
model.config.label2id = {key:id for id, key in enumerate(args.distinct_labels)}
model.config.id2label = {id:key for id, key in enumerate(args.distinct_labels)}
logits = self.clf_head(x)
return model
\ No newline at end of file
return logits, span_loss, (start_pred_pos, end_pred_pos)
\ No newline at end of file
import torch
import torch.nn as nn
from transformers import EsmModel
from config import ModelArgs
class DomainSpanESM(nn.Module):
def __init__(self, config: ModelArgs):
super().__init__()
self.config = config
self.esm = EsmModel.from_pretrained(self.config.version, add_pooling_layer=False)
for param in self.esm.parameters():
param.requires_grad = False
warm_layers = self.esm.encoder.layer[-6:]
for param in warm_layers.parameters():
param.requires_grad = True
hidd_size = self.esm.config.hidden_size
in_size = hidd_size
out_size = hidd_size #128
self.clf_head = nn.Sequential(
nn.Dropout(self.config.dropout),
nn.Linear(in_size, out_size),
nn.Tanh(),
nn.Dropout(self.config.dropout),
nn.Linear(out_size, len(self.config.labels))
)
self.span_outputs = nn.Linear(hidd_size, 2)
self.init_weights()
def init_weights(self):
torch.nn.init.xavier_uniform_(self.clf_head[1].weight)
torch.nn.init.xavier_uniform_(self.clf_head[-1].weight)
# torch.nn.init.xavier_uniform_(self.fc.weight)
torch.nn.init.xavier_uniform_(self.span_outputs.weight)
def forward(self, inputs, start=None, end=None):
last_hidd = self.esm(**inputs)[0]
last_hidd = last_hidd[:,1:,:] # remove cls token
# x = last_hidd[:,0,:]
span_logits = self.span_outputs(last_hidd)
start_logits, end_logits = span_logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous()
end_logits = end_logits.squeeze(-1).contiguous()
span_loss = 0.0
if start is not None and end is not None:
# sometimes the start/end positions are outside our model inputs, we ignore these terms
ignored_index = start_logits.size(1)
start = start.clamp(0, ignored_index)
end = end.clamp(0, ignored_index)
ce_span = nn.CrossEntropyLoss(ignore_index=ignored_index)
start_loss = ce_span(start_logits, start)
end_loss = ce_span(end_logits, end)
span_loss = (start_loss + end_loss) / 2.
start_pred_pos = torch.argmax(start_logits, dim=-1)
end_pred_pos = torch.argmax(end_logits, dim=-1)
mask = torch.zeros_like(last_hidd, dtype=torch.bool, requires_grad=False)
for i, (s,e) in enumerate(zip(start_pred_pos, end_pred_pos)):
if s < e:
mask[i,s:e+1,:] = True
else:
mask[i,:,:] = inputs['attention_mask'][i,1:].unsqueeze(-1)
eps = 1e-8
x = torch.sum(last_hidd * mask, dim=1) / (torch.sum(mask, dim=1) + eps)
logits = self.clf_head(x)
return logits, span_loss, (start_pred_pos, end_pred_pos)
\ No newline at end of file
pandas>=2.2.3
numpy>=1.26.4
matplotlib>=3.9.2
torch>=2.4.1
torchsummary>=1.5.1
scikit-learn>=1.5.1
tqdm>=4.64.0
transformers>=4.45.2
\ No newline at end of file
import argparse
from model.ProfileESM import DomainSpanESM
from model import DomainSpanESM
from trainer.trainer_domspanesm import TrainDomSpanESM
import torch
......
from pathlib import Path
import random
from model.ProfileESM import DomainSpanESM
from model import DomainSpanESM
from settings import BASE_PATH
import numpy as np
import torch
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment