美文网首页
tensorflow基础 2020-11-09

tensorflow基础 2020-11-09

作者: 9_SooHyun | 来源:发表于2020-11-09 16:27 被阅读0次

1.cpu vs gpu

cpu: 几个科学家
gpu: 成千上万个初中生

  • GPU的工作大部分是大量、重复、基础的计算,每个具体的计算单元都是非常基础的,初中生完全可以搞定。适用于计算密集型和并行(并发)任务
  • CPU负责的工作多数是复杂的计算,带有很多的逻辑控制和变化,就像科学家,高数线代离散概率论统统会

2.tensorflow

2.1 概要

tensorflow基于图结构进行计算,其中的图称为【计算图】

tensor张量之意,包括常量constant、变量variable、和占位符placeholder 3种对象。其中,变量对应计算图的边权,占位符用于将数据提供给计算图,即对应训练样本
flow流动之意,指张量在计算图中流动

使用tensorflow分为2步,首先要创建计算图,然后执行计算图

下文涉及的代码均基于 tensorflow-cpu 2.3.1

2.2 安装

pip安装tensorflow
tensorflow分为cpu版和gpu版,分别利用cpu和gpu进行图的计算,安装时根据自己的硬件环境选择

# 先搞个虚拟环境
python -m venv venvname

# pip安装【当只有cpu时,或者用于简单学习的,推荐2】
1.pip install tensorflow==version # 不指定version则安装最新版本。2.0×后默认是CPU和GPU版本在一起,1.×只表示tensorflow-CPU版本。如果你没有GPU而安装2.0以上版本,在导入包和使用过程中会出现很多warning
2.pip install tensorflow-cpu # 【推荐强制安装最新的cpu版本】

# 20201108-通过pip install tensorflow-cpu安装tensorflow-cpu2.3.1至虚拟环境tensorflow_cpu_2.3.1

2.3 测试安装结果和是否支持gpu

# 测试代码
import tensorflow as tf 
version = tf.__version__
gpu_ok = tf.config.list_physical_devices("GPU")
print("tf version:", version, "\nuse GPU", gpu_ok) # 打印tf version,以及GPU是否可用

# 本机测试结果
(tensorflow_cpu_2.3.1) D:\virenv_python\tensorflow_cpu_2.3.1\Scripts>python
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> version = tf.__version__
>>> gpu_ok = tf.config.list_physical_devices("GPU")
>>> print("tf version:", version, "\nuse GPU", gpu_ok) # 打印tf version,以及GPU是否可用
tf version: 2.3.1
use GPU []
>>>

2.4 tensorflow-cpu2.3.1的使用demo

——【创建图(create tensor object and operation object)+在session中执行图】

import tensorflow as tf
tf.compat.v1.disable_eager_execution() # 保证sess.run()能够正常运行,避免报错The Session graph is empty. Add operations to the graph before calling run()
hello = tf.constant('hello,tensorflow')  # 创建图
hi = tf.constant('hi')  # 创建图
total = tf.add(hello, hi)  # 创建图
sess = tf.compat.v1.Session() # 版本2.0的Session函数
print(sess.run(total)) # 在session中执行图
sess.close()

使用交互式的session: InteractiveSession()

当使用jupyter或者python shell做调试的时候,使用tf.compat.v1.InteractiveSession() 将比 tf.compat.v1.Session() 更方便,可以调用eval()直接运行张量对象而不用显式调用会话
demo如下:

>>> import tensorflow as tf
>>> sess = tf.compat.v1.InteractiveSession()
>>> hello = tf.constant('hello,tensorflow')
>>> print(hello.eval())
b'hello,tensorflow'

ps: 关于屏蔽tensorflow的提示消息

在使用tensorflow的过程中,可能会碰到一堆提示信息,例如

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA

大量这种信息打印出来就很烦,可以通过设置消息级别的方式进行屏蔽:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

说明:
os.environ["TF_CPP_MIN_LOG_LEVEL"]='1' # 这是默认的显示等级,显示所有信息  
os.environ["TF_CPP_MIN_LOG_LEVEL"]='2' # 只显示 warning 和 Error   
os.environ["TF_CPP_MIN_LOG_LEVEL"]='3' # 只显示 Error 

或者到GitHub上找支持avx的costomed version, such as visit https://github.com/fo40225/tensorflow-windows-wheel

2.5 tensorflow的程序脚本配置命令行参数

We usually use tf.app.flags to declare the command-line parameters for TensorFlow scripts.

tensorflow 创建命令行参数:

import tensorflow as tf

flags = tf.app.flags
FLAGS = flags.FLAGS
# 1.定义命令行参数
flags.DEFINE_string(flag_name, default_value, docstring)
# 2.指定给定的参数非None
flags.mark_flag_as_required(flag_name)
# FLAGS用于获取相关参数的值
print(FLAGS.flag_name)

注意:
If we try to print the values of these parameters, it prints the default values at the first time even though we have passed the values. 首次打印参数值会得到参数默认值而不是我们赋予的值
And if we actually "get" the values equal or more than one times, we can print the parameter values as expected. 直到我们显式调用参数后,才会得到我们期望的值
参考issue https://github.com/tensorflow/tensorflow/issues/20680
以下是测试demo:

## this file is test_flag.py

# tf1.x
# import tensorflow as tf

# tf2.3.1
import tensorflow.compat.v1 as tf

flags = tf.app.flags
FLAGS = flags.FLAGS

flags.DEFINE_integer("image_width", 224, "Width of the image")
flags.DEFINE_integer("image_height", 224, "Height of the image")
flags.DEFINE_integer("channels", 3, "Channel of the image")

parameter_value_map = {}
for key in FLAGS.__flags.keys():
  parameter_value_map[key] = FLAGS.__flags[key].value
print("Parameters: {}".format(parameter_value_map))
# Parameters: {'channels': 3, 'image_height': 224, 'image_width': 224}

# FLAGS的显式解析
FLAGS.channels 
for key in FLAGS.__flags.keys():
    parameter_value_map[key] = FLAGS.__flags[key].value
print("Parameters: {}".format(parameter_value_map))
# Parameters: {'channels': 1, 'image_height': 1, 'image_width': 1}

# run command 'python test_flag.py --image_width=1 --image_height=1 --channels=1' in command line

相关文章

网友评论

      本文标题:tensorflow基础 2020-11-09

      本文链接:https://www.haomeiwen.com/subject/ufalbktx.html