Views
No views yet
1from transformers import AutoTokenizer, AutoModel, T5Tokenizer
2tokenizer = T5Tokenizer.from_pretrained("Rostlab/prot_t5_xl_uniref50")
3model = AutoModel.from_pretrained("h4duan/PAIR-prott5").to("cuda")
4protein = ["AETCZAO"]
5
6def extract_feature(protein):
7 protein = [" ".join(list(re.sub(r"[UZOB]", "X", sequence))) for sequence in protein]
8 ids = tokenizer(protein, return_tensors="pt", padding=True, max_length=1024, truncation=True, return_attention_mask=True)
9 input_ids = torch.tensor(ids['input_ids']).to("cuda")
10 attention_mask = torch.tensor(ids['attention_mask']).to("cuda")
11 with torch.no_grad():
12 embedding_repr = model(input_ids=input_ids,attention_mask=attention_mask).last_hidden_state
13 return torch.mean(embedding_repr, dim=1)
14
15feature = extract_feature(protein)1proteins = ["AETCZAO","SKTZP"]
2def extract_features(proteins):
3 sequences = [" ".join(list(re.sub(r"[UZOB]", "X", sequence))) for sequence in proteins]
4 ids = tokenizer.batch_encode_plus(sequences, add_special_tokens=True, padding='max_length',
5 max_length=1024, truncation=True)
6 input_ids = torch.tensor(ids['input_ids']).to("cuda")
7 attention_mask = torch.tensor(ids['attention_mask']).to("cuda")
8 with torch.no_grad():
9 embedding_repr = model(input_ids=input_ids,attention_mask=attention_mask).last_hidden_state
10 attention_mask = attention_mask.unsqueeze(-1)
11 attention_mask = attention_mask.expand(-1, -1, embedding_repr.size(-1))
12 masked_embedding_repr = embedding_repr * attention_mask
13 sum_embedding_repr = masked_embedding_repr.sum(dim=1)
14 non_zero_count = attention_mask.sum(dim=1)
15 mean_embedding_repr = sum_embedding_repr / non_zero_count
16 return mean_embedding_repr
17
18features = extract_feature(proteins)