2017-06-16 42 views
3

尝试开发一些转移学习算法,我使用一些训练好的神经网络并添加图层。我使用Tensorflow和python。在Tensorflow模型中添加低层

看来很常见的Tensorflow利用现有的图表:您使用metaGraphs导入图形,例如,那么你通过增加节点设置新的高度层。例如,我发现这个代码here

vgg_saver = tf.train.import_meta_graph(dir + '/vgg/results/vgg-16.meta') 
# Access the graph 
vgg_graph = tf.get_default_graph() 

# Retrieve VGG inputs 
self.x_plh = vgg_graph.get_tensor_by_name('input:0') 

# Choose some node 
output_conv =vgg_graph.get_tensor_by_name('conv1_2:0') 

# Build further operations 
output_conv_shape = output_conv.get_shape().as_list() 
W1 = tf.get_variable('W1', shape=[1, 1, output_conv_shape[3], 32],initializer=tf.random_normal_initializer(stddev=1e-1)) 
b1 = tf.get_variable('b1', shape=[32], initializer=tf.constant_initializer(0.1)) 
z1 = tf.nn.conv2d(output_conv, W1, strides=[1, 1, 1, 1], padding='SAME') + b1 
a = tf.nn.relu(z1) 

然后在训练中,你会用你的层次以及所有低于。您也可以冻结一些层,进口训练有素的变量在会议期间,等

然而,在我的方法,我需要添加的输入和第一层之间的新低层,并用我的层加上那些上面。因此,我不能只在图表底部添加节点:我需要在输入后立即插入节点。

直到现在我还没有找到方便的方法来做到这一点与tensorflow。你有什么想法吗?还是仅仅是不可能的?

在此先感谢。

+0

一种方式可能会沿着这里的第一个答案https://stackoverflow.com/questions/33748552/tensorflow-how-to-replace-a-node-in-a-calculation-graph –

回答

1

无法插入图形的现有层之间的层,但你可以导入图形与沿途的一些重新布线。正如Pietro Tortella指出的那样,Tensorflow: How to replace a node in a calculation graph?的方法应该可行。下面是一个例子:

import tensorflow as tf 

with tf.Graph().as_default() as g1: 
    input1 = tf.placeholder(dtype=tf.float32, name="input_1") 
    l1 = tf.multiply(input1, tf.constant(2.0), name="mult_1") 
    l2 = tf.multiply(l1, tf.constant(3.0), name="mult_2") 

g1_def = g1.as_graph_def() 

with tf.Graph().as_default() as new_g: 
    new_input = tf.placeholder(dtype=tf.float32, name="new_input") 
    op_to_insert = tf.add(new_input, tf.constant(4.0), name="inserted_op") 
    mult_2, = tf.import_graph_def(g1_def, input_map={"input_1": op_to_insert}, 
            return_elements=["mult_2"]) 

原始图形看起来像this和导入的图形看起来像this

如果你想使用tf.train.import_meta_graph,你仍然可以通过在

input_map={"input_1": op_to_insert} 

kwarg。它会传递给import_graph_def。

+0

旧的输入不是连接并不会执行。如果你仍然想摆脱他们,你看看这里https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/graph_transforms/README.md – iga

+0

非常感谢!我会马上试试。 –