tensorflow学习入门

Tensorflow
官网:
Github
https://github.com/tensorflow/tensorflow  (内含get_started tutorial 文档)
 github中文:
tensorflow中文社区:
 神经网络训练图形演示:
基于TensorFlow更高阶的API:
https://github.com/tensorflow/skflow( Tensorflow 0.8已经将skflow包含进来, import tensorflow.contrib.learn as skflow)
Keras
SciKit flow

tensorflow serving相当于提供了dump、load以及提供输出能力(相当于对外提供API)

安装
官方提供的安装方式包含以下几种:
We support different ways to install TensorFlow:
·  Pip install : Install TensorFlow on your machine, possibly
upgrading previously installed Python packages. May impact existing
Python programs on your machine.
·  Virtualenv install Install TensorFlow in its own
directory, not impacting any existing Python programs on your machine.
·  Anaconda install : Install TensorFlow in its own
environment for those running the Anaconda Python distribution. Does not
impact existing Python programs on your machine.
·  Docker install : Run TensorFlow in a Docker container
isolated from all other programs on your machine.
·  Installing from sources : Install TensorFlow by
building a pip wheel that you then install using pip.
 
  分布式部署:
推荐采用Anaconda/ Virtualenv 方式安装,该方式会将需要的python 环境独立安装到 tensorflow 下。

pip install  :
这里以python3为例:
export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0rc2-cp34-cp34m-linux_x86_64.whl
pip3 install --upgrade $TF_BINARY_URL
(可能会用到pip升级:pip install --upgrade pip

Anaconda:
假设已经安装了Anaconda环境,那么安装起来非常简单:
$source activate python2
(python2)$ conda install -c conda-forge tensorflow #0.11版
安装好后,import tensorflow报错,提示:
ImportError: /lib64/libc.so.6: version `GLIBC_2.14' not found (required by /export/App/anaconda3/envs/ml2/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow.so)
参考:https://my.oschina.net/zhangxu0512/blog/262275
安装好2.14后,可能会继续报2.17的错误

Virtual Env:
With Virtualenv the installation is as follows:
1 Install pip and Virtualenv.
2 Create a Virtualenv environment.
3 Activate the Virtualenv environment and install TensorFlow in it.
4 After the install you will activate the Virtualenv environment each time you
want to use TensorFlow.
Install pip and Virtualenv:
# Ubuntu/Linux 64-bit
sudo apt-get install python-pip python-dev python-virtualenv
 
Create a Virtualenv environment in the directory ~/tensorflow( 路径可以自定 ):
virtualenv --system-site-packages ~/tensorflow
 
Activate the environment and use pip to install TensorFlow inside it:
source ~/tensorflow/bin/activate   # If using bash
$ source ~/tensorflow/bin/activate.csh  # If using csh
(tensorflow) $  # Your prompt should change
 
# Ubuntu/Linux 64-bit, CPU only, Python 2.7:
(tensorflow)$  pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.8.0-cp27-none-linux_x86_64.whl
  从source code安装:
(1)git clone https://github.com/tensorflow/tensorflow --recursive
(2)安装google的 bazel来编译
chmod +x PATH_TO_INSTALL.SH
./PATH_TO_INSTALL.SH --user

直接安装如果失败,可以尝试从源码安装bazel:
cd bazel
git checkout master
./compile.sh
Build successful! Binary is here: /export/App/bazel/output/bazel
注意安装完后的路径是上面给出的路径,由于上面的sh已经把bazel安装到/usr/local/bin/bazel下,所以要使用新安装的bazel修改tensorflow/configure里的bazel改为绝对路径。

(3)安装其他依赖:
# For Python 2.7:$ sudo apt-get install python-numpy swig python-dev python-wheel# For Python 3.x:$ sudo apt-get install python3-numpy swig python3-dev python3-wheel
(4)configuration:
./configure --user
(5) Create the pip package and install
bazel build -c opt //tensorflow/tools/pip_package:build_pip_package
报错:
/usr/local/bin/bazel: line 88: /usr/local/lib/bazel/bin/bazel-real: cannot execute binary file
这里解决是重新安装bazel,参考(2)中的从源码安装bazel

上面的步骤完成后,测试一下是否安装成功:
Try your first TensorFlow program
 
$ python
 
>>>  import tensorflow as tf
>>> hello = tf.constant('Hello, TensorFlow!')
>>> sess = tf.Session()
>>> sess.run(hello)
Hello, TensorFlow!
>>> a = tf.constant(10)
>>> b = tf.constant(32)
>>> sess.run(a+b)
42
>>>
 
测试一下:
启动tensorboard
 
首先需要先运行一个写日志的程序,并且已知日志的路径,执行:
$python -m tensorflow.models.image.cifar10.cifar10_train
 
$tensorboard --logdir=/tmp/to/log-directory
logdir 指定运行日志路径

Tensorflow mnist数据集CNN实例代码:
文件:tensorflow/tensorflow/models/image/mnist/convolutional.py
Tensorflow RNN代码实例:
文件:tensorflow/models/rnn/ptb/ptb_word_lm.py

数据集
Training set:  a set of examples used for learning: to fit the parameters of the classifier In the MLP case, we would use the training set to find the “optimal” weights with the back-prop rule
Validation set:  a set of examples used to tune the parameters of a classifier In the MLP case, we would use the validation set to find the “optimal” number of hidden units or determine a stopping point for the back-propagation algorithm(pick the optimal model)
Test set:  a set of examples used only to assess the performance of a fully-trained classifier In the MLP case, we would use the test to estimate the error rate after we have chosen the final model (MLP size and actual weights) After assessing the final model on the test set, YOU MUST NOT tune the model any further!

基础知识:
tensorflow  = tensor + flow = ndarray + dag图(网络),也就是通过每一个DAG有向图把每一步操作op 连接起来,传递 输入 输出都是一个nd array 多维数组(numpy) 然后在tensorFlow的回话中进行计算操作.
使用 TensorFlow 之前你需要了解关于 TensorFlow 的以下基础知识(教程1.3 Basic Usage):
• 使用图 (graphs) 来表示计算.
TensorFlow 是一个以图 (graphs) 来表示计算的编程系统, 图中的节点被称之为 op (op-eration 的缩写). 一个 op 获得零或多个张量 (tensors) 执行计算, 产生零或多个张量。TensorFlow 的图是一种对计算的抽象描述,TensorFlow的一个 描述了一个计算过程。
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1 , matrix2)
默认图现在拥有三个节点,两个constant() op,一个matmul() op.

• 使用张量 (tensors) 来代表数据.
TensorFlow 程序使用 tensor 数据结构来代表所有的数据, 计算图中, 操作间传递的数据都是 tensor. 可以把 TensorFlow 的张量看作是一个 n 维的数组或列表,通常来说, 张量可以用多维数组来表示. 一个 tensor包含一个静态类型 rank, 和一个 shape. Tensorflow提供的张量和numpy很相似,下面将numpy和Tensorflow中的部分定义和操作做成了一张一一对应的表格,方便查看。
Numpy Tensor
a = np.zeros((2,2)); b = np.ones((2,2)) a = tf.zeros((2,2)), b = tf.ones((2,2))
np.sum(b, axis=1) tf.reduce_sum(a,reduction_indices=[1])
a.shape a.get_shape()
np.reshape(a, (1,4)) tf.reshape(a, (1,4))
b*5+1 b*5+1
np.dot(a,b) tf.matmul(a, b)
a[0,0], a[:,0], a[0,:] a[0,0], a[:,0], a[0,:]
Tensorflow的输出要稍微注意一下,我们需要显式地输出(evaluation,也就是说借助eval()函数)!

• 通过变量 (Variables) 维护状态.
张量(constant tensors)是不可变的,变量维持了图执行过程中的状态信息。我们要预先对变量初始化(initialization): sess.run(tf.initialize_all_variables())
Tensorflow 的变量必须先初始化然后才有值!而常值张量是不需要的

• 在会话 (Session) 中执行图.
为了进行计算, 必须在 会话(Session)里被启动, 会话(Session)op分发到CPU或GPU之类的设备上,同时提供执行 op的方法。在代码中创建会话 Session 对象来启动图, 并调用 Session.run() 方法执行操作。
# Launch the default graph.
sess = tf.Session()

• 使用供给 (feeds) 和取回 (fetches) 将数据传入或传出任何操作.
Fetches:
为了取回操作的输出内容, 可以在使用 Session 对象的 run() 调用执行图时, 传入一些 tensor, 这些 tensor 会帮助你取回结果.
run方法如果传入的参数是一个op,那么返回的是None;如果参数传入的是一个tensor,返回的是 numpy ndarray containing the value of that tensor.
Feeds:
Tensorflow还提供了feed机制,该机制可以临时替代图中的任意操作中的张量,也就是说,可以对图中任何操作提交补丁,直接插入一个新的张量。feed 使用一个 tensor 值临时替换一个操作的输出结果. 你可以提供 feed 数据作为run() 调用的参数.feed 只在调用它的方法内有效, 方法结束, feed 就会消失. 最常见的用例是将某些特殊的操作指定为"feed" 操作, 标记的方法是使用tf.placeholder()为这些操作创建占位符.

交互式使用:
考虑到如IPython这样的交互式 Python 环境的易用, 可以使用InteractiveSession 代替Session类, 使用 Tensor.eval()和 Operation.run() 方法代替 Session.run(). 这样可以避免使用一个变量来持有会话.
import tensorflow as tf
sess = tf. InteractiveSession ()
weights = tf.random_normal([ 100 , 10 ])
print weights1. eval () #非交互式模式下是没有这个方法的

编写TensorFlow code:
安装好TensorFlow后就可以在IDEA中创建py文件(需要指定python sdk):
import tensorflow as tf
state = tf.Variable( 0 ,name= 'counter' ) #Variable 用来定义变量,初始值0
one = tf.constant( 1 ) #constant 定义常量
new_value = tf.add(state,one) #add 执行加法
update = tf.assign(state,new_value) #将new_value赋值给state
with tf.Session() as sess:
sess.run(tf.initialize_all_variables()) #初始化所有变量,定义的变量需要执行此操作
for _ in range( 5 ):
sess.run(update)
print sess.run(state)

上面的代码定义了一个如下的计算图,同时其中变量的状态是循环变化的:*


TensorFlow激活函数( Activation Functions:
TensorFlow优化方法( Optimizers):
使用Tensorboard:
#代码中指定一些name scope:
with tf.name_scope( 'layer1' ):
#将graph写到某个路径下
writer = tf.train.SummaryWriter( "logs/" , sess.graph)
console中执行:
$ tensorboard --logdir='../TensorflowTest/logs'
Starting TensorBoard 16 on port 6006
(You can navigate to http://0.0.0.0:6006)
#打开给出的url即可,由于只写了graph,所以只能看到graph的图


 
 
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值