RuntimeError: Physical devices cannot be modified after being initialized,tensorflow2.0(已解决)

tensorflow进行GPU分配时出现此错误。
原因:在分配GPU前就实例化了模型。
解决办法:在实例化模型前分配GPU。

如果是在导包完后,出现此错误,基本上是导入得包内实例化了模型

1.如图,报错

2.正常训练

3.进入函数一看,默认实例化了模型。
RuntimeError: Physical devices cannot be modified after being initialized,tensorflow2.0(已解决)_第1张图片

4.最简单的办法:
把import tensorflow as tf 放在代码第一行,后面调用GPU分配。正常训练。

import tensorflow as tf
physical_devices = tf.config.experimental.list_physical_devices("GPU")
if len(physical_devices) > 0:
	tf.config.experimental.set_memory_growth(physical_devices[0],True)	
	logical_devices = tf.config.list_logical_devices("GPU")

纯手敲,有错误的话看下面的图片,还有这样写也可以

import tensorflow as tf
physical_devices = tf.config.list_physical_devices("GPU")
tf.config.experimental.set_memory_growth(physical_devices[0],True)
logical_devices = tf.config.list_logical_devices("GPU")

你可能感兴趣的:(tensorflow,深度学习,神经网络)