-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathesm_encode_labeled.py
More file actions
66 lines (48 loc) · 2.09 KB
/
Copy pathesm_encode_labeled.py
File metadata and controls
66 lines (48 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from transformers import AutoTokenizer, AutoModel
from transformers import AutoConfig
import transformers
from transformers import EncoderDecoderModel
from transformers import Trainer, TrainingArguments
import pandas as pd
from Bio import SeqIO
from sklearn.model_selection import train_test_split
import random
import string
import torch
import numpy as np
# Device configuration
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Load the tokenizer and model
model_checkpoint = "facebook/esm2_t6_8M_UR50D"
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
model_encoder = AutoModel.from_pretrained(model_checkpoint).to(device)
data_path = "project/data/labeled_data_sorted.csv"
# Read a CSV file into a dataframe
def read_csv_to_df(csv_file):
return pd.read_csv(csv_file)
seq_length = 500
# Example usage
csv_file = data_path
df = read_csv_to_df(csv_file)
df = df[df["sequence"].str.len() <= seq_length]
print(df.head())
# Example usage with sequences from the dataframe
sequences = df["sequence"].tolist()
inputs = tokenizer(sequences, return_tensors="pt", padding='max_length', truncation=True, max_length=seq_length)
dataset = [{"input_ids": input_id, "attention_mask": attention_mask, "labels": input_id} for input_id, attention_mask in zip(inputs["input_ids"], inputs["attention_mask"])]
# Function to get embeddings from the encoder
def get_embeddings(dataset, model, tokenizer, device):
embeddings = []
for data in dataset:
input_ids = data["input_ids"].unsqueeze(0).to(device)
attention_mask = data["attention_mask"].unsqueeze(0).to(device)
with torch.no_grad():
outputs = model(input_ids=input_ids, attention_mask=attention_mask)
embeddings.append(outputs.last_hidden_state.squeeze().cpu().numpy())
return embeddings
# Get embeddings for the dataset
embeddings = np.array(get_embeddings(dataset, model_encoder, tokenizer, device))
embeddings = embeddings.mean(axis=1)
# Save embeddings to npz file
np.savez("project/data/labeled_embeddings.npz", embeddings=embeddings)
print(f"Embeddings: {embeddings.shape}")