Duplicate/Replicate 个具有相同属性的 tensorflow 层以形成图形

Duplicate/Replicate tensorflow layers with same properties to form a graph

我尝试使用神经网络实现的任务与其最常见的用法略有不同。我尝试通过优化代表物理属性的网络权重,将某些东西从输入层传播到输出层来模拟物理过程。

因此我需要一个 150 层的网络,其中每一层都具有相同的属性,形式为

mx+b

其中 x 是我想优化的变量,m 是每个层都相同的外部因素(b 现在未使用)。

我想自动化创建图表的过程,而不是 copy/paste 每层。那么是否有将第一层的结构复制到所有后续层的功能?

在 tensorflow 中,它应该如下所示:

graph = tf.Graph()
with graph.as_default():

    # Input data.
    tf_input = tf.placeholder(tf.float32, shape=(n_data, n))
    tf_spatial_grid = tf.constant(m_index_mat)
    tf_ph_unit = tf.const(m_unit_mat)
    tf_output = tf.placeholder(tf.float32, shape=(n_data, n))

    # new hidden layer 1    
    hidden_weights = tf.Variable( tf.truncated_normal([n*n, 1]) )
    hidden_layer = tf.nn.matmul( tf.matmul( tf_input, hidden_weights), tf_ph_unit)

    # new hidden layer 2
    hidden_weights_2 = tf.Variable( tf.truncated_normal([n*n, 1]) )
    hidden_layer_2 = tf.nn.matmul( tf.matmul( hidden_layer, hidden_weights_2), tf_ph_unit)

......

    # new hidden layer n
    hidden_weights_n = tf.Variable( tf.truncated_normal([n*n, 1]) )
    hidden_layer_n = tf.nn.matmul( tf.matmul( hidden_layer_m, hidden_weights_n), tf_ph_unit)

...

那么是否有任何选项可以以某种方式自动执行此过程?也许我遗漏了什么

非常感谢任何帮助!

实现这一点的最简单方法是创建一个构建图层的函数,然后简单地多次调用该函数,可能是在一个循环中。

例如:

def layer(input):
    hidden_weights = tf.Variable( tf.truncated_normal([n*n, 1]) )
    hidden_layer = tf.nn.matmul( tf.matmul( input, hidden_weights), tf_ph_unit)
    return hidden_layer

然后:

input = tf_input
for i in range(10):
    input = layer(input)