简介
关于TensorFlow的安装,请参考win10便捷安装TensorFlow2——使用Anaconda。
对于不熟悉DNN的同学,直接上复杂的概念不容易上手,我觉得还是先来点简单的。
本文就是使用TensorFlow2实现在屏幕上输出“Hello World”字串的功能。
即使是这么一个简单的程序,中间还是有一些小问题,一并解决。
代码
这是第一版代码,使用的TensorFlow v1.0版本代码,网上可以找到许多这样的代码:
'''
HelloWorld example using TensorFlow library.
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
from __future__ import print_function
import tensorflow as tf
# Simple hello world using TensorFlow
# Create a Constant op
# The op is added as a node to the default graph.
#
# The value returned by the constructor represents the output
# of the Constant op.
hello = tf.constant('Hello, TensorFlow!')
# Start tf session
sess = tf.Session()
# Run the op
print(sess.run(hello))
很简洁的代码,遗憾的是,它并不能在TensorFlow2.0上正常运行。
module ‘tensorflow’ has no attribute ‘Session’
如图:
是的,tf2没有这个属性。
所以需要加入以下代码,以与tf1兼容:
sess = tf.compat.v1.Session()
为了避免在每次使用类似的属性时都加上上述语句,可以在开始引入tf时就直接以兼容方式:
import tensorflow.compat.v1 as tf
后面就可以直接tf,ok了。
当然,还有第二个问题。
runtimeerror: the session graph is empty. add operations to the graph before calling run()
如图:
在tf2上需要在文件的开头加入以下语句可以解决问题:
tf.compat.v1.disable_eager_execution()
但另一方面,tf2支持eager 执行,就不用地创建会话并在其中执行代码。是的,直接print就行:
hello = tf.constant('Hello, TensorFlow!')
# Run
print(hello)
输出如下:
tf.Tensor(b'Hello, TensorFlow!', shape=(), dtype=string)
Warning/Info信息输出干扰查看
我是在win10是运行的,没有GPU,所以每次导入tf2的时候就会报一堆警告或者信息,如图:
这些信息与运行无关,可以屏蔽,这里使用python的os环境变量设置:
# set log level before import tf
import os
# 0 = all messages are logged (default behavior)
# 1 = INFO messages are not printed
# 2 = INFO and WARNING messages are not printed
# 3 = INFO, WARNING, and ERROR messages are not printed
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
ok,这时只有Error/Fatal信息才会输出。
特别注意,这个设置语句要在import tensorflow前,否则无效。
最终代码
新建一个py文件,录入以下内容:
使用tf1改造版本:
# -*- coding: utf-8 -*-
# set log level before import tf
import os
# 0 = all messages are logged (default behavior)
# 1 = INFO messages are not printed
# 2 = INFO and WARNING messages are not printed
# 3 = INFO, WARNING, and ERROR messages are not printed
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
#os.environ["CUDA_VISIBLE_DEVICES"] = "0"
# 这里安装的是v2版本的tensorflow
# 导入与v1版本兼容的tf
import tensorflow.compat.v1 as tf
print(tf.__version__)
# this does not work for v2.0
# tf.logging.set_verbosity(tf.logging.ERROR)
# tf.get_logger().setLevel('ERROR')
# 此函数只能在创建任何图、运算或张量之前调用
# 它可以用于从TensorFlow 1.x到2.x的复杂迁移项目的程序开头
tf.disable_eager_execution()
# 图形定义部分,创建计算图,此处只有一个节点,tensor常量字符串
message = tf.constant('Hello World!')
# 通过会话执行计算图
# 使用 with 关键字创建了会话,最后在会话中执行以上计算图
with tf.Session() as sess:
print(sess.run(message).decode())
使用tf2版本:
# -*- coding: utf-8 -*-
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
print(tf.__version__)
# 使用session
with tf.compat.v1.Session() as sess:
msg = tf.constant('Hello World!')
print(sess.run(msg).decode())
结果如图所示:
小结
tf2在tf1的基础上有了较大的升级改造,总体上而言,API接口更简洁,使用更简单。
相信从tf1转移到tf2也不是很难的事情。
建议初学者直接从tf2开始。
参考资料
helloworld.py
TF_CPP_MIN_LOG_LEVEL does not work with TF2.0 dev20190820
How to fix ‘RuntimeError: The Session graph is empty. Add operations to the graph before calling run()
RuntimeError: The Session graph is empty. Add operations to the graph before calling run()