-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeep_binning.py
256 lines (132 loc) · 5.68 KB
/
Deep_binning.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
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 9 18:01:40 2019
@author: ly
"""
#%%[1]input kmer.csv
def usage ():
print("usage:")
print(" Python encoder.py -i inputfile -n num_hidden -e iteration_number -l learning rate")
print(" -i inputfile should be in csv format")
# In[1]:
import sys
import getopt
opts, args = getopt.getopt(sys.argv[1:], "hi:n:e:l:")
input_file=""
for op, value in opts:
if op == "-i":
input_file = value
elif op == "-n":
n_hidden=int(value)
elif op == "-h":
usage()
sys.exit()
elif op=="-e":
training_epochs=int(value)
elif op=="-l":
learning_rate=float(value)
import numpy as np
import sklearn.preprocessing as prep
import tensorflow as tf
import csv
#input_file="Contigs_Sharon.txt_4mer.csv"
csv_reader=csv.reader(open(input_file))
title=[]
X=[]
for row in csv_reader:
title.append(row[0])
X.append(row[1:])
#%%[2]。
def xavier_init(fan_in, fan_out, constant = 1):
"""
目的是合理初始化权重。
参数:
fan_in --行数;
fan_out -- 列数;
constant --常数权重,条件初始化范围的倍数。
return 初始化后的权重tensor.
"""
low = -constant * np.sqrt(6.0 / (fan_in + fan_out))
high = constant * np.sqrt(6.0 / (fan_in + fan_out))
return tf.random_uniform((fan_in, fan_out),minval = low, maxval = high, dtype = tf.float32)
#%%
class AdditiveGaussianNoiseAutoencoder(object):
def __init__(self, n_input, n_hidden, transfer_function =tf.nn.sigmoid, optimizer = tf.train.AdamOptimizer(),
scale = 0.1):
self.n_input = n_input
self.n_hidden = n_hidden
self.transfer = transfer_function
self.scale = tf.placeholder(tf.float32)
self.training_scale = scale
network_weights = self._initialize_weights()
self.weights = network_weights
self.x = tf.placeholder(tf.float32, [None, self.n_input])
self.hidden = self.transfer(tf.add(tf.matmul(self.x +scale * tf.random_normal((n_input,)),
self.weights['w1']),
self.weights['b1']))
self.reconstruction = tf.add(tf.matmul(self.hidden,self.weights['w2']), self.weights['b2'])
self.cost = 0.5 *tf.reduce_sum(tf.pow(tf.subtract(self.reconstruction, self.x), 2.0))
self.optimizer = optimizer.minimize(self.cost)
init = tf.global_variables_initializer()
self.sess = tf.Session()
self.sess.run(init)
def _initialize_weights(self):
all_weights = dict()
all_weights['w1'] = tf.Variable(xavier_init(self.n_input,self.n_hidden))
all_weights['b1'] = tf.Variable(tf.zeros([self.n_hidden],dtype = tf.float32))
all_weights['w2'] = tf.Variable(tf.zeros([self.n_hidden,self.n_input], dtype = tf.float32))
all_weights['b2'] = tf.Variable(tf.zeros([self.n_input],dtype = tf.float32))
return all_weights
def partial_fit(self, X):
cost, opt = self.sess.run((self.cost, self.optimizer),feed_dict = {self.x: X,
self.scale: self.training_scale})
return cost
def calc_total_cost(self, X):
return self.sess.run(self.cost, feed_dict = {self.x: X, self.scale:self.training_scale})
def transform(self, X):
return self.sess.run(self.hidden, feed_dict = {self.x: X,self.scale:self.training_scale})
def generate(self, hidden = None):
if hidden is None:
hidden = np.random.normal(size = self.weights["b1"])
return self.sess.run(self.reconstruction, feed_dict ={self.hidden: hidden})
def reconstruct(self, X):
return self.sess.run(self.reconstruction, feed_dict ={self.x: X,
self.scale: self.training_scale})
def getWeights(self):
return self.sess.run(self.weights['w1'])
def getBiases(self):
return self.sess.run(self.weights['b1'])
# In[]。
def get_random_block_from_data(data, batch_size):
start_index = np.random.randint(0, len(data) - batch_size)
return data[start_index:(start_index + batch_size)]
n_samples = len(X)
n_input=len(X[0])
#training_epochs = 200
batch_size = 128
display_step = 1
autoencoder = AdditiveGaussianNoiseAutoencoder(n_input,
n_hidden,
transfer_function =tf.nn.softplus,
optimizer =tf.train.AdamOptimizer(learning_rate),
scale = 0.01)
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(n_samples / batch_size)
# Loop over all batches
for i in range(total_batch):
batch_xs = get_random_block_from_data(X, batch_size)
# Fit training using batch data
cost = autoencoder.partial_fit(batch_xs)
# Compute average loss
avg_cost += cost / n_samples
# Display logs per epoch step
if epoch % display_step == 0:
print("Epoch:", '%04d' % (epoch + 1), "cost=","{:.9f}".format(avg_cost))
# In[] 。
x=[]
x=autoencoder.transform(X)
import pandas as pd
test=pd.DataFrame(index=title,data=x)
output_file=input_file+"_encoder.csv"
test.to_csv(output_file,encoding='gbk') #,header=0