解决Jupyter Notebook中TensorFlow设备信息打印问题
本文介绍在Jupyter Notebook环境中使用TensorFlow时,如何正确打印设备分配信息。通过设置log_device_placement=True及output_partition_graphs=True,可获取详细的设备日志。同时解决了因中文编码导致的控制台输出异常问题,提供完整的代码示例与配置方法。
TensorFlow设备信息打印配置
在Jupyter Notebook环境中直接配置log_device_placement=True,往往无法成功打印出设备分配信息。
# Creates a graph.
with tf.device('/device:CPU:0'):
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True,allow_soft_placement=True))
# Runs the op.
print(sess.run(c))
为了获取完整的设备信息,必须额外启用output_partition_graphs参数进行输出。
启用output_partition_graphs获取详细日志
# Creates a graph.
with tf.device('/device:GPU:0'):
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True,allow_soft_placement=True))
# Runs the op.
options = tf.RunOptions(output_partition_graphs=True)
metadata = tf.RunMetadata()
c_val = sess.run(c, options=options, run_metadata=metadata)
print metadata.partition_graphs
解决Jupyter控制台打印与编码问题
补充说明:Jupyter Notebook默认环境下,控制台打印功能可能受限。
由于数据包含中文字符,需要在Jupyter启动前进行特定的编码设置。
reload(sys) sys.setdefaultencoding("utf-8")
若直接使用print语句无法输入内容,原因是reload操作将stdout重定向为IPython对象。因此,需要临时保存原始的stdout对象以恢复功能。
可以参考以下代码实现上述修复。
恢复stdout对象的代码示例
import sys
stdo = sys.stdout
reload(sys)
sys.setdefaultencoding('utf-8')
sys.stdout= stdo
以上关于在Jupyter Notebook中打印TensorFlow设备信息的实例分享完毕,希望能为读者提供参考,并欢迎继续支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













