I am trying to run the following tensorflow code and it's working fine the first time. If I try running it again, it keeps throwing an error saying

我正在尝试运行以下的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)

If I restart the console and then run it, once again it runs just fine.

如果我重新启动控制台,然后运行它,它又一次运行良好。

Given below is my implementation of the neural network.

下面给出的是我的神经网络的实现。

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

As the error suggests I tried adding reuse=True as a parameter in with tf.variable_scope(): but that again is not working.

由于错误提示,我尝试在使用tf.variable_scope()中添加重用=True作为参数:但这又不起作用。

I am running this inside a conda environment. I am using Python 3.5 and CUDA 8(But it shouldn't matter because this is not configured to run in the GPU) in windows 10.

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

1 个解决方案

#1


3

This is a matter of how TF works. One needs to understand that TF has a "hidden" state - a graph being built. Most of the tf functions create ops in this graph (like every tf.Variable call, every arithmetic operation and so on). On the other hand actual "execution" happens in the tf.Session(). Consequently your code will usually look like this:

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

build_graph()

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

since all actual variables, results etc. leave in session only, if you want to "run it twice" you would do

由于所有实际的变量、结果等只在会话中结束,如果您想“运行两次”,您就会这样做。

build_graph()

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

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

Notice that I am building graph once. Graph is an abstract representation of how things look like, it does not hold any state of computations. When you try to do

注意,我在构建图形。图是事物看起来的抽象表示,它不包含任何计算状态。当你试着去做的时候。

build_graph()

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

build_graph()

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

you might get errors during second build_graph() due to trying to create variables with the same names (what happens in your case), graph being finalised etc. If you really need to run things this way you simply have to reset graph in between

您可能会在第二次build_graph()中出现错误,因为尝试创建具有相同名称的变量(在您的例子中发生了什么),图被终结等等。如果您真的需要这样运行的话,您只需在中间重新设置图形。

build_graph()

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

tf.reset_default_graph()

build_graph()

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

will work fine.

将正常工作。

更多相关文章

  1. Python基础--图形用户界面GUI
  2. Python:Sympy定义与包含变量的边界的积分
  3. “全局变量是坏的”是什么意思?
  4. 环境变量的安装以及python cahrm的安装以及常用快捷键的使用
  5. tensorflow 变量定义路径//问题
  6. 变量和数据类型
  7. python的全局变量与局部变量实验
  8. 在混合的Bash-Python代码片段中,变量的双引号和单引号
  9. Tensorflow:恢复图形和模型,然后在单个图像上运行评估

随机推荐

  1. DataTables警告:table id = DataTables_Ta
  2. 在html表的第一行后追加行
  3. Jquery隐藏()除一个类外所有具有特定类的
  4. 从一个页面上的AJAX帖子获得NTLM挑战
  5. 如何设置请求标头字符串[重复]
  6. jquery IE9没有错,IE8出错了
  7. php中的json对象未被读取
  8. Internet Explorer导致无效的真实性令牌
  9. Android+Jquery Mobile学习系列(6)-个人
  10. 将css添加到jquery数据表中的特定单元格