TensorFlow安装、开发环境设定、使用入门

安装Anaconda

本文主要介绍使用Anaconda安装TensorFlow, 操作系统为Win10。

首先从Anaconda官网下载并安装Anaconada:

https://www.anaconda.com/download/

如果访问anaconda网站有问题的话,国内可以使用清华的镜像下载:

https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/

选择对应操作系统的anaconda,并安装。anaconda官方下载更新工具包的速度很慢,所以继续添加清华大学 提供的Anaconda仓库镜像,在终端或cmd中输入如下命令进行添加:

conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --set show_channel_urls yes
conda install numpy   #测试是否添加成功

安装TensorFlow

打开“开始目录”,找到Anaconda/Anaconda prompt,以管理员权限运行。在终端或cmd中输入以下命令搜索当前可用的tensorflow版本。

anaconda search -t conda tensorflow

选择一个较新的CPU或GPU版本,如aaronzs/tensorflow,输入如下命令查询安装命令

anaconda show aaronzs/tensorflow

使用上述命令的执行结果的最后一行的提示命令进行安装

conda install --channel https://conda.anaconda.org/aaronzs tensorflow

conda会自动检测安装此版本的Tensorflow所依赖的库,如果你的Anaconda缺少这些依赖库,会提示你安装。因为我之前已经安装过了,所以这里只提示我安装Tensorflow。输入y并回车之后等待安装结束即可。

进入python,输入

import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))

如果可以正常执行,表示安装没有问题。

集成开发环境设定

我们选用pycharm作为tensorflow python的集成开发工具,可以根据需要选择相应的版本,PyCharm Professional Edition和PyCharm Community Edition。下载地址为:

https://www.jetbrains.com/pycharm/

安装好后,在新建项目中选择选择相应的python 解释器地址(可以选择anaconda中的python开发环境):

C:\ProgramData\Anaconda3\python.exe

然后在开发环境中,新建一个 example.py 文件,测试如下代码是否可以正常运行:

import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))

线性回归用例:

import tensorflow as tf

# Model parameters
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W*x + b
y = tf.placeholder(tf.float32)

# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

# training data
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(1000):
    sess.run(train, {x: x_train, y: y_train})

# evaluate training accuracy
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))

TensorFlow程序设计简介

当安装完TensorFlow和设定好TensorFlow开发环境后,本章主要介绍TensorFlow程序中的基本概念。

写TensorFlow程序首先需要调入TensorFlow相关的Python库,如下所示:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

#python numpy库
import numpy as
np
#TensorFlow库
import
tensorflow as tf

TensorFlow中处理的核心数据定义为Tensor,是一个多维矩阵。矩阵的维度称之为rank,相应地矩阵每个维度对应的元素个数称之为shape。如下所示:

3 #rank=0,表示常量,对应的shape为[]
[1., 2., 3.] # rank=1,表示向量,对应的shape为 [3]
[[1., 2., 3.],
[4., 5., 6.]] # rank=2; 表示二维矩阵,对应的shape为 [2, 3]
[[[1., 2., 3.]],
[[7., 8., 9.]]] # rank=3;表示三维矩阵,对应的shape为 [2, 1, 3]

TensorFlow的核心程序主要由两部分组成:构建计算图,称之为Graph;运行计算图,称之为Session。和图计算的思想一样,TensorFlow的计算图同样由节点和边组成。TensorFlow中的节点称之为Operation,主要用于计算操作,操作的输入和输出是Tensor。TensorFlow图中的边表示Tensor,表示在计算图中流转的数据。下面的示例代码构建了一个简单的TensorFlow计算图:

a = tf.constant(3.0, dtype=tf.float32)
b = tf.constant(4.0) # also tf.float32 implicitly
total = a + b
print(a)
print(b)
print(total)

TensorFlow Tensor

TensorFlow中的Tensor可以是一个标量,向量,二维矩阵或多维矩阵,通常可以认为Tensor是一个多维矩阵。程序中用tf.Tensor来表示TensorFlow的Tensor对象,该对象主要包含以下几个属性:

1. 数据类型,例如float32,int32,string。

2. 矩阵的维度大小信息,例如[32,100]表示32行,100列的二维矩阵。

在TensorFlow程序中,可以通过如下操作来生成Tensor:

1. tf.Variable 构建变量

tf.Variable([100],name="var1",dtype=tf.float32)

2. tf.constant 构建常量

cons1=tf.constant(-1.0, name="cons1", shape=[2, 3])

3. tf.placeholder 构建占位符

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, shape=(1024, 1024))
y = tf.matmul(x, x)
rand_array = np.random.rand(1024, 1024)
sess=tf.Session()
print(sess.run(y, feed_dict={x: rand_array}))

TensorFlow变量

TensorFlow模型中一般使用tf.get_variable来定义变量,与tf.Variable的主要区别在于tf.get_variable定义的变量可以被重复使用,从而简化TensorFlow模型的定义。下面主要讲解TensorFlow变量的常用用例:

创建变量:

my_variable = tf.get_variable("my_variable", [1, 2, 3])
my_int_variable = tf.get_variable("my_int_variable", [1, 2, 3], dtype=tf.int32,
initializer=tf.zeros_initializer)
other_variable = tf.get_variable("other_variable", dtype=tf.int32,
initializer=tf.constant([23, 42]))

其中[1, 2, 3]表示变量的shape,initializer表示变量的初始方法。my_variable的默认数据类型为float32,默认的变量初始化方法为tf.glorot_uniform_initializer的均匀分布。

TensorFlow Graph和Sesssion

在TensorFlow中tf.Graph主要包含两部内容:

1. 图结构:包含节点和边,节点主要指的是TensorFlow中的操作,边主要指的是Tensor数据。

2. 图中的集合:TensorFlow中定义了一系列的集合,用来存储图中的元数据信息,如全局变量,训练变量,局部变量等。集合的key值定义在tf.GraphKeys中。

在图的定义中,可以指定操作的命名空间,如下所示:

c_0 = tf.constant(0, name="c") # => 操作命名为 "c"

# 注意c名字已经被使用
c_1 = tf.constant(2, name="c") # => 操作命名为 "c_1"

# 指定操作的命名空间
with tf.name_scope("outer"):
  c_2 = tf.constant(2, name="c") #=> 操作命名为"outer/c"

# 指定操作的命名空间
with tf.name_scope("inner"):
  c_3 = tf.constant(3, name="c") #=> 操作命名为"outer/inner/c"

# 相同的命名空间,存在同名的操作
c_4 = tf.constant(4, name="c") #=> 操作被命名为"outer/c_1"

# 相同的命名空间,存在同名的操作
with tf.name_scope("inner"):
  c_5 = tf.constant(5,name="c") # => 操作命名为"outer/inner_1/c

TensorFlow 模型的保存和回复

保存模型:

import tensorflow as tf

# 创建模型变量.
v1 = tf.get_variable("v1", shape=[3], initializer = tf.zeros_initializer)
v2 = tf.get_variable("v2", shape=[5], initializer = tf.zeros_initializer)

inc_v1 = v1.assign(v1+1)
dec_v2 = v2.assign(v2-1)

#模型全局变量初始操作.
init_op = tf.global_variables_initializer()

#用于保存模型变量的操作.
saver = tf.train.Saver()

# 保存模型到磁盘.
with tf.Session() as sess:
  sess.run(init_op)
  #执行模型中的操作.
  inc_v1.op.run()
  dec_v2.op.run()
  # 保存模型变量到磁盘.
  save_path = saver.save(sess, "C:\\tmp\\ckpt\\model.ckpt")
  print("Model saved in path: %s" % save_path)

注意:并没有物理文件名叫C:\\tmp\\ckpt\\model.ckpt,model.ckpt是checkppoint文件的前缀。

“.meta”文件:图形结构元数据信息。

“.data”文件:checkpoint数据文件。

“.index”文件:checkpoint数据索引文件。

“checkpoint”文件:最近检查点的文件列表信息。内容如下所示:

model_checkpoint_path: "C:\\tmp\\ckpt\\model.ckpt"
all_model_checkpoint_paths: "C:\\tmp\\ckpt\\model.ckpt"

恢复模型变量:

import tensorflow as tf

tf.reset_default_graph()

# 创建模型变量
v1 = tf.get_variable("v1", shape=[3])
v2 = tf.get_variable("v2", shape=[5])

# 用于回复模型变量
saver = tf.train.Saver()

with tf.Session() as sess:
  # 从磁盘回复模型变量
  saver.restore(sess, "C:\\tmp\\ckpt\\model.ckpt")
  print("Model restored.")
  # 打印变量值
  print("v1 : %s" % v1.eval())
  print("v2 : %s" % v2.eval())

查看模型变量

from tensorflow.python.tools import inspect_checkpoint as chkp

# 打印checkpoint文件中所有变量
chkp.print_tensors_in_checkpoint_file("C:\\tmp\\ckpt\\model.ckpt", tensor_name='', all_tensors=True, all_tensor_names=True)

# 打印checkpoint文件中的变量v1
chkp.print_tensors_in_checkpoint_file("C:\\tmp\\ckpt\\model.ckpt", tensor_name='v1', all_tensors=False, all_tensor_names=False)

# 打印checkpoint文件中的变量v2
chkp.print_tensors_in_checkpoint_file("C:\\tmp\\ckpt\\model.ckpt", tensor_name='v2', all_tensors=False, all_tensor_names=False)

    原文作者:武维
    原文地址: https://zhuanlan.zhihu.com/p/33623071
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞