一、Tensors

TensorFlow所有的数据都称之为Tensor,即TensorFlow图计算过程中,节点之间是数据流转都是采用Tensor的形式进行,而且也只能采用Tensor形式进行。

Tensor可以是一个变量,可以是一个数组,也可以是多维数组等。

一般的,Tensor可以抽象为n-dimensional array or list。

Tensor有几个重要的属性:

Data types,标志该Tensor存储的数据类型,如tf.float32,tf.String等;

Rank,即tensor是几维的数组,scalar rank为0,vector rank为1,matrix rank为3,N-demensional tensor rank为N;

Shape,tensor的形状,scalar shape为[],vector shape为 [D0],matrix shape为 [D0,D1];

import tensorflow as tf

a = tf.zeros((2, 2))

print(a)

输出

Tensor("zeros:0", shape=(2, 2), dtype=float32)

二、Session

Session,会话是TensorFlow的运行上下文环境,TensorFlow的Operations和Compution Graph都必须运行在TensorFlow的Session中。

import tensorflow as tf

# Build a graph

a = tf.constant(5.0)

b = tf.constant(6.0)

c = a * b

# Launch a graph in a sesion

sess = tf.Session()

# Evaluate a tensor c

print(sess.run(c))

输出30.0

从上面可以看出,Session提供了run方法来执行tensor的计算,run方法有四个参数,如下

fetches 必选

feed_dict 可选

options 可选

run_metadata 可选

另外,由于Session提供的是运行环境,所以,是TensorFlow系统宝贵的资源,用完我们要及时释放,释放方式有如下两种:

第一种方式是,直接调用Session.close()方式显示关闭Session;

第二种方式是,采用代码块,当当前代码块执行完毕后,Session会自动被析构释放掉,如下:

with tf.Session() as sess:

result = sess.run(c)

print(result)

InteractiveSession

有一类session是交互式session,这类session能在运行过程中接收外部的输入。交互式的Session能更好的适用于这类场景。

结合Tensor.eval()和Operation.run()来取代Session.run()。这样的好处是避免在一个session中长时间使用一个变量,见下例所示:

# Enter an interactive TensorFlow Session.

import tensorflow as tf

sess = tf.InteractiveSession()

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

a = tf.constant([3.0, 3.0])

# Initialize 'x' using the run() method of its initializer op.

x.initializer.run()

# Add an op to subtract 'a' from 'x'.  Run it and print the result

sub = tf.sub(x, a)

print(sub.eval())

[-2. -1.]

# Close the sesion when we are done

sess.close()

三、Variables

变量是TensorFlow重要的概念,前面我们的实例更多的是使用tensorflow constant常量。Variables在使用前必须先初始化好。

tensorflow variables提供了tf.initialize_all_variables()快速初始化所有变量。

import tensorflow as tf

W = tf.Variable(tf.zeros((2, 2)), name="weights")

R = tf.Variable(tf.random_normal((2, 2)), name="random_weights")

with tf.Session() as sess:

sess.run(tf.initialize_all_variables())

print(sess.run(W))

print(sess.run(R))

输出

[[ 0.  0.]

[ 0.  0.]]

[[ 1.09000123  0.34866104]

[ 1.02729785  0.71264291]]

用一个变量赋值给另一个变量,如下:

import tensorflow as tf

weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35), name="weights")

w2 = tf.Variable(weights.initialized_value(), name="w2")

with tf.Session() as sess:

sess.run(tf.initialize_all_variables())

print(sess.run(weights))

print(sess.run(w2))

Saving and Restoring Variables

tf.train.Saver提供了Variable checkpoint转储功能和恢复功能,你可以将变量某一时刻的值持久化到磁盘,当需要用时再从磁盘恢复出来,如下:

import tensorflow as tf

v1 = tf.Variable(tf.zeros((2, 2)), name="weights")

v2 = tf.Variable(tf.random_normal((2, 2)), name="random_weights")

init_op = tf.initialize_all_variables()

saver = tf.train.Saver()

with tf.Session() as sess:

sess.run(init_op)

save_path = saver.save(sess, "/tmp/model.ckpt")

print("Model saved in file: %s" % save_path)

输出

Model saved in file: /tmp/model.ckpt

with tf.Session() as sess:

saver.restore(sess, "/tmp/model.ckpt")

更新变量的值

import tensorflow as tf

# state = 0

state = tf.Variable(0, name="counter")

# new_value = state + 1

new_value = tf.add(state, tf.constant(1))

# state = state + 1

update = tf.assign(state, new_value)

with tf.Session() as sess:

sess.run(tf.initialize_all_variables())

print(sess.run(state))

for _ in range(3):

sess.run(update)

print(sess.run(state))

输出

0

1

2

3

获取变量

import tensorflow as tf

in1 = tf.constant(3.0)

in2 = tf.constant(2.0)

in3 = tf.constant(5.0)

temp = tf.add(in2, in3)

mul = tf.mul(in1, temp)

with tf.Session() as sess:

result = sess.run([mul, temp])

print(result)

输出

[21.0, 7.0]

Variable Scope

变量Scope,类似变量的名字空间。variable_scope设置命名空间,get_variable获取命名空间,如下:

import tensorflow as tf

with tf.variable_scope("foo"):

with tf.variable_scope("bar"):

v = tf.get_variable("v", [1])

assert v.name == "foo/bar/v:0"

Reuse variable scope

重用变量命名空间,在RNN场景中会用到该功能,如下

import tensorflow as tf

with tf.variable_scope("foo"):

v = tf.get_variable("v", [1])

tf.get_variable_scope().reuse_variables()

v1 = tf.get_variable("v", [1])

assert v == v1

Placeholders and Feed Dictionaries

tensorflow的占位符,在程序运行过程中进行参数的赋值,非常使用,用于接受程序外部传入的值,如下:

import tensorflow as tf

in1 = tf.placeholder(tf.float32)

in2 = tf.placeholder(tf.float32)

out = tf.mul(in1, in2)

with tf.Session() as sess:

print(sess.run([out], feed_dict={in1:[7.], in2:[2.]}))

输出

[array([ 14.], dtype=float32)]

最后再提下,tensorflow提供了一个转换为tensor的方法,convert_to_tensor(),如下:

import numpy as np

import tensorflow as tf

a = np.zeros((3, 3))

ta = tf.convert_to_tensor(a)

with tf.Session as sess:

print(sess.run(ta))

参考资料

https://cs224d.stanford.edu/lectures/CS224d-Lecture7.pdf

https://www.tensorflow.org/versions/r0.10/get_started/basic_usage.html#basic-usage

TensorFlow入门教程相关推荐

  1. Tensorflow 入门教程

    Tensorflow 入门教程  http://tensornews.cn/ 深度学习发展史 特征工程 深度学习之激活函数 损失函数 反向传播算法 [上] 反向传播算法 [下] Tensorflow ...

  2. (转)tensorflow入门教程(二十六)人脸识别(上)

    https://blog.csdn.net/rookie_wei/article/details/81676177 1.概述 查看全文 http://www.taodudu.cc/news/show- ...

  3. TensorFlow入门教程(1)安装、基础、Tensorboard

    TensorFlow入门教程 本教程适合人群: - 会些python但不是特别精通 - 机器学习的初学者 本教程预计耗时: - 2-3小时 本教程预计效果: - 掌握TensorFlow的基础操作 - ...

  4. TensorFlow入门教程:1:安装和第一个例子程序

    TensorFlow™ 是Google开源的一个采用数据流图用于数值计算的开源库.截止到目前为止在github上已经获得超过6万个Star,已经成为深度学习和机器学习方面最为受欢迎的项目,炙手可热.这 ...

  5. tensorflow官方文档_开源分享:最好的TensorFlow入门教程

    如果一门技术的学习曲线过于陡峭,那么我们在入门时的场景往往是,一鼓作气,没入门,再而衰,三而竭.演绎一出从入门到放弃的败走麦城. 今天发现一个入门TensorFlow的宝藏,迫不及待的分享给大家.这个 ...

  6. 比官方更简洁的Tensorflow入门教程

    声明: 参考自Python TensorFlow Tutorial – Build a Neural Network,本文简化了文字部分 文中有很多到官方文档的链接,毕竟有些官方文档是中文的,而且写的 ...

  7. 极客兔兔 TensorFlow入门教程

    TensorFlow入门(一) - mnist手写数字识别(网络搭建) TensorFlow入门(二) - mnist手写数字识别(模型保存加载) TensorFlow入门(三) - mnist手写数 ...

  8. TensorFlow入门教程集合

    TensorFlow入门教程之0: BigPicture&极速入门 TensorFlow入门教程之1: 基本概念以及理解 TensorFlow入门教程之2: 安装和使用 TensorFlow入 ...

  9. tensorflow入门教程(三十四)疲劳检测之开眼闭眼识别

    # #作者:韦访 #博客:https://blog.csdn.net/rookie_wei #微信:1007895847 #添加微信的备注一下是CSDN的 #欢迎大家一起学习 # ------韦访 2 ...

  10. 世界最清楚tensorflow入门教程

    人工智能.机器学习和深度学习 在介绍TensorFlow(以下简称为TF)之前,我们首先了解一下相关背景. TF是一种机器学习框架,而机器学习经常和人工智能,深度学习联系在一起,那么三者到底是什么关系 ...

最新文章

  1. [IOS]UIWebView实现保存页面和读取服务器端json数据
  2. Xcode编译Undefined symbols for architecture xxx 错误总结
  3. 没文化连广告都看不懂—“网易密码信破解”【续】
  4. Kettle使用_14 文件操作复制移动删除结合JS
  5. C++基础知识点整理
  6. Linux Kernel ‘CLONE_NEWUSER|CLONE_FS’本地权限提升漏洞
  7. kaike的FLAGs
  8. ubuntu linux 系统搭建我的世界基岩版 私服我的世界服务器
  9. 平稳时间序列的相关概念
  10. [读史思考]为何此大神可以同时进入文庙和武庙?
  11. 迭代期望和方差(iterated expectation,variance)
  12. 概率论与数理统计知识框架梳理
  13. carbon安装win7 thinkpad x1_ThinkPad X1 carbon笔记本Win7重装系统步骤详细教程。 重装系统...
  14. 高级防火墙规则-Direct Rules
  15. 联想拯救者R7000_2020款黑屏解决方案
  16. 持续集成与持续部署(五)01-TravisCI——使用简介-Travis CI 只支持 Github,提供的是持续集成服务 配置项目的.travis.yml文件
  17. Java 八种排序算法比较实践
  18. oracle gbk ebcdic,文件编码 ANSI、GBK、GB2312、MS936、MS932、SJIS、Windows-31 、EUC-JP 、EBCDIC 等等之间的区别与联系...
  19. Oracle 存储过程中自定义异常
  20. .value和.innerHTML

热门文章

  1. Android Region代码分析
  2. php private方法,PHP-private私有访问的操作方法
  3. c语言会出现fullgc,以上述代码为基础,在发生过一次FullGC后,上述代码在He
  4. dedecms php5.4 无法退出后台,解决更换PHP5.4以上版本后Dedecms后台登录空白问题的方法...
  5. 与c交互_SV DPI-C接口学习心得
  6. java 互斥量_什么是Java中的互斥和信号量?主要区别是什么?
  7. nginx增加php支持,Nginx启用php支持
  8. 赠书:京东当当新书榜TOP1的“算法小抄”!
  9. 2020 蚂蚁面试指南!
  10. IntelliJ IDEA 2019.3发布,饱受性能诟病的2019.2版本终于成为过去式