简体   繁体   English

如何在 TensorFlow 2 中重置初始化

[英]How to reset initialization in TensorFlow 2

If I try to change parallelism in TensorFlow 2 after initializing a tf.Variable ,如果我在初始化tf.Variable后尝试更改 TensorFlow 2 中的tf.Variable

import tensorflow as tf
_ = tf.Variable([1])
tf.config.threading.set_inter_op_parallelism_threads(1)

I get an error我收到一个错误

RuntimeError: Inter op parallelism cannot be modified after initialization.运行时错误:初始化后无法修改操作间并行性。

I understand why that could be, but it (and possibly other factors) are causing my tests to interfere with each other.我明白为什么会这样,但它(可能还有其他因素)导致我的测试相互干扰。 For example例如

def test_model():  # this test
   v = tf.Variable([1])
   ...

def test_threading():  # is breaking this test
   tf.config.threading.set_inter_op_parallelism_threads(1)
   ...

How do I reset the TensorFlow state so that I can set the threading?如何重置 TensorFlow 状态以便设置线程?

This is achievable in a "hacky" way.这可以通过“hacky”方式实现。 But I'd recommend doing this the right way (ie by setting up config at the beginning).但我建议以正确的方式执行此操作(即在开始时设置配置)。

import tensorflow as tf
from tensorflow.python.eager import context

_ = tf.Variable([1])

context._context = None
context._create_context()

tf.config.threading.set_inter_op_parallelism_threads(1)

Edit : What is meant by setting up config at the beginning,编辑:一开始就设置配置是什么意思,

import tensorflow as tf
from tensorflow.python.eager import context

tf.config.threading.set_inter_op_parallelism_threads(1)
_ = tf.Variable([1])

But there could be circumstances where you cannot always do this.但在某些情况下,您不能总是这样做。 Merely pointing out the conventional way of setting up config in tf .仅仅指出在tf中设置配置的传统方法。 So if your circumstances don't allow you to fix tf.config at the beginning you have to reset your tf.eager.context as shown in the solution above.因此,如果您的情况不允许您在开始时修复tf.config ,您必须按照上面的解决方案中所示重置您的tf.eager.context

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM