-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
205 lines (167 loc) · 5.99 KB
/
utils.py
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import pandas as pd
import numpy as np
def get_data(item,typ):
BaseDir = './humploc_c/'
object = item+ ' proteins.{}.csv'.format(typ)
Path = BaseDir +object
data = pd.read_csv(Path)
return data['label'],data['seq']
from torch import nn, optim
import torch.nn.functional as F
import torch
import torch.utils.data as Data
import requests
def request_page(url):
response = requests.get(url)
if response.status_code == 200:
print('succucess!')
return response.content
else:
print(response)
print('failed try!')
return None
def loop_find(target, str, start=0):
li = []
while True:
beg = target.find(str, start)
if beg == -1:
break
li.append(beg)
start = beg + 1
return li
def save_mydict(dict, name):
# 字典保存
import pickle
f_save = open(name + '.pkl', 'wb')
pickle.dump(dict, f_save)
f_save.close()
def load_mydict(name):
import pickle
# # 读取
f_read = open(name + '.pkl', 'rb')
dict2 = pickle.load(f_read)
f_read.close()
return dict2
def train(model,Dataload,epochs=5):
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.003)
train_losses, test_losses = [], []
for i in range(epochs):
for data,label in Dataload:
optimizer.zero_grad()
pre = model(data)
loss = criterion(pre,label)
loss.backward()
optimizer.step()
running_loss += loss.item()
return model
from tqdm import tqdm
def generate_representation(labels, datt):
print('Now we begin to generate embedding \n------------****-----------')
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device2 = torch.device("cpu")
import esm
# Load ESM-1b model
model, alphabet = esm.pretrained.esm1b_t33_650M_UR50S()
# Load ESM-2 model
# model, alphabet = esm.pretrained.esm2_t33_650M_UR50D()
# model, alphabet = esm.pretrained.esm2_t48_15B_UR50D()
batch_converter = alphabet.get_batch_converter()
sequence_representations = []
sequence_total = []
labels_list = []
for i in tqdm(range(0, len(datt), 10),desc='processing'):
data = list(zip(labels[i:i + 10], datt[i:i + 10]))
batch_labels, batch_strs, batch_tokens = batch_converter(data)
# print('------')
# print(len(batch_tokens))
# print(len(labels_list))
# print(len(sequence_representations))
# print('------')
for item in batch_labels:
labels_list.append(item)
batch_tokens = batch_tokens.cuda()
# print(batch_tokens)
# Extract per-residue representations
with torch.no_grad():
model = model.cuda()
results = model(batch_tokens, repr_layers=[33])
token_representations = results["representations"][33]
# print(token_representations[1])
# print('representation now have {} data '.format(len(token_representations)))
# print('total proecess {}'.format(i))
for j, (_, seq) in enumerate(data):
token_representations = token_representations.cpu()
sequence_total.append(token_representations[j, 1: len(seq) + 1])
return sequence_total
def generate_representation_includtoken(labels, datt):
print('Now we begin to generate embedding \n------------****-----------')
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device2 = torch.device("cpu")
import esm
# Load ESM-1b model
model, alphabet = esm.pretrained.esm1b_t33_650M_UR50S()
batch_converter = alphabet.get_batch_converter()
sequence_representations = []
sequence_total = []
token_total = []
labels_list = []
for i in tqdm(range(0, len(datt), 10),desc='processing'):
data = list(zip(labels[i:i + 10], datt[i:i + 10]))
batch_labels, batch_strs, batch_tokens = batch_converter(data)
# print('------')
# print(len(batch_tokens))
# print(len(labels_list))
# print(len(sequence_representations))
# print('------')
for item in batch_labels:
labels_list.append(item)
for token in batch_tokens:
token_total.append(token)
# print(token.size())
batch_tokens = batch_tokens.cuda()
# print(batch_tokens)
# Extract per-residue representations
with torch.no_grad():
model = model.cuda()
results = model(batch_tokens, repr_layers=[33])
token_representations = results["representations"][33]
# print(token_representations[1])
# print('representation now have {} data '.format(len(token_representations)))
# print('total proecess {}'.format(i))
for j, (_, seq) in enumerate(data):
token_representations = token_representations.cpu()
sequence_total.append(token_representations[j, 1: len(seq) + 1])
return sequence_total,token_total
class classifier(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(1280, 1)
self.dropout = nn.Dropout(p=0.2)
def forward(self, x):
# make sure input tensor is flattened
x = x.view(x.shape[0], -1)
return torch.sigmoid(self.fc1(x))
def getBatch(batch_size, train_data):
import random
random.shuffle(train_data)
sindex = 0
eindex = batch_size
while eindex < len(train_data):
batch = train_data[sindex:eindex]
temp = eindex
eindex = eindex + batch_size
sindex = temp
yield batch
if eindex >= len(train_data):
batch = train_data[sindex:]
yield batch
import numpy as np
def get_padding(train_total):
numpy_value=[]
for item in train_total:
num_list = list(item.numpy())
while len(num_list)<1022:
num_list.append((np.zeros(1280)))
numpy_value.append(num_list)
return numpy_value