Tensorflow学习笔记

Install

Ubuntu14.04:

#安装pip
sudo apt-get install python-pip python-dev 

#安装tensorflow
sudo pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.8.0-cp27-none-linux_x86_64.whl

#安装python-numpy ,python-scipy,python-matplotlib
sudo apt-get install python-numpy
sudo apt-get install python-scipy
sudo apt-get install python-matplotlib

官网上的tensorflow安装命令在虚拟机里面安装不上,可能是网络的问题。

测试是否安装成功:

>>> import tensorflow as tf
>>> hello = tf.constant('Hello, TensorFlow!')
>>> sess = tf.Session()
>>> print(sess.run(hello))
Hello, TensorFlow!
>>> a = tf.constant(10)
>>> b = tf.constant(32)
>>> print(sess.run(a + b))
42

Basic Usage

TensorFlow的基本内容:

  • 用图(graph)来表示计算任务
  • 在会话(Session)中执行图
  • 用(tensor)表示数据
  • 用变量(Variable)维护状态
  • 用feed和fetch来赋值或取值

构建图

构建图,首先创建源op,比如(Constant)。
TensorFlow Python 库有一个默认图(default graph), op 构造器可以为其增加节点,通常这个默认图对许多程序来说已经够用了。
图构造完成后,需要启动图才能运行操作。启动图需要创建一个Session,参数缺省启动默认图。

以下是示例代码:

import tensorflow as tf

# 创建一个常量 op, 产生一个 1x2 矩阵. 这个 op 被作为一个节点
# 加到默认图中.
#
# 构造器的返回值代表该常量 op 的返回值.
matrix1 = tf.constant([[3., 3.]])

# 创建另外一个常量 op, 产生一个 2x1 矩阵.
matrix2 = tf.constant([[2.],[2.]])

# 创建一个矩阵乘法 matmul op , 把 'matrix1' 和 'matrix2' 作为输入.
# 返回值 'product' 代表矩阵乘法的结果.
product = tf.matmul(matrix1, matrix2)

# 启动默认图.
sess = tf.Session()

# 调用 sess 的 'run()' 方法来执行矩阵乘法 op, 传入 'product' 作为该方法的参数. 
# 上面提到, 'product' 代表了矩阵乘法 op 的输出, 传入它是向方法表明, 我们希望取回
# 矩阵乘法 op 的输出.
#
# 整个执行过程是自动化的, 会话负责传递 op 所需的全部输入. op 通常是并发执行的.
# 
# 函数调用 'run(product)' 触发了图中三个 op (两个常量 op 和一个矩阵乘法 op) 的执行.
#
# 返回值 'result' 是一个 numpy `ndarray` 对象.
result = sess.run(product)
print result
# ==> [[ 12.]]

# 任务完成, 关闭会话.
sess.close()

Session对象使用完成后需要关闭释放资源。除了显示调用close以外,也可以用以下方式来代替原来方法:

with tf.Session() as sess:
  result = sess.run([product])
  print result

在实现上,TensorFlow 将图形定义转换成分布式执行的操作,以充分利用可用的计算资源(如 CPU 或 GPU)。一般不需要显式指定使用 CPU 还是 GPU,TensorFlow 能自动检测。如果检测到 GPU,TensorFlow 会尽可能地利用找到的第一个 GPU 来执行操作。

如果机器上有超过一个可用的 GPU, 除第一个外的其它 GPU 默认是不参与计算的. 为了让 TensorFlow 使用这些 GPU, 你必须将 op 明确指派给它们执行. with…Device 语句用来指派特定的 CPU 或 GPU 执行操作:

with tf.Session() as sess:
  with tf.device("/gpu:1"):
    matrix1 = tf.constant([[3., 3.]])
    matrix2 = tf.constant([[2.],[2.]])
    product = tf.matmul(matrix1, matrix2)

设备用字符串进行标识,目前支持的设备包括:

"/cpu:0": 机器的 CPU.
"/gpu:0": 机器的第一个 GPU, 如果有的话.
"/gpu:1": 机器的第二个 GPU, 以此类推.

交互式方法

文档中的 Python 示例使用一个会话 Session 来 启动图,并调用 Session.run() 方法执行操作。

为了便于使用诸如 IPython 之类的 Python 交互环境, 可以使用 InteractiveSession 代替 Session 类,使用 Tensor.eval() 和 Operation.run() 方法代替 Session.run()。这样可以避免使用一个变量来持有会话。
以下是示例代码:

# 进入一个交互式 TensorFlow 会话.
import tensorflow as tf
sess = tf.InteractiveSession()

x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])

# 使用初始化器 initializer op 的 run() 方法初始化 'x' 
x.initializer.run()

# 增加一个减法 sub op, 从 'x' 减去 'a'. 运行减法 op, 输出结果 
sub = tf.sub(x, a)
print sub.eval()
# ==> [-2. -1.]

变量

变量维护图执行过程中的状态信息,下面的例子演示了如何使用变量实现一个简单的计数器:

# 创建一个变量, 初始化为标量 0.
state = tf.Variable(0, name="counter")

# 创建一个 op, 其作用是使 state 增加 1

one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)

# 启动图后, 变量必须先经过`初始化` (init) op 初始化,
# 首先必须增加一个`初始化` op 到图中.
init_op = tf.initialize_all_variables()

# 启动图, 运行 op
with tf.Session() as sess:
  # 运行 'init' op
  sess.run(init_op)
  # 打印 'state' 的初始值
  print sess.run(state)
  # 运行 op, 更新 'state', 并打印 'state'
  for _ in range(3):
    sess.run(update)
    print sess.run(state)

# 输出:

# 0
# 1
# 2
# 3

在调用 run() 执行表达式之前,图所描绘的表达式(assign(), add() ….)并不会真正执行赋值操作。

[ ]可以在run的时候取回多个tensor:

input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
intermed = tf.add(input2, input3)
mul = tf.mul(input1, intermed)

with tf.Session():
  result = sess.run([mul, intermed])
  print result

# 输出:
# [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]

还可以用一下方式来待定参数,在run的时候再设定输入:

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.mul(input1, input2)

with tf.Session() as sess:
  print sess.run([output], feed_dict={input1:[7.], input2:[2.]})

# 输出:
# [array([ 14.], dtype=float32)]

MNIST Training

MNIST是在机器学习领域中的一个经典问题。该问题解决的是把28x28像素的灰度手写数字图片识别为相应的数字,其中数字的范围从0到9。

MNIST是ML界的’hello world’,这个比喻还挺有意思的。

MNIST Data

MNIST数据集有四个文件:

  • train-images-idx3-ubyte.gz:训练集图片 - 55000 张 训练图片,5000 张 验证图片。
  • train-labels-idx1-ubyte.gz:训练集图片对应的数字标签。
  • t10k-images-idx3-ubyte.gz:测试集图片 - 10000 张 图片。
  • t10k-labels-idx1-ubyte.gz:测试集图片对应的数字标签。

这些文件本身并没有使用标准的图片格式存储。在下面代码中extract_images()和extract_labels()函数可以手动解压他们。

图片数据将被解压成2维的tensor:[image index, pixel index] 其中每一项表示某一图片中特定像素的强度值。”image index”代表数据集中图片的编号,从0到数据集的上限值。”pixel index”代表该图片中像素点的个数, 从0到图片的像素上限值。

以train-*开头的文件中包括60000个样本,其中分割出55000个样本作为训练集,其余的5000个样本作为验证集。因为所有数据集中28x28像素的灰度图片的尺寸为784,所以训练集输出的tensor格式为[55000, 784]。

数字标签数据被解压成1维的tensor:[image index],它定义了每个样本数值的类别分类。对于训练集的标签来说,这个数据规模就是:[55000]。

解压重构图片和标签数据之后,会得到如下数据集对象:

  • data_sets.train:55000 组 图片和标签,用于训练。
  • data_sets.validation:5000 组 图片和标签,用于迭代验证训练的准确性。
  • data_sets.test:10000 组 图片和标签, 用于最终测试训练的准确性。

调用以下代码中的read_data_sets()函数,将会返回一个DataSet实例,其中包含了以上三个数据集。

函数DataSet.next_batch()是用于获取以batch_size为大小的一个元组,其中包含了一组图片和标签,该元组会被用于当前的TensorFlow运算会话中。

下载数据的代码:

# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unles
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值