TensorFlow的基本介绍及"Hello,world"

转载自:
http://www.tensorfly.cn/tfdoc/get_started/basic_usage.html
https://blog.csdn.net/sarsscofy/article/details/78541836

基本使用:

  1. 使用(graph)来表示计算任务
  2. 在被称之为 会话 (Session) 的上下文 (context) 中执行图.
  3. 使用 tensor 表示数据.
  4. 通过 变量 (Variable) 维护状态.
  5. 使用 feed 和 fetch 可以为任意的操作(arbitrary operation) 赋值或者从其中获取数据.

综述:

图中的节点被称之为 op (operation 的缩写)。 一个 op 获得 0 个或多个 Tensor(图中的有向边), 执行计算, 产生 0 个或多个 Tensor.。每个 Tensor 是一个类型化的多维数组。

计算图(graph)

TensorFlow 程序通常被组织成一个构建阶段和一个执行阶段。
在构建阶段, op 的执行步骤 被描述成一个图。
在执行阶段, 使用会话(Session)执行执行图中的 op。
例如, 通常在构建阶段创建一个图来表示和训练神经网络, 然后在执行阶段反复执行图中的训练 op。
TensorFlow 支持 C, C++, Python 编程语言。目前, TensorFlow 的 Python 库更加易用, 它提供了大量的辅助函数来简化构建图的工作, 这些函数尚未被 C 和 C++ 库支持。

构建图

构建图的第一步, 是创建源 op (source op)。源 op 不需要任何输入, 例如 常量 (Constant). 源 op 的输出被传递给其它 op 做运算。
Python 库中, op 构造器的返回值代表被构造出的 op 的输出, 这些返回值可以传递给其它 op 构造器作为输入。
TensorFlow Python 库有一个默认图 (default graph), op 构造器可以为其增加节点。这个默认图对 许多程序来说已经足够用了。

在一个会话中启动图

构造阶段完成后, 才能启动图。启动图的第一步是创建一个 Session 对象, 如果无任何创建参数, 会话构造器将启动默认图。
Session 对象在使用完后需要关闭以释放资源。 除了显式调用 close 外, 也可以使用 “with” 代码块 来自动完成关闭动作。
在实现上, TensorFlow 将图形定义转换成分布式执行的操作, 以充分利用可用的计算资源(如 CPU 或 GPU)。 一般你不需要显式指定使用 CPU 还是 GPU, TensorFlow 能自动检测。 如果检测到 GPU, TensorFlow 会尽可能地利用找到的第一个 GPU 来执行操作。
如果机器上有超过一个可用的 GPU, 除第一个外的其它 GPU 默认是不参与计算的。 为了让 TensorFlow 使用这些 GPU, 你必须将 op 明确指派给它们执行。 with…Device 语句用来指派特定的 CPU 或 GPU 执行操作。

实践项目

MNIST是机器学习中的“hello,world”。该项目分为一下几个步骤

  1. 数据集的下载(不要解压),网址为:http://yann.lecun.com/exdb/mnist/,下载后在运行代码目录下新建MNIST_data文件夹,把上述四个文件放入该文件夹下。
    train-images-idx3-ubyte.gz: training set images (9912422 bytes)
    train-labels-idx1-ubyte.gz: training set labels (28881 bytes)
    t10k-images-idx3-ubyte.gz: test set images (1648877 bytes)
    t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes)

  2. 编写自动安装和下载MNIST数据集的python代码,代码写入文件input_data.py中,该文件和运行代码同一个目录,input_data.py文件内容编码为utf-8。(代码部分在下面显示)

  3. 编写运行代码文件Test_1.py。

两个.py文件加一个文件夹如下图所示,
这里写图片描述
MNIST_data文件夹下有四个下载的数据文件;
input_data.py是自动下载和安装的MNIST数据集的python代码;
Test_1.py是运行代码;
其中input_data.py代码如下:

"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import gzip
import os
import tempfile

import numpy
from six.moves import urllib
from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets

其中Test_1.py代码如下:

扫描二维码关注公众号,回复: 3697719 查看本文章
#!/usr/bin/env python3  
# -*- coding: utf-8 -*- 
import input_data
import tensorflow as tf

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
#x不是一个特定的值,而是一个占位符placeholder,我们在TensorFlow运行计算时输入这个值。
#我们希望能够输入任意数量的MNIST图像,每一张图展平成784维的向量。
#我们用2维的浮点数张量来表示这些图,这个张量的形状是[None,784 ]。
#(这里的None表示此张量的第一个维度可以是任何长度的。)
x = tf.placeholder(tf.float32, [None, 784])
#权重值,初始值全为0
W = tf.Variable(tf.zeros([784,10]))
#偏置量,初始值全为0
b = tf.Variable(tf.zeros([10]))

#建立模型,y是匹配的概率
#tf.matmul(x,W)表示x乘以W
#y是预测,y_是实际
y = tf.nn.softmax(tf.matmul(x,W) + b)

#为计算交叉熵,添加的placeholder
y_ = tf.placeholder("float", [None,10])
#交叉熵
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
#用梯度下降算法(gradient descent algorithm)以0.01的学习速率最小化交叉熵
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

#初始化我们创建的变量
init = tf.global_variables_initializer()

#在Session里面启动模型
sess = tf.Session()
sess.run(init)

#训练模型
#循环的每个步骤中,都会随机抓取训练数据中的100个批处理数据点,然后用这些数据点作为参数替换之前的占位符来运行train_step
#即:使用的随机梯度下降训练方法
for i in range(1000):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

#-------------------模型评估----------------------
#判断预测标签和实际标签是否匹配 
#tf.argmax 找出某个tensor对象在某一维上的其数据最大值所在的索引值
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

#计算所学习到的模型在测试数据集上面的正确率 
print (sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

运行结果显示,每次运行的结果可能不一样。

Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
2018-08-15 19:42:54.657354: W c:\l\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2018-08-15 19:42:54.657354: W c:\l\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2018-08-15 19:42:54.657354: W c:\l\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2018-08-15 19:42:54.657354: W c:\l\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2018-08-15 19:42:54.657354: W c:\l\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2018-08-15 19:42:54.658354: W c:\l\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2018-08-15 19:42:54.658354: W c:\l\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2018-08-15 19:42:54.658354: W c:\l\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
2018-08-15 19:42:54.753360: I c:\l\work\tensorflow-1.1.0\tensorflow\core\common_runtime\gpu\gpu_device.cc:887] Found device 0 with properties: 
name: GeForce GT 630
major: 3 minor: 0 memoryClockRate (GHz) 0.8755
pciBusID 0000:01:00.0
Total memory: 2.00GiB
Free memory: 1.72GiB
2018-08-15 19:42:54.754360: I c:\l\work\tensorflow-1.1.0\tensorflow\core\common_runtime\gpu\gpu_device.cc:908] DMA: 0 
2018-08-15 19:42:54.754360: I c:\l\work\tensorflow-1.1.0\tensorflow\core\common_runtime\gpu\gpu_device.cc:918] 0:   Y 
2018-08-15 19:42:54.754360: I c:\l\work\tensorflow-1.1.0\tensorflow\core\common_runtime\gpu\gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GT 630, pci bus id: 0000:01:00.0)
0.9117

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/u010551600/article/details/81707390