python - 在 Tensorflow 模型中添加低层

标签 python tensorflow neural-network

为了开发一些迁移学习算法,我使用了一些经过训练的神经网络并添加了层。我正在使用 Tensorflow 和 python。

在 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)

然后在训练中,您将使用您的图层以及下面的所有图层。您还可以卡住一些层,在 session 期间导入经过训练的变量等。

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

直到现在,我还没有找到用 tensorflow 做到这一点的便捷方法。你知道吗?还是根本不可能?

提前致谢。

最佳答案

您不能在图表的现有层之间插入层,但您可以在导入图表的过程中进行一些重新布线。正如 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}

夸格。它将传递给 import_graph_def。

关于python - 在 Tensorflow 模型中添加低层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44585310/

相关文章:

python - 如何恢复 tensorflow 中的占位符?

python - Keras:如何在自定义损失中获取张量尺寸?

neural-network - Encog 神经网络错误未改变

python - 改进 Python NetworkX 图形布局

python - DataFrame 和 Series 之间的按元素乘法返回 NaN

C++ Tensorflow lite,某些函数的 undefined reference

algorithm - 2 个神经元的 ANN 可以解决 XOR 问题吗?

python - 如何使用python和 Mechanize 从php页面获取所有链接

python - 在 Python 中对数组的各个部分求平均值

machine-learning - 神经网络的初始偏差值