【问题标题】:Tensor must be from the same graph as Tensor张量必须来自与张量相同的图
【发布时间】:2018-08-04 12:44:13
【问题描述】:

我正在做一些回归,然后我尝试在其中添加 L2 正则化。但它向我显示以下错误:

ValueError: Tensor("Placeholder:0", dtype=float32) 必须来自 与 Tensor("w_hidden:0", shape=(10, 36), dtype=float32_ref) 相同的图。

代码如下:

def tensorGraph5Fold(initState = 'NSW'):
    weights_obj, biases_obj = loadKernelBias5Fold(initState)

    weights = [tf.convert_to_tensor(w, dtype=tf.float32) for w in weights_obj]
    biases = [tf.convert_to_tensor(b, dtype=tf.float32) for b in biases_obj]

    #RNN designning
    tf.reset_default_graph()

    inputs = x_size #input vector size
    output = y_size #output vector size
    learning_rate = 0.01

    x = tf.placeholder(tf.float32, [inputs, None])
    y = tf.placeholder(tf.float32, [output, None])

    #L2 regulizer
    regularizer = tf.contrib.layers.l2_regularizer(scale=0.2)
    weights = {
        'hidden': tf.get_variable("w_hidden", initializer = weights[0], regularizer=regularizer),
        'output': tf.get_variable("w_output", initializer = weights[1], regularizer=regularizer)
    }

    biases = {
        'hidden': tf.get_variable("b_hidden", initializer = biases[0]),
        'output': tf.get_variable("b_output", initializer = biases[1])
    }

    hidden_layer = tf.add(tf.matmul(weights['hidden'], x), biases['hidden'])
    hidden_layer = tf.nn.relu(hidden_layer)

    output_layer = tf.matmul(weights['output'], hidden_layer) + biases['output']

    loss = tf.reduce_mean(tf.square(output_layer - y))    #define the cost function which evaluates the quality of our model
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)          #gradient descent method
    training_op = optimizer.minimize(loss)          #train the result of the application of the cost_function                                 

    #L2 regulizer
    reg_variables = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
    reg_term = tf.contrib.layers.apply_regularization(regularizer, reg_variables)
    loss += reg_term

    init = tf.global_variables_initializer()           #initialize all the variables
    epochs = 2000     #number of iterations or training cycles, includes both the FeedFoward and Backpropogation

    pred = {'NSW': [], 'QLD': [], 'SA': [], 'TAS': [], 'VIC': []}
    y_pred = {1: pred, 2: pred, 3: pred, 4: pred, 5: pred}

    print("Training the ANN...")
    for st in state.values():
        for fold in np.arange(1,6):
            print("State: ", st, end='\n')
            print("Fold : ", fold)

            with tf.Session() as sess:
                init.run()
                for ep in range(epochs):
                    sess.run(training_op, feed_dict={x: x_batches_train_fold[fold][st], y: y_batches_train_fold[fold][st]})

            print("\n")

错误显示我正在使用两个图表,但我不知道在哪里。

【问题讨论】:

  • 看看this answer能不能帮到你。 > 引用:“您可能在一个地方使用默认图表,而在您的训练块中使用不同的图表”。重置图表 (tf.reset_default_graph()) 后,再次调用上一张图表中的 weightsbiases
  • @LIXuhong 删除 tf.reset_default_graph() 工作。

标签: python tensorflow


【解决方案1】:

错误消息说明您的 x 占位符与 w_hidden 张量不在同一个图中 - 这意味着我们无法使用这两个张量完成操作(可能是在运行 tf.matmul(weights['hidden'], x) 时抛出)

出现这种情况的原因是您在创建weights 的引用之后使用了tf.reset_default_graph() ,但创建占位符x 之前。

为了解决这个问题,您可以在所有操作之前移动 tf.reset_default_graph() 调用(或完全删除它)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 2018-09-20
    • 2018-08-26
    相关资源
    最近更新 更多