-
Notifications
You must be signed in to change notification settings - Fork 29
/
encoder.py
59 lines (43 loc) · 2.04 KB
/
encoder.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
import tensorflow as tf
from tensorflow.python import pywrap_tensorflow
WEIGHT_INIT_STDDEV = 0.1
class Encoder(object):
def __init__(self, model_pre_path):
self.weight_vars = []
self.model_pre_path = model_pre_path
with tf.variable_scope('encoder'):
self.weight_vars.append(self._create_variables(1, 16, 3, scope='conv1_1'))
self.weight_vars.append(self._create_variables(16, 32, 3, scope='conv1_2'))
def _create_variables(self, input_filters, output_filters, kernel_size, scope):
if self.model_pre_path:
reader = pywrap_tensorflow.NewCheckpointReader(self.model_pre_path)
with tf.variable_scope(scope):
kernel = tf.Variable(reader.get_tensor('encoder/' + scope + '/kernel'), name='kernel')
bias = tf.Variable(reader.get_tensor('encoder/' + scope + '/bias'), name='bias')
else:
with tf.variable_scope(scope):
shape = [kernel_size, kernel_size, input_filters, output_filters]
kernel = tf.Variable(tf.truncated_normal(shape, stddev=WEIGHT_INIT_STDDEV), name='kernel')
bias = tf.Variable(tf.zeros([output_filters]), name='bias')
return (kernel, bias)
def encode(self, image):
final_layer_idx = len(self.weight_vars) - 1
out = image
for i in range(len(self.weight_vars)):
kernel, bias = self.weight_vars[i]
if i == final_layer_idx:
out = conv2d(out, kernel, bias, use_relu=False)
else:
out = conv2d(out, kernel, bias)
# print('encoder ', i)
# print('encoder out:', out.shape)
return out
def conv2d(x, kernel, bias, use_relu=True):
# padding image with reflection mode
x_padded = tf.pad(x, [[0, 0], [1, 1], [1, 1], [0, 0]], mode='REFLECT')
# conv and add bias
out = tf.nn.conv2d(x_padded, kernel, strides=[1, 1, 1, 1], padding='VALID')
out = tf.nn.bias_add(out, bias)
if use_relu:
out = tf.nn.relu(out)
return out