分享

TensorFlow教程:1基本概念


问题导读

1.机器学习和深度学习的基础包含哪些内容?
2.TensorFlow包含哪些内容?
3.如何使用TensorBoard?







在本章中,我们将介绍以下主题:
  • 机器学习和深度学习的基础
  • TensorFlow - 一般概述
  • Python的基本知识
  • 安装TensorFlow
  • 第一次工作会议
  • 数据流图
  • TensorFlow编程模型
  • 如何使用TensorBoard


Machine learning and deep learning basics


机器学习是人工智能的一个分支,更具体地说是计算机科学的一个分支,它涉及研究可以从数据中学习的系统和算法,并从中综合新的知识。
The word learn intuitively suggests that a system based on machine learning, may, on the basis of the observation of previously processed data, improve its knowledge in order to achieve better results in the future, or provide output closer to the desired output for that particular system.
The ability of a program or a system based on machine learning to improve its performance in a particular task, thanks to past experience, is strongly linked to its ability to recognize patterns in the data. This theme, called pattern recognition, is therefore of vital importance and of increasing interest in the context of artificial intelligence; it is the basis of all machine learning techniques.
机器学习系统的培训可以通过不同的方式进行:
  • 监督学习
  • 无监督学习



Supervised learning


监督式学习是机器学习最常见的形式。 With supervised learning, a set of examples, the training set, is submitted as input to the system during the training phase, where each example is labeled with the respective desired output value. 例如,让我们考虑一个classification problem,系统必须在已知的N个不同类别之一中归入一些实验观察值。 In this problem, the training set is presented as a sequence of pairs of the type {(X1, Y1), ....., (Xn, Yn)} where Xi are the input vectors (feature vectors) and Yi represents the desired class for the corresponding input vector. Most supervised learning algorithms share one characteristic: the training is performed by the minimization of a particular loss function (cost function), which represents the output error with respect to the desired output system.
The cost function most used for this type of training calculates the standard deviation between the desired output and the one supplied by the system. 训练结束后, 准确性 的模型是从训练集,所谓的一组脱节的例子来衡量的 验证集。

1.jpeg
监督学习工作流程



In this phase the model's generalization capability is then verified: we will test if the output is correct for an unused input during the training phase.

无监督学习


在无监督学习中,系统提供的训练样例are not labeled和相关的所有物类别。 The system, therefore, develops and organizes the data, looking for common characteristics among them, and changing them based on their internal knowledge.
无监督学习算法特别用于clustering problems,其中有许多输入例子,你不知道这个类是什么,你甚至不知道可能的类是什么,他们很多。 这是一个明确的情况,当你不能使用监督学习,因为你不知道先验类的数量。

00003.jpeg
无监督的学习工作流程





深入学习


Deep learning techniques represent a remarkable step forward taken by machine learning in recent decades, having provided results never seen before in many applications, such as image and speech recognition or Natural Language Processing (NLP). 有几个原因导致了深度学习的发展,直到最近几十年才被置于机器学习领域的中心。 One reason, perhaps the main one, is surely represented by progress in hardware, with the availability of new processors, such as graphics processing units (GPUs), which have greatly reduced the time needed for training networks, lowering them by a factor of 10 or 20. 另一个原因当然是越来越多的数据集来训练一个系统,需要训练一定深度的架构和输入数据的高维度。

00004.jpeg
深度学习工作流程



Deep learning is based on the way the human brain processes information and learns, responding to external stimuli. 它包含一个机器学习模型,在several levels of representation Each level corresponds in this hypothetical model to a different area of the cerebral cortex: when the brain receives images, it processes them through various stages such as edge detection and form perception, that is, from a primitiverepresentation level to the most complex. 例如,在图像分类问题中,每个块通过filtering operations,在各个抽象级别,输入已经处理的数据,逐渐提取features。





TensorFlow – A general overview


TensorFlow(https://www.tensorflow.org/)是由Google Brain Team在Google机器学习情报研究机构开发的一个软件库,用于进行机器学习和深度神经网络研究。 然后TensorFlow结合了编译优化技术的计算代数,使得计算许多数学表达式变得容易,其中问题是执行计算所需的时间。
主要功能包括:
  • 定义,优化和高效地计算涉及多维数组(张量)的数学表达式。
  • 深度神经网络和机器学习技术的编程支持。
  • 透明地使用GPU计算,自动管理和优化相同的内存和使用的数据。 您可以编写相同的代码,并在CPU或GPU上运行它。 更具体地说,TensorFlow会计算哪些部分的计算应该移动到GPU。
  • 跨计算机和庞大的数据集计算的高可扩展性。


00005.jpeg


TensorFlow主页


TensorFlow可用于Python和C ++支持,我们将使用Python 2.7进行学习,因为Python API的确支持得更好,学习起来也更容易。 Python的安装取决于你的系统;下载页面(https://www.python.org/downloads/)包含安装所需的全部信息。 在下一节中,我们将通过一些编程实例,简要介绍Python语言的主要特性。



Python basics


Python是一种强类型和动态的语言(数据类型是必要的,但没有必要显式声明它们),区分大小写(var和VAR是两个不同的变量)和面向对象(Python中的所有东西都是对象)。


Syntax


在Python中,不需要行结束符,并且使用缩进指定块。 缩进开始一个块,并删除缩进结束,就这些了。 需要缩进块的指令以冒号结尾(:)。 注释以散列符号(#)开始,并且是单行的。 多行字符串用于多行注释。 赋值是用等号(=)完成的。 对于相等性测试,我们使用双等号(==)符号。 您可以使用+ =和 - =,然后加上加数来增加或减少一个值。 这适用于许多数据类型,包括字符串。 您可以在同一行上分配和使用多个变量。
以下是一些例子:
[mw_shl_code=bash,true]>>> myvar = 3
>>> myvar += 2
>>> myvar
5
>>> myvar -= 1
>>> myvar
4
"""This is a comment"""
>>> mystring = "Hello"
>>> mystring += " world."
>>> print mystring
Hello world.[/mw_shl_code]
下面的代码在一行中交换两个变量:
[mw_shl_code=bash,true]>>> myvar, mystring = mystring, myvar
[/mw_shl_code]

Data types


Python中最重要的结构是列表,元组和字典。 这些集合自2.5版本以来就集成在Python中(对于以前的版本,它们在集合库中是可用的)。 列表类似于一维数组,但您可以创建包含其他列表的列表。 字典是包含键和值对(哈希表)的数组,而元组是不可变的单维对象。 在Python中,数组可以是任何类型的,所以你可以在你的列表/字典和元组中混合使用整数,字符串等等。 任何类型数组中的第一个对象的索引始终为零。 Negative indices are allowed and counting from the end of the array, -1 is the last element. 变量可以引用函数。
[mw_shl_code=bash,true]>>> example = [1, ["list1", "list2"], ("one", "tuple")]
>>> mylist = ["Element 1", 2, 3.14]
>>> mylist [0]
"Element 1"
>>> mylist [-1]
3.14
>>> mydict = {"Key 1": "Val 1", 2: 3, "pi": 3.14}
>>> mydict ["pi"]
3.14
>>> mytuple = (1, 2, 3)
>>> myfunc = len
>>> print myfunc (mylist)
3[/mw_shl_code]
你可以得到一个数组范围使用冒号(:)。 不指定范围的起始索引意味着第一个元素;不表示最后的索引意味着最后一个元素。 从最后一个元素开始计算负指数(-1是最后一个元素)。 然后运行以下命令:
[mw_shl_code=bash,true]>>> mylist = ["first element", 2, 3.14]
>>> print mylist [:]
['first element', 2, 3.1400000000000001]
>>> print mylist [0:2]
['first element', 2]
>>> print mylist [-3:-1]
['first element', 2]
>>> print mylist [1:]
[2, 3.14][/mw_shl_code]


Strings


Python字符串用单引号(')或double()表示,并允许在另一个字符串的分隔字符串中使用符号(“他说'你好'。”这是有效的)。 多行字符串包含在三个(或单个)引号(“”“)中。 Python支持Unicode;只需使用以下语法:“这是一个unicode字符串”。 要将值插入到字符串中,请使用%运算符(模)和一个元组。 每个%由一个元组元素替换,从左到右,并被允许使用替代字典。
[mw_shl_code=bash,true]>>> print "Nome: %s\nNumber: %s\nString: %s" % (myclass.nome, 3, 3 * "-")
Name: Poromenos
Number: 3
String: ---
strString = """this is a string
on multiple lines."""
>>> print "This %(verbo)s un %(name)s." % {"name": "test", "verb": "is"}
This is a test.[/mw_shl_code]


Control flow


The instructions for flow control are if, for, and while. 有选择控制流程;在它的地方,我们使用if。 控制流的用于枚举列表的成员。 要获取数字列表,请使用范围(数字)。
[mw_shl_code=bash,true]rangelist = range(10)
>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][/mw_shl_code]
我们来检查number是否是元组中的数字之一:
[mw_shl_code=bash,true]for number in rangelist:
    if number in (3, 4, 7, 9):
        # "Break" ends the for instruction without the else clause
        break
    else:
        # "Continue" continues with the next iteration of the loop
        continue
else:
    # this is an optional "else"
    # executed only if the loop is not interrupted with "break".
    pass # it does nothing
if rangelist[1] == 2:
    print "the second element (lists are 0-based) is 2"
elif rangelist[1] == 3:
    print "the second element is 3"
else:
    print "I don't know"
while rangelist[1] == 1:
    pass[/mw_shl_code]


Functions


函数使用关键字def声明。 任何可选参数必须在必须的参数之后声明,并且必须赋值。 当使用参数来命名函数时,您还必须传递值。 函数可以返回一个元组(tuple unpacking可以返回多个值)。 Lambda函数是联机的。 参数是通过引用传递的,但不可变的类型(元组,整数,字符串等)不能在函数中改变。 发生这种情况是因为它只通过内存中元素的位置,并将另一个对象分配给该变量会导致之前丢失对象引用。
例如:
[mw_shl_code=bash,true]# equal to a def f(x): return x + 1
funzionevar = lambda x: x + 1
>>> print funzionevar(1)
2
def passing_example(my_list,my_int):
    my_list.append("new element")
    my_int = 4
    return my_list, my_int
>>> input_my_list = [1, 2, 3]
>>> input_my_int = 10
>>> print passing_example(input_my_list, input_my_int)
([1, 2, 3, 'new element'], 10)
>>> my_list
[1, 2, 3, 'new element']
>>> my_int
10[/mw_shl_code]


Classes


Python支持类的多重继承。 这些变量和私有方法是通过在两个下划线(__)之前用对流(它不是语言规则)声明的。 我们可以将属性(属性)分配给一个类的任意实例。
以下是一个例子:
[mw_shl_code=bash,true]class Myclass:
    common = 10
    def __init__(self):
        self.myvariable= 3
    def myfunc(self, arg1, arg2):
        return self.myvariable
# We create an instance of the class
>>> instance= Myclass()
>>> instance.myfunc(1, 2)
3
# This variable is shared by all instances
>>> instance2= Myclass()
>>> instance.common
10
>>> instance2.common
10
# Note here how we use the class name
# Instead of the instance.
>>> Myclass.common = 30
>>> instance.common
30
>>> instance2.common
30
# This does not update the variable in the class,
# Instead assign a new object to the variable
# of the first instance.
>>> instance.common = 10
>>> instance.common
10
>>> instance2.common
30
>>> Myclass.common = 50
# The value is not changed because "common" is an instance variable.
>>> instance.common
10
>>> instance2.common
50
# This class inherits from Myclass. Multiple inheritance
# is declared like this:
# class AltraClasse(Myclass1, Myclass2, MyclassN)
class AnotherClass(Myclass):
    # The topic "self" is automatically passed
    # and makes reference to instance of the class, so you can set
    # of instance variables as above, but within the class.   
def __init__(self, arg1):
        self.myvariable= 3
        print arg1
>>> instance= AnotherClass ("hello")
hello
>>> instance.myfunc(1, 2)
3
# This class does not have a member (property) .test member, but
# We can add one all instance when we want. Note
# .test That will be a member of only one instance.
>>> instance.test = 10
>>> instance.test
10[/mw_shl_code]




Exceptions


Python中的异常处理 尝试 - 除了 块[exception_name]:
[mw_shl_code=bash,true]def my_func():
    try:
        # Division by zero causes an exception
        10 / 0
    except ZeroDivisionError:
        print "Oops, error"
    else:
        # no exception, let's proceed
        pass
    finally:
# This code is executed when the block
    # Try..except is already executed and all exceptions
    # Were handled, even if there is a new
    # Exception directly in the block.
        print "finish"
>>> my_func()
Oops, error.
finish[/mw_shl_code]




Importing a library


使用导入[库名称]导入外部库。 您还可以使用[libraryname] import [funcname]格式导入各个功能。 这是一个例子:
[mw_shl_code=bash,true]import random
from time import clock
randomint = random.randint(1, 100)
>>> print randomint
64[/mw_shl_code]




Installing TensorFlow


TensorFlow Python API支持Python 2.7和Python 3.3+。 GPU版本(仅Linux)需要Cuda Toolkit> = 7.0和cuDNN> = v2。
在Python环境下工作时,建议使用virtualenv。 它将隔离不同项目的Python配置;使用virtualenv不会覆盖TensorFlow所需的Python软件包的现有版本。


Installing on Mac or Linux distributions


以下是在Mac和Linux系统上安装TensorFlow的步骤:
  • 首先安装pip和virtualenv(可选),如果它们尚未安装:
             对于Ubuntu / Linux 64位:
       [mw_shl_code=bash,true]$ sudo apt-get install python-pip python-dev python-virtualenv               对于Mac OS X:

            $ sudo easy_install pip
            $ sudo pip install --upgrade virtualenv[/mw_shl_code]
  • 然后你可以创建一个虚拟环境virtualenv。 以下命令在〜/ tensorflow目录中创建虚拟环境virtualenv:   [mw_shl_code=bash,true] $ virtualenv --system-site-packages ~/tensorflow[/mw_shl_code]
  • 下一步是激活virtualenv,如下所示:   [mw_shl_code=bash,true] $ source ~/tensorflow/bin/activate.csh    (tensorflow)$[/mw_shl_code]
  • 此后,我们正在使用的环境的名称位于命令行之前。 一旦激活,Pip就用来在其中安装TensorFlow。


               对于Ubuntu / Linux 64位,CPU:
[mw_shl_code=bash,true](tensorflow)$ pip install --upgrade https://storage.googleapis.com/t ... ne-linux_x86_64.whl
                 对于Mac OS X,CPU:

(tensorflow)$ pip install --upgrade https://storage.googleapis.com/t ... .0-py2-none-any.whl[/mw_shl_code]
如果你想用TensorFlow来使用你的GPU卡,那么安装另一个软件包。 我建议您访问官方文档,看看您的GPU是否符合支持TensorFlow所需的规格。
[url=]T0>注意[/url]
要使用TensorFlow启用GPU,可以参考(https://www.tensorflow.org/versions/r0.9/get_started/os_setup.html#optional-linux-enable-gpu-support)的完整描述。

最后,当你完成后,你必须禁用虚拟环境:
(tensorflow)$ deactivate[url=]T0>注意[/url]
鉴于本书的介绍性,我建议读者访问下载并设置TensorFlow页面(https://www.tensorflow.org/versions/r0.7/get_started/os_setup.html#download-and -setup)以查找有关安装TensorFlow的其他方法的更多信息。




Installing on Windows


如果您无法获得基于Linux的系统,则可以在虚拟机上安装Ubuntu;只需使用名为VirtualBox的免费应用程序,即可在Windows上创建虚拟PC,并在后者中安装Ubuntu。 因此,您可以尝试操作系统而不创建分区或处理繁琐的过程。
[url=]T0>注意[/url]
安装好VirtualBox后,你可以安装Ubuntu(www.ubuntu.com),然后按照Linux机器的安装来安装TensorFlow。




Installation from source


但是,可能会发生Pip安装会导致问题,特别是在使用可视化工具TensorBoard时 https://github.com/tensorflow/tensorflow/issues/530)。 为了解决这个问题,我建议你建立并安装TensorFlow,从源文件开始,通过以下步骤:
  • 克隆TensorFlow存储库:[mw_shl_code=bash,true]git clone --recurse-submodules   
    [/mw_shl_code]
  • 安装Bazel(依赖项和安装程序),按照以下说明进行操作:
  • 运行Bazel安装程序:[mw_shl_code=bash,true]   chmod +x bazel-version-installer-os.sh
      ./bazel-version-installer-os.sh --user[/mw_shl_code]
  • 安装Python依赖关系:
    [mw_shl_code=bash,true]sudo apt-get install python-numpy swig python-dev
    [/mw_shl_code]配置(GPU还是不用GPU?) 您在TensorFlow下载的存储库中安装:
  • ./configure
  • 使用bazel创建您自己的TensorFlow Pip包:
    [mw_shl_code=bash,true]bazel build -c opt //tensorflow/tools/pip_package:build_pip_package
    [/mw_shl_code]要使用GPU支持构建,请使用bazel build -c opt --config = cuda,然后再次执行:
  • //tensorflow/tools/pip_package:build_pip_package
  • 最后,安装TensorBoard,其中.whl文件的名称取决于您的平台。
    [mw_shl_code=bash,true]   pip install /tmp/tensorflow_pkg/tensorflow-0.7.1-py2-none- linux_x86_64.whl
    [/mw_shl_code]祝你好运!


[url=]T0>注意[/url]



Testing your TensorFlow installation


打开一个终端并键入以下几行代码:
[mw_shl_code=bash,true]>>> import tensorflow as tf
>>> hello = tf.constant("hello TensorFlow!")
>>> sess=tf.Session()[/mw_shl_code]
要验证您的安装,只需键入:
[mw_shl_code=bash,true]>>> print(sess.run(hello))
[/mw_shl_code]您应该有以下输出:[mw_shl_code=bash,true]Hello TensorFlow!
>>>[/mw_shl_code]


First working session


最后是从理论走向实践的时候了。 我将使用Python 2.7 IDE来编写所有的例子。 要初步了解如何使用TensorFlow,请打开Python编辑器并编写以下几行代码:
[mw_shl_code=bash,true]x = 1
y = x + 9
print(y)
import tensorflow as tf
x = tf.constant(1,name='x')
y = tf.Variable(x+9,name='y')
print(y)[/mw_shl_code]
As you can easily understand in the first three lines, the constant x, set equal to 1, is then added to 9 to set the new value of the variable y, and then the end result of the variable y is printed on the screen.
在最后的四行中,我们根据TensorFlow库将前三个变量进行了翻译。
如果我们运行该程序,我们有以下输出:
[mw_shl_code=bash,true]10
<tensorflow.python.ops.variables.Variable object at    0x7f30ccbf9190>[/mw_shl_code]
程序示例前三行的TensorFlow翻译会产生不同的结果。 我们来分析一下:
  • 如果您想使用TensorFlow库,请不要错过以下语句。 它告诉我们,我们正在导入库并称之为tf:
    [mw_shl_code=bash,true]import tensorflow as tf
    [/mw_shl_code]我们创建一个名为x的常数值,其值等于1:
  • [mw_shl_code=bash,true]x = tf.constant(1,name='x')
    [/mw_shl_code]然后我们创建一个名为y的变量。 这个变量是用简单的等式定义的:y = x + 9:
  • [mw_shl_code=bash,true]y = tf.Variable(x+9,name='y')
    [/mw_shl_code]最后打印出结果:
  • [mw_shl_code=bash,true]print(y)
    [/mw_shl_code]那么我们如何解释不同的结果呢? 区别在于变量的定义。 事实上,变量y不代表x + 9的当前值,而是代表:when the variable y is computed, take the value of the constant x and add 9 to it。 这就是为什么y的值从未被执行的原因。 在下一节中,我将尝试修复它。

所以我们打开Python IDE并输入以下几行:

00006.jpeg


运行上面的代码,输出结果最终如下:
10
我们删除了打印指令,但是我们已经初始化了模型变量:
[mw_shl_code=bash,true]model = tf.initialize_all_variables()
[/mw_shl_code]而且,大多数情况下,我们已经创建了一个计算值的会话。 下一步,我们运行先前创建的模型,最后运行变量y并打印出当前值。[mw_shl_code=bash,true]with tf.Session() as session:
    session.run(model)
    print(session.run(y))[/mw_shl_code]
这是允许正确结果的魔术。 在这个基本步骤中,称为数据流图的执行图被创建在会话中,具有所有变量之间的依赖关系。 y变量&#8203;&#8203;取决于变量x,该值通过向其添加9进行转换。 在会话执行之前,不会计算该值。
最后一个例子介绍了TensorFlow中的另一个重要特性,即数据流图。


Data Flow Graphs


机器学习应用程序是重复计算复杂数学表达式的结果。 In TensorFlow, a computation is described using the Data Flow Graph, where each node in the graph represents the instance of a mathematical operation (multiply, add, divide, and so on), and each edge is a multi-dimensional data set (tensors) on which the operations are performed.
TensorFlow支持这些构造和这些运算符。 让我们来看看TensorFlow如何管理节点和边缘:
  • Node:在TensorFlow中,每个节点代表一个操作的实例。 每个操作都有&gt; =个输入和&gt; = 0个输出。
  • Edges:在TensorFlow中,有两种类型的边:
    • Normal Edges: They are carriers of data structures (tensors), where an output of one operation (from one node) becomes the input for another operation.
    • Special Edges: These edges are not data carriers between the output of a node (operator) and the input of another node. 一个特殊的边缘表示两个节点之间的控制依赖关系。 Let's suppose we have two nodes A and B and a special edges connecting A to B; it means that B will start its operation only when the operation in A ends. 数据流图中使用特殊的边来设置张量上的操作之间的发生之前的关系。




我们来更详细地研究数据流图中的一些功能:
  • Operation:这表示一个抽象计算,例如添加或乘以矩阵。 操作管理张量。 它可以是多态的:相同的操作可以操作不同的张量元素类型。 例如,添加两个int32张量,添加两个浮点张量,等等。
  • Kernel: This represents the concrete implementation of that operation. 内核定义了特定设备上操作的实现。 例如,一个添加矩阵操作可以有一个CPU实现和一个GPU。 在下面的章节中,我们介绍了会话的概念,在TensorFlow中创建一个del执行图。 我们来解释一下这个话题:
  • Session: When the client program has to establish communication with the TensorFlow runtime system, a session must be created. 一旦为客户端创建会话,就会创建一个初始图形并为空。 它有两个基本的方法:
    • session.extend: In a computation, the user can extend the execution graph, requesting to add more operations (nodes) and edges (data).
    • session.run: Using TensorFlow, sessions are created with some graphs, and these full graphs are executed to get some outputs, or sometimes, subgraphs are executed thousands/millions of times using run invocations. 基本上,该方法运行执行图来提供输出。






00007.jpeg
数据流图中的特征






TensorFlow programming model


采用数据流图作为执行模型,您可以使用一个隐藏所有复杂性的单一编程接口,将数据流设计(图形构建和数据流)与其执行(CPU,GPU卡或其组合)分开。 它还定义了TensorFlow中的编程模型。
让我们考虑乘以两个整数的简单问题,即a和b。
以下是这个简单的问题所需的步骤:
  • 定义和初始化变量。 每个变量都应该定义当前执行的状态。 在Python中导入TensorFlow模块之后:import tensorflow as tf
  • 我们定义参与计算的变量a和b。 这些是通过一个更基本的结构来定义的,称为占位符:a = tf.placeholder("int32")b = tf.placeholder("int32")
  • 一个占位符允许我们创建我们的操作并构建我们的计算图without needing数据。
  • 然后我们使用这些变量作为TensorFlow函数mul的输入:y = tf.mul(a,b)this function will return the result of the multiplication the input   integers a and b.
  • 管理执行流程,这意味着我们必须建立一个session:sess = tf.Session()
  • 可视化结果。 我们在变量a和b上运行模型,通过先前定义的占位符将数据提供给数据流图。print sess.run(y , feed_dict={a: 2, b: 5})





How to use TensorBoard


TensorBoard是一个可视化工具,致力于分析数据流图,并更好地理解机器学习模型。 它可以以图形方式查看关于计算机图形的任何部分的参数和细节的不同类型的统计。 通常情况下,计算图可能非常复杂。 深度神经网络可以有多达36,000个节点。 为此,TensorBoard折叠高层块中的节点,突出显示具有相同结构的组。 这样做可以更好地分析图表,只关注计算图的核心部分。 另外,可视化过程是交互式的;用户可以平移,缩放和展开节点以显示细节。
下图显示了带有TensorBoard的神经网络模型:

00008.jpeg
一个TensorBoard可视化的例子



TensorBoard的算法将节点分解为高级块并突出显示具有相同结构的组,同时还分离出高度节点。 可视化工具也是交互式的:用户可以平移,放大,展开和折叠节点。
TensorBoard在机器学习模型的开发和调整中同样有用。 出于这个原因,TensorFlow允许您在图中插入所谓的summary operations。 这些汇总操作监视写在日志文件中的更改值(执行计算期间)。 然后,TensorBoard被配置为通过摘要信息观察这个日志文件,并显示这个信息随着时间的变化。
让我们考虑一个基本的例子来了解TensorBoard的用法。 我们有以下例子:
[mw_shl_code=bash,true]import tensorflow as tf
a = tf.constant(10,name="a")
b = tf.constant(90,name="b")
y = tf.Variable(a+b*2, name="y")
model = tf.initialize_all_variables()
with tf.Session() as session:
    merged = tf.merge_all_summaries()
    writer = tf.train.SummaryWriter\
                      ("/tmp/tensorflowlogs",session.graph)   
     session.run(model)
    print(session.run(y))[/mw_shl_code]
这给出了以下结果:
190
我们来谈谈会话管理。 第一条要考虑的指令如下:
[mw_shl_code=bash,true]merged = tf.merge_all_summaries()
[/mw_shl_code]该指令必须合并默认图表中收集的所有摘要。
然后我们创建SummaryWriter。 它会将从代码执行中获得的所有摘要(在本例中为执行图)写入/ tmp / tensorflowlogs目录中:
[mw_shl_code=bash,true]writer = tf.train.SummaryWriter\
                    ("/tmp/tensorflowlogs",session.graph)[/mw_shl_code]
最后,我们运行模型,然后构建数据流图:
[mw_shl_code=bash,true]session.run(model)
print(session.run(y))[/mw_shl_code]
使用TensorBoard非常简单。 我们打开一个终端并输入以下内容:
[mw_shl_code=bash,true]$tensorboard --logdir=/tmp/tensorflowlogs
[/mw_shl_code]应该显示如下信息:startig tensorboard on port 6006
然后,打开一个Web浏览器,我们应该显示带有辅助节点的数据流图:

00009.jpeg
数据流图显示与TensorBoard



现在我们将能够探索数据流图:

00010.jpeg
用TensorBoard探索数据流图显示



TensorBoard使用常量和汇总节点的特殊图标。 总结一下,我们在下图中报告显示的节点符号表:

00011.jpeg
在TensorBoard中的节点符号






Summary


在本章中,我们介绍了主要的主题:machine learning和deep learning。 当机器学习探索可以学习和预测数据的算法s的研究和构建时,深度学习正是基于human brain processes information and learns
In this vast scientific research and practical application area, we can firmly place the TensorFlow software library, developed by the Google's research group for artificial intelligence (Google Brain Project) and released as open source software on November 9, 2015.
在选择Python编程语言作为我们的例子和应用程序的开发工具之后,我们看到了如何安装和编译这个库,然后进行了第一个工作会话。 这使我们能够引入TensorFlow和Data Flow Graph的执行模型。 它引导我们定义我们的编程模型应该是什么。
本章以如何使用调试机器学习应用程序的重要工具为例结束:TensorBoard。
在下一章中,我们将继续进入TensorFlow库,以展示其多功能性。 从基本概念,张量出发,我们将看到如何将这个库用于纯粹的数学应用。


http://usyiyi.cn/documents/getting-started-with-tf/ch1.html


没找到任何评论,期待你打破沉寂

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条