-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
382 lines (310 loc) · 14.6 KB
/
model.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
from math import exp
import keras.layers
import numpy as np
import tensorflow as tf
from keras import layers, initializers, Model
from tensorflow import sigmoid
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense
from tensorflow.keras.models import Model
KERNEL_INITIALIZER = {
"class_name": "TruncatedNormal",
"config": {
"stddev": 0.2
}
}
BIAS_INITIALIZER = "Zeros"
class Attention_Layer(layers.Layer):
# input = 20*9*21 == 20 * [9*21]
def __init__(self, name: str = None, init_value={}): # dim[0] = 32
super().__init__(name=name)
self.layer_scale_init_value = 1e-6
# aa_list = A,R,N,D,C,Q,E,G,H,I,L,K,M,F,P,S,T,W,Y,V
self.conv_20_block = [
layers.Conv1D(filters=1, kernel_size=9, activation=sigmoid,
kernel_initializer=keras.initializers.Constant(value=init_value[i])
)
for i in
["A", "R", "N", "D", "C", "Q", "E", "G", "H", "I", "L", "K", "M", "F", "P", "S", "T", "W", "Y", "V"]
]
self.norm = layers.LayerNormalization(epsilon=1e-6, name="norm")
def build(self, input_shape):
if self.layer_scale_init_value > 0:
self.gamma = self.add_weight(shape=[input_shape[-1]],
initializer=initializers.Constant(self.layer_scale_init_value),
trainable=True,
dtype=tf.float32,
name="gamma")
else:
self.gamma = None
def call(self, x, training=False):
print(x.shape)
ans_att = []
for i, conv in enumerate(self.conv_20_block):
att = conv(x[:, i, :, :])
ans_att.append(att)
# [20,batch_size,1,1]
return ans_att
class Attention(layers.Layer):
# input = 20*9*21 == 20 * [9*21]
def __init__(self): # dim[0] = 32
super().__init__()
self.Att_Block = Attention_Layer(
init_value={'P': 0, 'Y': 1.0, 'F': 0.032992930086410056, 'A': 0.2875098193244305, 'M': 0.05420267085624509,
'Q': 0.24823252160251374, 'E': 0.23644933228593873, 'R': 0.2199528672427337,
'N': 0.23095051060487037, 'H': 0.07855459544383346, 'T': 0.42498036135113904,
'D': 0.1681068342498036, 'L': 0.2474469756480754, 'I': 0.11626080125687353,
'K': 0.16496465043205027, 'W': 0.2513747054202671, 'V': 0.14846818538884524,
'G': 0.02199528672427337, 'C': 0.0, 'S': 0.14611154752553024})
def call(self, x, training=False):
attention = self.Att_Block(x)
attention = tf.transpose(attention, perm=(1, 0, 2, 3))
return attention
# [20, 9, 21]
# [2*2*5, 3*3*3 , 21]
class Block(layers.Layer):
"""
Args:
dim (int): Number of input channels.
drop_rate (float): Stochastic depth rate. Default: 0.0
layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
"""
# 5 * 3
def __init__(self, dim, drop_rate=0.2, layer_scale_init_value=1e-6, name: str = None):
super().__init__(name=name)
self.layer_scale_init_value = layer_scale_init_value
self.dwconv = layers.DepthwiseConv2D((7, 3),
padding="same",
depthwise_initializer=KERNEL_INITIALIZER,
bias_initializer=BIAS_INITIALIZER,
name="dwconv")
self.norm = layers.LayerNormalization(epsilon=1e-6, name="norm")
self.pwconv1 = layers.Dense(4 * dim,
kernel_initializer=KERNEL_INITIALIZER,
bias_initializer=BIAS_INITIALIZER,
name="pwconv1")
self.act = layers.Activation("gelu")
self.pwconv2 = layers.Dense(dim,
kernel_initializer=KERNEL_INITIALIZER,
bias_initializer=BIAS_INITIALIZER,
name="pwconv2")
self.drop_path = layers.Dropout(drop_rate, noise_shape=(None, 1, 1, 1)) if drop_rate > 0 else None
def build(self, input_shape):
if self.layer_scale_init_value > 0:
self.gamma = self.add_weight(shape=[input_shape[-1]],
initializer=initializers.Constant(self.layer_scale_init_value),
trainable=True,
dtype=tf.float32,
name="gamma")
else:
self.gamma = None
def call(self, x, training=False):
shortcut = x
x = self.dwconv(x)
x = self.norm(x, training=training)
x = self.pwconv1(x)
x = self.act(x)
x = self.pwconv2(x)
if self.gamma is not None:
x = self.gamma * x
if self.drop_path is not None:
x = self.drop_path(x, training=training)
return shortcut + x
class Stem(layers.Layer): # 融合第三个维度,(None, [20, 9, 21] --> (None, [20, 9, 7]
def __init__(self, dim, name: str = None): # dim[0] = 32
super().__init__(name=name)
self.conv = layers.Conv2D(dim,
kernel_size=(1, 1),
strides=(1, 1),
# padding="same",
kernel_initializer=KERNEL_INITIALIZER,
bias_initializer=BIAS_INITIALIZER,
name="conv2d")
self.norm = layers.LayerNormalization(epsilon=1e-6, name="norm")
def call(self, x, training=False):
x = self.conv(x)
x = self.norm(x, training=training)
return x
class DownSample(layers.Layer):
def __init__(self, dim, name: str = None):
super().__init__(name=name)
self.norm = layers.LayerNormalization(epsilon=1e-6, name="norm")
self.conv = layers.Conv2D(dim,
kernel_size=(2, 3),
strides=(2, 3),
# padding="same",
kernel_initializer=KERNEL_INITIALIZER,
bias_initializer=BIAS_INITIALIZER,
name="conv2d")
def call(self, x, training=False):
x = self.norm(x, training=training)
x = self.conv(x)
return x
def tt():
attention = Attention()
train_ds = generate_MHC_ms("ms_{}_x.npy".format(0), "ms_{}_y.npy".format(0), batch_size=700)
a = np.zeros([11, 20, 9, 21])
for images, labels in train_ds:
print(images.shape)
temp = attention.predict(images)
print(temp[1])
temp = temp * images
# ans = temp2 * images
print(np.array(temp).shape)
break
class ConvNeXt_attention(Model):
def __init__(self, num_classes: int, depths: list, dims: list, drop_path_rate: float = 0.,
layer_scale_init_value: float = 1e-6):
super().__init__()
cur = 0
dp_rates = np.linspace(start=0, stop=drop_path_rate, num=sum(depths))
self.stage1 = [Block(dim=dims[0],
drop_rate=dp_rates[cur + i],
layer_scale_init_value=layer_scale_init_value,
name=f"stage1_block{i}")
for i in range(depths[0])]
cur += depths[0]
self.downsample1 = DownSample(dims[1], name="downsample1")
self.stage2 = [Block(dim=dims[1],
drop_rate=dp_rates[cur + i],
layer_scale_init_value=layer_scale_init_value,
name=f"stage2_block{i}")
for i in range(depths[1])]
self.downsample2 = DownSample(dims[2], name="downsample2")
cur += depths[1]
# self.maxpool = layers.MaxPool2D(pool_size=(2, 1), strides=2)
self.norm = layers.LayerNormalization(epsilon=1e-6, name="norm")
self.head = layers.Dense(units=num_classes,
kernel_initializer=KERNEL_INITIALIZER,
bias_initializer=BIAS_INITIALIZER,
name="head",
activation='Softmax')
self.attention = Attention()
self.flatten = tf.keras.layers.Flatten()
def call(self, x, training=False):
# x = self.stem(x, training=training) # [20, 9, 21] --> [20, 9, 7] dim[0] = 7 ,
att = self.attention(x)
x = att * x
for block in self.stage1:
x = block(x, training=training) # 2*3 block
x = self.downsample1(x, training=training) # down sample ,[20, 9, 7] --> [10, 3, 42] dim[1]=42
for block in self.stage2:
x = block(x, training=training) # 2*3 block
x = self.downsample2(x, training=training) # down sample ,[10, 3, 42] --> [5, 1, 252] dim[2]=252
x = tf.reduce_mean(x, axis=[1, 2])
# x = self.flatten(x)
x = self.norm(x, training=training)
x = self.head(x)
return x
# [20, 9, 21]
# [2*2*5, 3*3*3 , 21]
def convnext_H3N2(num_classes: int):
model = ConvNeXt_attention(depths=[8, 8],
dims=[21, 14, 28],
num_classes=num_classes)
return model
def convnext_4_4(num_classes: int):
model = ConvNeXt_attention(depths=[4, 4],
dims=[21, 14, 28],
num_classes=num_classes)
return model
def convnext_10_10(num_classes: int):
model = ConvNeXt_attention(depths=[10, 10],
dims=[21, 14, 28],
num_classes=num_classes)
return model
def convnext_12_12(num_classes: int):
model = ConvNeXt_attention(depths=[12, 12],
dims=[21, 14, 28],
num_classes=num_classes)
return model
def convnext_20_20(num_classes: int):
model = ConvNeXt_attention(depths=[20, 20],
dims=[21, 14, 28],
num_classes=num_classes)
return model
def convnext_2_2(num_classes: int):
model = ConvNeXt_attention(depths=[2, 2],
dims=[21, 14, 28],
num_classes=num_classes)
return model
def convnext_search(num_classes, depths, dims):
model = ConvNeXt_attention(depths=depths,
dims=dims,
num_classes=num_classes)
return model
def model1_MHCflurry_CNN(num_classes=2):
input_shape1 = (49, 21, 1)
input1 = Input(shape=input_shape1)
conv1_1 = Conv2D(128, kernel_size=(3, 7), activation='relu')(input1)
pool1_1 = MaxPooling2D(pool_size=(2, 1), padding='same')(conv1_1)
conv1_2 = Conv2D(32, kernel_size=(2, 1), activation='relu')(pool1_1)
pool1_2 = MaxPooling2D(pool_size=(2, 1), padding='same')(conv1_2)
flat1 = Flatten()(pool1_2)
dense1 = Dense(32)(flat1)
output_layer = Dense(num_classes, activation='softmax')(dense1)
model = Model(inputs=[input1], outputs=output_layer)
model.compile(loss="binary_crossentropy",
optimizer="sgd",
metrics=["accuracy"])
return model
def model2_NetMHCpan4_CNN(num_classes=2):
input_shape2 = (43, 21, 1)
input2 = Input(shape=input_shape2)
conv2_1 = Conv2D(128, kernel_size=(3, 7), activation='relu')(input2)
pool2_1 = MaxPooling2D(pool_size=(2, 1), padding='same')(conv2_1)
conv2_2 = Conv2D(32, kernel_size=(2, 1), activation='relu')(pool2_1)
pool2_2 = MaxPooling2D(pool_size=(2, 1), padding='same')(conv2_2)
flat2 = Flatten()(pool2_2)
dense1 = Dense(32)(flat2)
output_layer = Dense(num_classes, activation='softmax')(dense1)
model = Model(inputs=[input2], outputs=output_layer)
model.compile(loss="binary_crossentropy",
optimizer="sgd",
metrics=["accuracy"])
return model
def model3_MSF_CNN(num_classes=2):
input_shape3 = (9, 7, 5)
input3 = Input(shape=input_shape3)
conv3_1 = Conv2D(128, kernel_size=(3, 7), activation='relu')(input3)
pool3_1 = MaxPooling2D(pool_size=(2, 1), padding='same')(conv3_1)
conv3_2 = Conv2D(32, kernel_size=(2, 1), activation='relu')(pool3_1)
pool3_2 = MaxPooling2D(pool_size=(2, 1), padding='same')(conv3_2)
flat3 = Flatten()(pool3_2)
dense1 = Dense(32)(flat3)
output_layer = Dense(num_classes, activation='softmax')(dense1)
model = Model(inputs=[input3], outputs=output_layer)
model.compile(loss="binary_crossentropy",
optimizer="sgd",
metrics=["accuracy"])
return model
def model4_ANN40_CNN(num_classes=2): # 43, 21, 1
input_shape4 = (43, 21, 1)
input3 = Input(shape=input_shape4)
conv3_1 = Conv2D(128, kernel_size=(3, 7), activation='relu')(input3)
pool3_1 = MaxPooling2D(pool_size=(2, 1), padding='same')(conv3_1)
conv3_2 = Conv2D(32, kernel_size=(2, 1), activation='relu')(pool3_1)
pool3_2 = MaxPooling2D(pool_size=(2, 1), padding='same')(conv3_2)
flat3 = Flatten()(pool3_2)
dense1 = Dense(32)(flat3)
output_layer = Dense(num_classes, activation='softmax')(dense1)
model = Model(inputs=[input3], outputs=output_layer)
model.compile(loss="binary_crossentropy",
optimizer="sgd",
metrics=["accuracy"])
return model
def model5_DeepHLA_CNN(num_classes=2): # 49, 21, 1
input_shape5 = (49, 21, 1)
input3 = Input(shape=input_shape5)
conv3_1 = Conv2D(128, kernel_size=(3, 7), activation='relu')(input3)
pool3_1 = MaxPooling2D(pool_size=(2, 1), padding='same')(conv3_1)
conv3_2 = Conv2D(32, kernel_size=(2, 1), activation='relu')(pool3_1)
pool3_2 = MaxPooling2D(pool_size=(2, 1), padding='same')(conv3_2)
flat3 = Flatten()(pool3_2)
dense1 = Dense(32)(flat3)
output_layer = Dense(num_classes, activation='softmax')(dense1)
model = Model(inputs=[input3], outputs=output_layer)
model.compile(loss="binary_crossentropy",
optimizer="sgd",
metrics=["accuracy"])
return model
print(model3_MSF_CNN(2).summary())