重置默认图形不会删除变量 [英] Resetting default graph does not remove variables

查看:237
本文介绍了重置默认图形不会删除变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在Jupyter的交互式会话中快速更改图形以便测试不同结构的方法。最初我想简单地删除现有的变量,并用不同的初始化器重新创建它们。这似乎是不可能的[1]。

然后我发现[2],现在我试图简单地丢弃并重新创建默认图形。但这似乎并不奏效。这就是我所做的:

a。开始会话

 导入tensorflow为tf 
导入数学

sess = tf.InteractiveSession ()



b。在默认图中创建一个变量

$ p $ IMAGE_PIXELS = 32 * 32
HIDDEN1 = 200

BATCH_SIZE = 100
NUM_POINTS = 30

images_placeholder = tf.placeholder(tf.float32,shape =(BATCH_SIZE,IMAGE_PIXELS))
points_placeholder = tf.placeholder(tf.float32 ,shape =(BATCH_SIZE,NUM_POINTS))


#隐藏1
with tf.name_scope('hidden1'):
weights_init = tf.truncated_normal([IMAGE_PIXELS ,HIDDEN1],stddev = 1.0 / math.sqrt(float(IMAGE_PIXELS)))
weights = tf.Variable(weights_init,name ='weights')
biases_init = tf.zeros([HIDDEN1])
biasses = tf.Variable(biases_init,name ='biases')
hidden1 = tf.nn.relu(tf.matmul(images_placeholder,weights)+ biases)

c。使用变量

 #添加变量初始值设定项Op。 
init = tf.initialize_all_variables()

#运行Op来初始化变量。
sess.run(init)

d。重置图表

  tf.reset_default_graph()

e。使用tf.name_scope('hidden1'):
权重= tf.get_variable(name =')重新创建变量

  ('HIDDEN1])$ ​​b $ b biasses = tf.Variable (biasses_init,name ='biases')
hidden1 = tf.nn.relu(tf.matmul(images_placeholder,weights)+ biasses)

然而,我得到一个异常(见下文)。所以我的问题是:是否可以重新设置/删除图形并重新创建它?如果是这样,怎么样?

欣赏任何指针。

TIA,

参考




  1. 更改Tensorflow中变量的初始值设定项

  2. 从图表中移除节点或重置整个预设图表



例外



  ValueError Traceback(最近一次调用最后一次)
< ipython-input-5-e98a82c45473> in< module>()
5 biases_init = tf.zeros([HIDDEN1])$ ​​b $ b 6 biases = tf.Variable(biases_init,name ='biases')
----> ; 7 hidden1 = tf.nn.relu(tf.matmul(images_placeholder,weights)+偏好)
8

/home/hmf/my_py3/lib/python3.4/site-packages/ tensorflow / python / ops / math_ops.py in matmul(a,b,transpose_a,transpose_b,a_is_sparse,b_is_sparse,name)
1323与`a`类型相同的`张量'。
1324
- > 1325以ops.op_scope([a,b],名称,MatMul)作为名称:
1326 a = ops.convert_to_tensor(a,name =a)
1327 b = __enter __(self)$中的ops.convert_to_tensor(b,name =b)

/usr/lib/python3.4/contextlib.py b $ b 57 def __enter __(self):
58尝试:
---> 59 return next(self.gen)
60除StopIteration:
61 61 Run RunError( generator does not yield)from None

/home/hmf/my_py3/lib/python3.4/site-packages/tensorflow/python/framework/ops.py in op_scope(values,name ,default_name)
4014 ValueError:如果既不提供`name`也不提供`default_name`。
4015
- > 4016 g = _get_graph_from_inputs(values)
4017 n = default_name如果name是None其他名称
4018如果n是None:

/ home / hmf / my_py3 / lib / python3。 4 / site-packages / tensorflow / python / framework / ops.py in _get_graph_from_inputs(op_input_list,graph)
3812 graph = graph_element.graph
3813 elif original_graph_element is not None:
- > 3814 _assert_same_graph(original_graph_element,graph_element)
3815 elif graph_element.graph不是图形:
3816 raise ValueError(

/home/hmf/my_py3/lib/python3.4/site如果original_item.graph不是item.graph:
3758 raise ValueError(
- > 3759),则在_assert_same_graph(original_item,item)中包装/ tensorflow / python / framework / ops.py
3757 %s必须来自与%s相同的图表。%(item,original_item))
3760
3761

ValueError:张量(权重:0,形状=(1024,200),dtype = float32_ref)必须与Tensor(Placeholder:0,shape =(100,1024),dtype = float32).`


解决方案

当您重置默认图表时,您不会删除之前创建的张量。 $ c> tf.reset_default_graph(),创建一个新图并设置为默认值。



下面是一个例子来说明: p>

  x = tf.constant(1)
print tf.get_default_graph()== x.graph#prints True

tf.reset_default_graph()
print tf.get_default_graph()== x.graph#打印False






你得到的错误表明两个张量必须来自同一个图表,这意味着你仍然使用上一张图中的一些张量和当前默认图中的张量。 p>

简单的修复方法是再次创建两个占位符 images_placeholder points_placeholder


I am looking for a way to quickly change a graph within an interactive session in Jupyter in order to test different structures. Initially I wanted to simple delete existing variables and recreate them with a different initializer. This does not seem to be possible [1].

I then found [2] and am now attempting to simply discard and recreate the default graph. But this does not seem to work. This is what I do:

a. Start a session

import tensorflow as tf
import math

sess = tf.InteractiveSession()

b. Create a variable in the default graph

IMAGE_PIXELS = 32 * 32
HIDDEN1 = 200

BATCH_SIZE = 100
NUM_POINTS = 30

images_placeholder = tf.placeholder(tf.float32, shape=(BATCH_SIZE, IMAGE_PIXELS))
points_placeholder = tf.placeholder(tf.float32,   shape=(BATCH_SIZE, NUM_POINTS))


# Hidden 1
with tf.name_scope('hidden1'):
  weights_init = tf.truncated_normal([IMAGE_PIXELS, HIDDEN1], stddev=1.0 / math.sqrt(float(IMAGE_PIXELS)))
  weights      = tf.Variable(weights_init, name='weights')
  biases_init  = tf.zeros([HIDDEN1])
  biases       = tf.Variable(biases_init, name='biases')
  hidden1      = tf.nn.relu(tf.matmul(images_placeholder, weights) + biases)

c. Use the variable

# Add the variable initializer Op.
init = tf.initialize_all_variables()

# Run the Op to initialize the variables.
sess.run(init) 

d. Reset the graph

tf.reset_default_graph()

e. Recreate the variable

with tf.name_scope('hidden1'):
  weights      = tf.get_variable(name='weights', shape=[IMAGE_PIXELS, HIDDEN1], 
                                 initializer=tf.contrib.layers.xavier_initializer())
  biases_init  = tf.zeros([HIDDEN1])
  biases       = tf.Variable(biases_init, name='biases')
  hidden1      = tf.nn.relu(tf.matmul(images_placeholder, weights) + biases)

However, I get an exception (see below). So my question is: is it possible to reset/remove the graph and recreate it as before? If so, how?

Appreciate any pointers.

TIA,

Refs

  1. Change initializer of Variable in Tensorflow
  2. Remove nodes from graph or reset entire default graph

Exception

ValueError                                Traceback (most recent call last)
<ipython-input-5-e98a82c45473> in <module>()
      5   biases_init  = tf.zeros([HIDDEN1])
      6   biases       = tf.Variable(biases_init, name='biases')
----> 7   hidden1      = tf.nn.relu(tf.matmul(images_placeholder, weights) + biases)
  8 

/home/hmf/my_py3/lib/python3.4/site-packages/tensorflow/python/ops/math_ops.py in matmul(a, b, transpose_a, transpose_b, a_is_sparse, b_is_sparse, name)
   1323     A `Tensor` of the same type as `a`.
   1324   """
-> 1325   with ops.op_scope([a, b], name, "MatMul") as name:
   1326     a = ops.convert_to_tensor(a, name="a")
   1327     b = ops.convert_to_tensor(b, name="b")

/usr/lib/python3.4/contextlib.py in __enter__(self)
     57     def __enter__(self):
     58         try:
 ---> 59             return next(self.gen)
     60         except StopIteration:
     61             raise RuntimeError("generator didn't yield") from None

/home/hmf/my_py3/lib/python3.4/site-packages/tensorflow/python/framework/ops.py in op_scope(values, name, default_name)
   4014     ValueError: if neither `name` nor `default_name` is provided.
   4015   """
-> 4016   g = _get_graph_from_inputs(values)
   4017   n = default_name if name is None else name
   4018   if n is None:

/home/hmf/my_py3/lib/python3.4/site-packages/tensorflow/python/framework/ops.py in _get_graph_from_inputs(op_input_list, graph)
   3812         graph = graph_element.graph
   3813       elif original_graph_element is not None:
-> 3814         _assert_same_graph(original_graph_element, graph_element)
   3815       elif graph_element.graph is not graph:
   3816         raise ValueError(

/home/hmf/my_py3/lib/python3.4/site-packages/tensorflow/python/framework/ops.py in _assert_same_graph(original_item, item)
   3757   if original_item.graph is not item.graph:
   3758     raise ValueError(
-> 3759         "%s must be from the same graph as %s." % (item, original_item))
   3760 
   3761 

ValueError: Tensor("weights:0", shape=(1024, 200), dtype=float32_ref) must be from the same graph as Tensor("Placeholder:0", shape=(100, 1024), dtype=float32).`

解决方案

When you reset the default graph, you do not remove the previous Tensors created. When calling tf.reset_default_graph(), a new graph is created and set to default.

Here is an example to illustrate:

x = tf.constant(1)
print tf.get_default_graph() == x.graph  # prints True

tf.reset_default_graph()
print tf.get_default_graph() == x.graph  # prints False


The error you had indicates that two tensors must be from the same graph, which means you are still using some tensors from the previous graph AND from the current default graph.

The easy fix is to create again the two placeholders images_placeholder and points_placeholder

这篇关于重置默认图形不会删除变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆