|
| 1 | +import tensorflow as tf |
| 2 | +import numpy as np |
| 3 | +class siamese: |
| 4 | + |
| 5 | + # Create model |
| 6 | + def __init__(self,input_dim): |
| 7 | + self.x1 = tf.placeholder(tf.float32, [None, input_dim]) |
| 8 | + self.x2 = tf.placeholder(tf.float32, [None, input_dim]) |
| 9 | + |
| 10 | + with tf.variable_scope("siamese") as scope: |
| 11 | + self.a1,self.b1,self.o1 = self.network(self.x1) |
| 12 | + scope.reuse_variables() |
| 13 | + self.a1,self.b2,self.o2 = self.network(self.x2) |
| 14 | + |
| 15 | + # Create loss |
| 16 | + self.y_ = tf.placeholder(tf.float32, [None]) |
| 17 | + self.loss = self.loss_with_cds() |
| 18 | + |
| 19 | + def network(self, x): |
| 20 | + weights = [] |
| 21 | + kernel_size =150 |
| 22 | + stride = 18 |
| 23 | + depth=40 |
| 24 | + conv1 = self.conv_layer(x, kernel_size,stride,depth,'conv1') |
| 25 | + conv1r = tf.nn.relu(conv1) |
| 26 | + n_prev_weight = int(x.get_shape()[1]) |
| 27 | + conv1_d = tf.reshape(conv1r,[-1, int(round(n_prev_weight/stride+0.5)*depth)]) |
| 28 | + |
| 29 | + fc1 = self.fc_layer(conv1_d, 1500, "fc1") |
| 30 | + ac1 = tf.nn.relu(fc1) |
| 31 | + fc2 = self.fc_layer(ac1, 600, "fc2") |
| 32 | + ac2 = tf.nn.relu(fc2) |
| 33 | + fc3 = self.fc_layer(ac2, 200, "fc3") |
| 34 | + return fc1,fc2,fc3 |
| 35 | + |
| 36 | + def fc_layer(self, bottom, n_weight, name): |
| 37 | + print( bottom.get_shape()) |
| 38 | + n_prev_weight = bottom.get_shape()[1] |
| 39 | + W = tf.get_variable(name+'W', dtype=tf.float32, shape=[n_prev_weight, n_weight], initializer=tf.contrib.layers.xavier_initializer()) |
| 40 | + b = tf.get_variable(name+'b', dtype=tf.float32, initializer=tf.random_uniform([n_weight],-0.001,0.001, dtype=tf.float32)) |
| 41 | + fc = tf.nn.bias_add(tf.matmul(bottom, W), b) |
| 42 | + return fc |
| 43 | + |
| 44 | + def conv_layer(self, bottom, kernel_size, stride, depth, name): |
| 45 | + n_prev_weight = int(bottom.get_shape()[1]) |
| 46 | + num_channels = 1 # for 1 dimension |
| 47 | + inputlayer = tf.reshape(bottom, [-1,n_prev_weight,1]) |
| 48 | + initer = tf.truncated_normal_initializer(stddev=0.1) |
| 49 | + W = tf.get_variable(name+'W', dtype=tf.float32, shape=[kernel_size, num_channels, depth], initializer=tf.contrib.layers.xavier_initializer()) |
| 50 | + b = tf.get_variable(name+'b', dtype=tf.float32, initializer=tf.constant(0.001, shape=[depth*num_channels], dtype=tf.float32)) |
| 51 | + |
| 52 | + conv = tf.nn.bias_add( tf.nn.conv1d(inputlayer, W, stride, padding='SAME'), b) |
| 53 | + return conv |
| 54 | + |
| 55 | + def loss_with_cds(self): |
| 56 | + labels_t = self.y_ |
| 57 | + cds = tf.reduce_sum(tf.multiply(self.o1,self.o2),1) |
| 58 | + eucd2 = tf.reduce_mean(tf.pow(tf.subtract(labels_t,cds),2)) |
| 59 | + eucd = tf.sqrt(eucd2, name="eucd") |
| 60 | + return eucd |
| 61 | + |
| 62 | + |
0 commit comments