【发布时间】:2018-02-21 13:59:49
【问题描述】:
我正在构建 TF 图,这是我的代码的一部分:
class Model:
def __init__(self, neurons, links, input_neurons_num=4):
"""
Constructor.
:param neurons: array list of neurons
:param input_neurons_num: number of input neurons
"""
# neuron_id as key and weights entering in it as value
self.weights = {}
# neuron_id as key and neurons entering in it as value
self.connections = {}
self.graph = None
def build_graph(self):
with self.graph.as_default():
operations = {}
# create Variables for input vertices
for neuron_id in self.input_neurons:
self.inputs[neuron_id] = tf.get_variable(name=str(neuron_id), shape=(),
initializer=tf.zeros_initializer)
# create input & output vertices
for neuron_id in self.connections:
input_neuron_ids = self.connections[neuron_id]
# weights
v_weights = tf.constant(self.weights[neuron_id])
# input vertices
v_inputs = []
for input_neuron_id in input_neuron_ids:
if self.is_input_neuron(input_neuron_id):
vertex = self.inputs[input_neuron_id]
else:
# KeyError if input_neuron_id isn't alreay created
vertex = operations[input_neuron_id]
v_inputs.append(vertex)
# multiply weights and inputs
mul = tf.multiply(v_inputs, v_weights, str(neuron_id))
所以我有链接列表,其中每个链接都有 from_neuron、to_neuron 和 weight。例如:(1,2,3) => edge(connection) 从 1 到 2,权重为 2。 我想遍历所有链接并基于连接构建图。
一开始我就知道输入和输出节点。想法是遍历链接并逐步构建图。如果有 node 4: (1,4,2), (2,4,3.5) 我想创建一个 tf.operation 它将从 1 乘以输出和它的权重(2),从2的输出和它的权重(3.5),求和获得值并通过网络转发。 但问题是如果我有输入节点:1、2、3 和 node 4 与 etc.node 7 有连接,但尚未创建。它会尝试引用尚未创建的节点,我会得到 KeyError。
然后我尝试跳过与尚不存在的节点相连的节点:
deletion = []
while len(self.connections) > 0:
for neuron_id in deletion:
self.connections.pop(neuron_id, None)
deletion = []
# create input & output vertices
for neuron_id in self.connections:
# same logic with addition:
deletion.append(neuron_id)
这可行,但问题是当我在图中有循环时。这将陷入无限循环。
我必须解决这个问题的唯一想法是分两次完成。第一次通过在图中创建所有节点,第二次用实际值替换它们。我想使用占位符,但我不确定如何实现。
所以欢迎任何帮助。
【问题讨论】:
标签: python tensorflow graph cycle