2017-06-16 40 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

非常感謝!我會馬上試試。 –