Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 再次运行tensorflow时出错_Python_Tensorflow_Deep Learning_Artificial Intelligence - Fatal编程技术网

Python 再次运行tensorflow时出错

Python 再次运行tensorflow时出错,python,tensorflow,deep-learning,artificial-intelligence,Python,Tensorflow,Deep Learning,Artificial Intelligence,我正在尝试运行下面的tensorflow代码,第一次它运行得很好。如果我再次尝试运行它,它会不断抛出一个错误 ValueError: Variable layer1/weights1 already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at: File "C:\Users\owner\Anaconda3\envs\DeepLearning_NoGPU\l

我正在尝试运行下面的tensorflow代码,第一次它运行得很好。如果我再次尝试运行它,它会不断抛出一个错误

ValueError: Variable layer1/weights1 already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:

      File "C:\Users\owner\Anaconda3\envs\DeepLearning_NoGPU\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
        self._traceback = _extract_stack()
      File "C:\Users\owner\Anaconda3\envs\DeepLearning_NoGPU\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
        original_op=self._default_original_op, op_def=op_def)
      File "C:\Users\owner\Anaconda3\envs\DeepLearning_NoGPU\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
        op_def=op_def)
如果我重新启动控制台,然后运行它,它会再次正常运行

下面是我对神经网络的实现

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
import tensorflow as tf

learning_rate = 0.001
training_epochs = 100

n_input = 9
n_output = 1

n_layer1_node = 100
n_layer2_node = 100

X_train = np.random.rand(100, 9)
y_train = np.random.rand(100, 1)

with tf.variable_scope('input'):
    X = tf.placeholder(tf.float32, shape=(None, n_input))

with tf.variable_scope('output'):
    y = tf.placeholder(tf.float32, shape=(None, 1))

#layer 1
with tf.variable_scope('layer1'):
    weight_matrix1 = {'weights': tf.get_variable(name='weights1', 
                                                shape=[n_input, n_layer1_node], 
                                                initializer=tf.contrib.layers.xavier_initializer()),
                      'biases': tf.get_variable(name='biases1',
                                shape=[n_layer1_node],
                                initializer=tf.zeros_initializer())}
    layer1_output = tf.nn.relu(tf.add(tf.matmul(X, weight_matrix1['weights']), weight_matrix1['biases']))

#Layer 2
with tf.variable_scope('layer2'):
    weight_matrix2 = {'weights': tf.get_variable(name='weights2', 
                                                shape=[n_layer1_node, n_layer2_node], 
                                                initializer=tf.contrib.layers.xavier_initializer()),
                      'biases': tf.get_variable(name='biases2',
                                shape=[n_layer2_node],
                                initializer=tf.zeros_initializer())}
    layer2_output = tf.nn.relu(tf.add(tf.matmul(layer1_output, weight_matrix2['weights']), weight_matrix2['biases']))

#Output layer
with tf.variable_scope('layer3'):
    weight_matrix3 = {'weights': tf.get_variable(name='weights3', 
                                                shape=[n_layer2_node, n_output], 
                                                initializer=tf.contrib.layers.xavier_initializer()),
                      'biases': tf.get_variable(name='biases3',
                                shape=[n_output],
                                initializer=tf.zeros_initializer())}
    prediction = tf.nn.relu(tf.add(tf.matmul(layer2_output, weight_matrix3['weights']), weight_matrix3['biases']))

cost = tf.reduce_mean(tf.squared_difference(prediction, y))
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)

with tf.Session() as session:

    session.run(tf.global_variables_initializer())


    for epoch in range(training_epochs):

        session.run(optimizer, feed_dict={X: X_train, y: y_train})
        train_cost = session.run(cost, feed_dict={X: X_train, y:y_train})

        print(epoch, " epoch(s) done")

    print("training complete")
正如错误所示,我尝试将
reuse=True
作为参数添加到带有tf.variable_scope():的
中,但同样不起作用


我在conda环境中运行这个。我在windows 10中使用Python 3.5和CUDA 8(但这不重要,因为它没有配置为在GPU中运行)。

这是TF如何工作的问题。我们需要了解TF有一个“隐藏”状态——一个正在构建的图形。大多数tf函数在这个图中创建操作(比如每个tf.变量调用、每个算术运算等等)。另一方面,实际的“执行”发生在tf.Session()中。因此,您的代码通常如下所示:

build_graph()

with tf.Session() as sess:
  process_something()
由于所有实际变量、结果等只在会话中离开,如果您想“运行两次”,您可以这样做

build_graph()

with tf.Session() as sess:
  process_something()

with tf.Session() as sess:
  process_something()
请注意,我正在构建一次图形。图形是事物外观的抽象表示,它不包含任何计算状态。当你试着去做

build_graph()

with tf.Session() as sess:
  process_something()

build_graph()

with tf.Session() as sess:
  process_something()
在第二次构建_graph()期间,您可能会因为尝试创建同名变量(在您的情况下会发生什么)、图形正在最终确定等而出错。如果确实需要以这种方式运行,您只需在其间重置图形即可

build_graph()

with tf.Session() as sess:
  process_something()

tf.reset_default_graph()

build_graph()

with tf.Session() as sess:
  process_something()

这是TF如何工作的问题。我们需要了解TF有一个“隐藏”状态——一个正在构建的图形。大多数tf函数在这个图中创建操作(比如每个tf.变量调用、每个算术运算等等)。另一方面,实际的“执行”发生在tf.Session()中。因此,您的代码通常如下所示:

build_graph()

with tf.Session() as sess:
  process_something()
由于所有实际变量、结果等只在会话中离开,如果您想“运行两次”,您可以这样做

build_graph()

with tf.Session() as sess:
  process_something()

with tf.Session() as sess:
  process_something()
请注意,我正在构建一次图形。图形是事物外观的抽象表示,它不包含任何计算状态。当你试着去做

build_graph()

with tf.Session() as sess:
  process_something()

build_graph()

with tf.Session() as sess:
  process_something()
在第二次构建_graph()期间,您可能会因为尝试创建同名变量(在您的情况下会发生什么)、图形正在最终确定等而出错。如果确实需要以这种方式运行,您只需在其间重置图形即可

build_graph()

with tf.Session() as sess:
  process_something()

tf.reset_default_graph()

build_graph()

with tf.Session() as sess:
  process_something()

很好。

非常感谢您!我有一个我描述过的类似问题。阅读您的答案后,我可以通过在main.py中添加
tf.reset\u default\u graph()
来解决这个问题。非常感谢!我有一个我描述过的类似问题。阅读您的答案后,我可以通过在main.py中添加
tf.reset\u default\u graph()
来解决这个问题。