-
Notifications
You must be signed in to change notification settings - Fork 3
/
jsnn.py
181 lines (145 loc) · 6.73 KB
/
jsnn.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created by Bakhtawar Noor and Judit Kisistók
Aarhus University, 2018
"""
# import tensorflow as tf
import numpy as np
import tqdm
import MSA_parser
import parse
from keras.models import Sequential
from keras.layers import Dense, Activation, Reshape, Flatten, Input
from keras.layers import Conv1D, MaxPooling1D
from keras.layers import BatchNormalization, Dropout
from keras.layers import LSTM, GRU, Masking, Embedding, SimpleRNN
from keras.optimizers import SGD, RMSprop, Adam
from keras import initializers
from sklearn.utils import class_weight
import math
import matplotlib.pyplot as plt
plt.switch_backend('agg')
from keras import regularizers
import ThreeStateGenerator
import os
from sklearn.model_selection import KFold
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
# Associating each character with a number (Encoding the characters for the model)
ACIDS = {'<': 1, '>': 2, 'A': 3, 'C': 4, 'E': 5, 'D': 6, 'G': 7, 'F': 8, 'I': 9, 'H': 10, 'K': 11, 'M': 12, 'L': 13, 'N':14, 'Q':15, 'P':16, 'S':17, 'R':18, 'T':19, 'W':20, 'V':21, 'Y':22, 'X':23, 'U': 24, 'Z': 25, 'B':26, 'O':27}
#LABELS = {'<': 1, '>': 2, 'NoSeq': 2, 'L': 3, ' ':3, 'B': 4, 'E': 5, 'G': 6, 'I': 7, 'H': 8, 'S': 9, 'T': 10}
LABELS = {'<': 1, '>': 2, '?': 2, 'S': 3, ' ': 4, 'H': 5}
# return two lists of amino acid / label strings
def parse_file(data_file):
X_strings = ''
Y_strings = ''
next_line_is_seq = False
next_line_is_output = False
# String formatting for the input
with open(data_file, 'r') as f:
for line in f:
if 'A:sequence' in line:
next_line_is_output = False
next_line_is_seq = True
X_strings = X_strings + '<'
elif 'A:secstr' in line:
next_line_is_seq = False
next_line_is_output = True
Y_strings = Y_strings + '<'
elif (':sequence' in line) or ('secstr' in line):
next_line_is_seq = False
next_line_is_output = False
elif next_line_is_seq:
X_strings = X_strings + line[:-1]
elif next_line_is_output:
Y_strings = Y_strings + line[:-1]
splitX = X_strings.split('<')[1:] # Input primary protein structure
splitY = Y_strings.split('<')[1:] # Label secondary protein structure
assert len(splitX) == len(splitY)
return splitX, splitY
def create_sequence(string, vocab_dict):
sequence = []
# One hot encoding
vec_length = np.max(list(vocab_dict.values()))
# print vec_length
for i in range(len(string)):
temp = np.zeros(vec_length)
temp[vocab_dict[string[i]]-1] = 1
sequence.append(temp)
return sequence
def pad_sequences(input_data, window_size=5):
padded_sequence = []
for i in tqdm.tqdm(range(len(input_data))):
padded_sequence.append(np.pad(input_data[i], math.ceil(window_size/2), 'constant'))
return padded_sequence
def create_window_data(input_data, output_data, window_size=21):
windowed_input = []
output = []
# Padding input sequences on both sides with zeros
input_data = pad_sequences(input_data=input_data, window_size=window_size)
for j in tqdm.tqdm(range(len(output_data))):
for i in range(len(output_data[j])):
slice_ = input_data[j][i:i+window_size]
windowed_input.append(np.array(slice_).astype(float))
output.append(output_data[j][i])
return np.array(windowed_input), output
def build_mlp(class_weight, train_data,input_data,output_data,model, num_nodes = 100, num_layers = 2,
activation='relu', ouput_activation='softmax',
kernel_regularizer = None,batch_size = 100,optimizer = "adam"):
"""
Builds a basic neural network in Keras.
By default, assumes a multiclass classification
problem (softmax output).
"""
model.add(Dense(num_nodes, activation=activation,
input_shape=(train_data.shape[1],train_data.shape[2]),kernel_regularizer = None))
model.add(Flatten())
for l in range(num_layers-1):
model.add(Dense(num_nodes, activation=activation,kernel_regularizer = regularizers.l2(0.01)))
model.add(Dropout(0.2))
model.add(Dense(5, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer=optimizer,metrics=['accuracy'])
history = model.fit(input_data, output_data, validation_split = 0.2, epochs =70, batch_size = batch_size,class_weight = class_weight)
return model,history
def jNN_msa(X):
path = os.getcwd()
path = os.path.join(path,"DATA")
path_1 = os.chdir(path)
X_strings,Y_strings,msa,file_lst = MSA_parser.parse_file(path_1)
Y_strings = ThreeStateGenerator.replace_all(Y_strings)
profile_table,X_strings = MSA_parser.making_profile_table(msa)
input_sequences = []
output_sequences = []
for i in tqdm.tqdm(range(len(X_strings))):
input_sequences.append(create_sequence(X_strings[i], ACIDS))
output_sequences.append(create_sequence(Y_strings[i], LABELS))
input_data, output_data = create_window_data(input_data=input_sequences, output_data=output_sequences)
output_data = np.array(output_data)
train_data = input_data[:int(0.8*input_data.shape[0])]
train_labels = output_data[:int(0.8*output_data.shape[0])]
test_data = input_data[int(0.8*input_data.shape[0]):]
test_labels = output_data[int(0.8*output_data.shape[0]):]
# To remove class imbalance....
class_weight1 = class_weight.compute_class_weight('balanced', np.unique([np.argmax(i) for i in list(train_labels)]), [np.argmax(i) for i in list(train_labels)])
model = Sequential()
model, history = build_mlp(class_weight1, train_data,input_data,output_data,model, num_nodes=180, num_layers=2,
activation='relu',kernel_regularizer = None,batch_size = 100,optimizer = "adam")
###Prediction
Xnew,s = MSA_parser.making_profile_table(X)
Ynew = '>' * len(s[0])
lst = []
lst.append(Ynew)
input_sequences = []
output_sequences = []
for i in tqdm.tqdm(range(len(s))):
input_sequences.append(create_sequence(s[i], ACIDS))
output_sequences.append(create_sequence(lst[i], LABELS))
input_data, output_data = create_window_data(input_data=input_sequences, output_data=output_sequences)
output_data = np.array(output_data)
output = model.predict(input_data)
INV_LABELS = {}
for key in LABELS.keys():
INV_LABELS[LABELS[key]] = key
prediction = ''.join([INV_LABELS[np.argmax(output[i])+1] for i in range(output.shape[0])])
return prediction