Coding Skill目录下的所有Tutorials、Notes博客都会不定期迭代更新
文章目录
1. What Is Tensorflow
- Official Chinese Tutorials
- Awesome
- Mofan Tutorials
- Github Tutorials
- Tensorflow Project Template
- Book
- 《21个项目玩转深度学习———基于TensorFlow的实践详解》 Code
- Tensorflow 实战Google深度学习框架
- tensorflow-internals
2. 基本使用
使用 TensorFlow, 你必须明白 TensorFlow:
- 使用图 (graph) 来表示计算任务.
- 在被称之为 会话 (Session) 的上下文 (context) 中执行图.
- 使用 tensor 表示数据.
- 通过 变量 (Variable) 维护状态.
- 使用 feed 和 fetch 可以为任意的操作(arbitrary operation) 赋值或者从其中获取数据.
Reference:详见TensorFlow实战Google深度学习框架一书
TensorFlow:Tensor表示数据结构(多维数组),Flow中文译为“流“,其代表计算模型,表达了张量(Tensor)之间通过计算相互转化的过程。
2.1 Tensorflow 计算模型 —— 计算图
计算图的概念
TensorFlow是一个通过计算图的形式来表述计算的编程系统,TensorFlow中每一个计算都是计算图中的一个节点,节点之间的边描述了计算之间的依赖关系。
计算图的使用
- 计算图使用
- 第一步:定义计算图中所有的计算
所有定义的变量和计算都会自动转化为计算图上的节点 - 第二步:执行计算
- 第一步:定义计算图中所有的计算
- 多个计算图
通过tf.Graph可以定义多个计算图,多个计算图之间的张量和运算都不会共享 - 指定计算单元
通过tf.Graph.device来指定计算的设备,GPU或者CPU
2.2 Tensorflow 数据模型 —— Tensor
张量的概念
张量在Tensorflow中并不是数组的形式,它只是对Tensorflow中运算结果的引用。在张量中并没有真正保存数字,它保存的是如何得到这些数字的计算过程。一个张量类型中有三个属性:名字(name)、维度(shape)、类型(type)。变量Varieable是tensorflow计算图中的节点,但是张量Tensor不是节点
下面这段内容很重要
张量的使用
张量的两个作用:
1.对中间计算结果的引用
2.计算图构建完成之后,用来获取计算结果
2.3 Tensorflow 运行模型 —— Session
前面的两节介绍了 TensorFlow 是如何组织数据(Tensor)和运算(Graph)的,本节介绍使用TensorFlow中的会话(Session)来执行定义好的运算。
- session需要用完释放
- session需要手动指定为默认会话
- InteractiveSession
在交互环境下直接构建默认session
2.4 Tensorflow搭建神经网络的简易流程
- 定义所有网络中的变量和计算,输入变量用placeholder
- 加载数据
- 构建Train逻辑,分epoch、分batch输送数据去网络,用session.run(),参数通过feed_dict构建
3. 模型保存、重载
遇到问题:tensorflow restore之后变成了CPU计算,目前尚不知如何解决
3.5. 日志模块
https://blog.csdn.net/vagrantabc2017/article/details/77507168
https://blog.csdn.net/lfs666666/article/details/85376941
https://www.cnblogs.com/wenwei-blog/p/7196658.html
https://www.cnblogs.com/CJOKER/p/8295272.html
tf.logging.info('conv_vae using cpu.')
4. Tensorboard可视化
tf.summary()
TENSORFLOW变量作用域(VARIABLE SCOPE)
https://www.cnblogs.com/MY0213/p/9208503.html
# 本地
tensorboard --logdir logs/
在浏览器中输入以下链接
http://xufengdemacbook-pro.local:6006
# 远程
在colab上执行,在本地打开tensorboard查看进度
'tensorboard --logdir {} --host 0.0.0.0 --port 6006 &'.format('logdir')
'./ngrok http 6006 &'
curl -s http://localhost:4040/api/tunnels | python3 -c \
"import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])"
在本地浏览器中输入https://15f94605.ngrok.io,进行查看
5. TFRecord
统一数据格式,将每个不同格式的数据集转换成tfrecord格式,统一管理。
https://www.cnblogs.com/upright/p/6136265.html
http://www.cnblogs.com/xinghun85/p/9119858.html
6. 数据读取框架
详见TensorFlow实战Google深度学习框架
多线程队列读取数据、图像处理
tf.train.Coordinator
https://blog.csdn.net/weixin_42052460/article/details/80714539
https://blog.csdn.net/kk123k/article/details/86772678
tf.FIFOQueue队列
https://blog.csdn.net/akadiao/article/details/78552037
7. 计算加速
GPU
多GPU
分布式
8. Eager
Simple tutorials for building neural networks with TensorFlow Eager mode.
9. Estimator
10. Tensorflow目录结构
Tensorflow源码解析1 – 内核架构和源码结构
Tensorflow[目录结构]
带你深入AI(6)- 详解bazel
TF.Learn
TF.Contrib
TF-Slim:
TF-Slim is a lightweight library for defining, training and evaluating complex models in TensorFlow. Components of tf-slim can be freely mixed with native tensorflow, as well as other frameworks, such as tf.contrib.learn.
11. Addition
tf.variable_scope
应该是tensorboard的summary有关
tf.get_variable()
https://www.cnblogs.com/MY0213/p/9208503.html
tf.assign
https://www.jianshu.com/p/fc5f0f971b14
tensorflow设置gpu及gpu显存使用
https://blog.csdn.net/m0_37987687/article/details/80240998
Chapter1
对Mnist进行Softmax线性回归
激活函数:softmax
y = tf.nn.softmax(tf.matmul(x, W) + b)
损失函数:交叉熵
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y)))
优化函数:随机梯度下降
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
Tensorflow高阶封装
Tensorflow.Contrib.Slim
Slim Github repo:Readme可以当tutorial来读
tensorflow中slim手册
tensorflow中slim模块api介绍
TensorFlow-Slim API 官方教程 1.12
TensorFlow - TF-Slim 使用总览
TFLearn
Tflearn:有简介、有教程
Tensorflow.contrib.learn:没有介绍
doc:可以看看Getting Start和Tutorials
TensorFlow-4: tf.contrib.learn 快速入门
Keras
TensorLayer
Jupyter notebook
xufengdembp:notebooks xufeng$ jupyter notebook
C++部署
C++如何使用Tensorflow
tensorflow C++ 环境搭建及实战
tensorflow c/c++库使用方法
如何用C++实现自己的Tensorflow
安装 C 版 TensorFlow
tensorflow C++接口
Tensorflow c++ 使用指南
tensorflow C++服务开发指南
C++ API
tensorflow c++接口,python训练模型,c++调用
C++ solution for testing the VGG_face deep model
Neural Network TensorFlow C API
Tensorflow源码解析1 – 内核架构和源码结构
Tensorflow Python 中文文档
Tensorflow 中文API
搞算法(图像识别,深度学习)必须要懂C/C++吗?
C++入门书
C++ 数字图像处理
深度学习C部署
如何实现在服务器端部署深度学习模型?实现(桌面)客户端与(远程服务器端)模型实现交互?
如何学习C++图像处理?
Resources
tf.cast()数据类型转换
https://blog.csdn.net/abc13526222160/article/details/86299106
tf.assign(A, new_number): 这个函数的功能主要是把A的值变为new_number
https://blog.csdn.net/uestc_c2_403/article/details/72235310
tf.add_to_collection,tf.get_collection和tf.add_n的用法
https://blog.csdn.net/uestc_c2_403/article/details/72415791
https://blog.csdn.net/nini_coded/article/details/80528466
tf.add_n函数的用法
https://blog.csdn.net/uestc_c2_403/article/details/72808839
tf.reduce_mean()
https://blog.csdn.net/he_min/article/details/78694383
https://blog.csdn.net/dcrmg/article/details/79797826
tensorflow tf.Variable()和tf.get_variable()
https://blog.csdn.net/MrR1ght/article/details/81228087
梯度修剪apply_gradients和compute_gradients
https://blog.csdn.net/NockinOnHeavensDoor/article/details/80632677
tf.reset_default_graph函数用于清除默认图形堆栈并重置全局默认图形。
注意:默认图形是当前线程的一个属性。该tf.reset_default_graph函数只适用于当前线程。当一个tf.Session或者tf.InteractiveSession激活时调用这个函数会导致未定义的行为。调用此函数后使用任何以前创建的tf.Operation或tf.Tensor对象将导致未定义的行为。
当前环境的作用域可以通过函数tf.get_variable_scope()获取,并且reuse标志可以通过调用reuse_variables()设置为True,
tf.train.batch和tf.train.shuffle_batch的理解
https://blog.csdn.net/ying86615791/article/details/73864381
tf.gradients 与 tf.stop_gradient() 与 高阶导数
https://blog.csdn.net/u012436149/article/details/53905797
tf.gradients()简单实用教程
https://blog.csdn.net/hustqb/article/details/80260002
tf.nn.l2_loss()的用法
https://blog.csdn.net/yangfengling1023/article/details/82910536
https://blog.csdn.net/m0_37561765/article/details/79645026
tf.get_variable & tf.Variable
tf.Variable是一个Variable类
通过变量维持图graph的状态,以便在sess.run()中执行;可以用Variable类创建一个实例在图中增加变量;
tf.get_variable
获取一个已经存在的变量或者创建一个新的变量
两者的区别
tf.get_variable的参数列表为tf.get_variable(name, shape=None, initializer=None, dtype=tf.float32, trainable=True, collections=None),如果已存在参数定义相同的变量,就返回已存在的变量,否则创建由参数定义的新变量。
所以tf.get_variable创建变量时,会进行变量检查,当设置为共享变量时(通过scope.reuse_variables()或tf.get_variable_scope().reuse_variables()),检查到第二个拥有相同名字的变量,就返回已创建的相同的变量;如果没有设置共享变量,则会报[ValueError: Variable varx alreadly exists, disallowed.]的错误。
而tf.Variable()创建变量时,name属性值允许重复,检查到相同名字的变量时,由自动别名机制创建不同的变量。
Tensorflow——tf.Variable()、tf.get_variable()和tf.placeholder()
tensorflow tf.Variable()和tf.get_variable()详解
tf.global_variables()
tf.initialize_all_variables()
tf.pad
tf.pad() 就是扩充维度
>>> import tensorflow as tf
>>> t=tf.constant([[[1,2,3], [2,3,4],[2,1,4]],
... [[1,2,3], [2,3,4],[2,1,4]],
... [[1,2,3], [2,3,4],[2,1,4]]])
>>>
>>> t
<tf.Tensor 'Const_2:0' shape=(3, 3, 3) dtype=int32>
>>>
>>> print(t.get_shape)
<bound method Tensor.get_shape of <tf.Tensor 'Const_2:0' shape=(3, 3, 3) dtype=int32>>
>>>
>>> t2=tf.constant([[1,2,3]])
>>> t2
<tf.Tensor 'Const_3:0' shape=(1, 3) dtype=int32>
>>> a=tf.pad(t,[[1,1], [2,2],[1,1]])
>>> c=tf.pad(t2,[[1,1],[2,2]])
>>> a
<tf.Tensor 'Pad:0' shape=(5, 7, 5) dtype=int32>
>>> c
<tf.Tensor 'Pad_1:0' shape=(3, 7) dtype=int32>
>>> sess = tf.Session()
2019-05-14 17:27:23.674522: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
>>> a_, c_ = sess.run([a,c])
>>> a_
array([[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 2, 3, 0],
[0, 2, 3, 4, 0],
[0, 2, 1, 4, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 2, 3, 0],
[0, 2, 3, 4, 0],
[0, 2, 1, 4, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 2, 3, 0],
[0, 2, 3, 4, 0],
[0, 2, 1, 4, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]], dtype=int32)
>>> t.shape
TensorShape([Dimension(3), Dimension(3), Dimension(3)])
>>> a_.shape
(5, 7, 5)
>>> c_
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 2, 3, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], dtype=int32)
>>> t2.shape
TensorShape([Dimension(1), Dimension(3)])
>>> c_.shape
(3, 7)
https://blog.csdn.net/qwe2508/article/details/79725701
tf.shape 和 tf.less
tf.shape返回张量的形状
tf.less返回两个张量各元素比较(x<y)得到的真假值组成的张量
import tensorflow as tf
A=[[1,2,3]]
t = tf.shape(A)
i=[3,2]
r = tf.less(i, t)
with tf.Session() as sess:
print(sess.run(t))
print(sess.run(r))
结果:
[1 3]
[False True]
import tensorflow as tf
A=[[1,2,3],
[4,5,6]]
t = tf.shape(A)
i=[[1,2,3],
[1,2,3]]
r = tf.less(i, A)
with tf.Session() as sess:
print(sess.run(t))
print(sess.run(r))
结果:
[2 3]
[[False False False]
[ True True True]]
tf.tile
复制纬度上的值
tf.tile(
input, #输入
multiples, #某一维度上复制的次数
name=None
)
import tensorflow as tf
a = tf.tile([1,2,3],[2])
b = tf.tile([[1,2],
[3,4],
[5,6]],[2,3])
with tf.Session() as sess:
print(sess.run(a))
print(sess.run(b))
Result:
tf.equal
tensorflow 中tf.equal()用法:
equal(x, y, name=None)
equal,相等的意思。顾名思义,就是判断,x, y 是不是相等,它的判断方法不是整体判断,
而是逐个元素进行判断,如果相等就是True,不相等,就是False。
由于是逐个元素判断,所以x,y 的维度要一致。
看个例子:
import tensorflow as tf
a = [[1,2,3],[4,5,6]]
b = [[1,0,3],[1,5,1]]
with tf.Session() as sess:
print(sess.run(tf.equal(a,b)))
结果:
[[ True False True]
[False True False]]
get_shape()
tf.transpose()
https://blog.csdn.net/uestc_c2_403/article/details/73350498
tf.transpose(input, [dimension_1, dimenaion_2,…,dimension_n]):这个函数主要适用于交换输入张量的不同维度用的,如果输入张量是二维,就相当是转置。dimension_n是整数,如果张量是三维,就是用0,1,2来表示。这个列表里的每个数对应相应的维度。如果是[2,1,0],就把输入张量的第三维度和第一维度交换。
import tensorflow as tf;
import numpy as np;
A = np.array([[1,2,3],[4,5,6]])
x = tf.transpose(A, [1,0])
B = np.array([[[1,2,3],[4,5,6]]])
y = tf.transpose(B, [2,1,0])
with tf.Session() as sess:
print A[1,0]
print sess.run(x[0,1])
print B[0,1,2]
print sess.run(y[2,1,0])
输出:
4
4
6
6
tf.where
where(condition, x=None, y=None, name=None)
condition, x, y 相同维度,condition是bool型值,True/False
1,where(condition)的用法
condition是bool型值,True/False
返回值,是condition中元素为True对应的索引
看个例子:
import tensorflow as tf
a = [[1,2,3],[4,5,6]]
b = [[1,0,3],[1,5,1]]
condition1 = [[True,False,False],
[False,True,True]]
condition2 = [[True,False,False],
[False,True,False]]
with tf.Session() as sess:
print(sess.run(tf.where(condition1)))
print(sess.run(tf.where(condition2)))
结果1:
[[0 0]
[1 1]
[1 2]]
结果2:
[[0 0]
[1 1]]
2, where(condition, x=None, y=None, name=None)的用法
condition, x, y 相同维度,condition是bool型值,True/False
返回值是对应元素,condition中元素为True的元素替换为x中的元素,为False的元素替换为y中对应元素
x只负责对应替换True的元素,y只负责对应替换False的元素,x,y各有分工
由于是替换,返回值的维度,和condition,x ,y都是相等的。
看个例子:
import tensorflow as tf
x = [[1,2,3],[4,5,6]]
y = [[7,8,9],[10,11,12]]
condition3 = [[True,False,False],
[False,True,True]]
condition4 = [[True,False,False],
[True,True,False]]
with tf.Session() as sess:
print(sess.run(tf.where(condition3,x,y)))
print(sess.run(tf.where(condition4,x,y)))
结果:
1, [[ 1 8 9]
[10 5 6]]
2, [[ 1 8 9]
[ 4 5 12]]
tf.case
tf.case()相当于switch
参数:
tf.case(
pred_fn_pairs,
default=None,
exclusive=False,
strict=False,
name='case'
)
import tensorflow as tf
def f1():
return tf.constant(17)
def f2():
return tf.constant(23)
def f3():
return tf.constant(-1)
x = 2
y = 3
r = tf.case({tf.less(x, y): f1, tf.greater(x, y): f2},
default=f3, exclusive=True)
sess = tf.Session()
print(sess.run(r))#17
https://blog.csdn.net/fyq201749/article/details/82777384
Example 1: Pseudocode:
if (x < y) return 17;
else return 23;
Expressions:
f1 = lambda: tf.constant(17)
f2 = lambda: tf.constant(23)
r = case([(tf.less(x, y), f1)], default=f2)
Example 2: Pseudocode:
if (x < y && x > z) raise OpError("Only one predicate may evaluate true");
if (x < y) return 17;
else if (x > z) return 23;
else return -1;
Expressions:
def f1(): return tf.constant(17)
def f2(): return tf.constant(23)
def f3(): return tf.constant(-1)
r = case({tf.less(x, y): f1, tf.greater(x, z): f2},
default=f3, exclusive=True)
Args:
- pred_fn_pairs: Dict or list of pairs of a boolean scalar tensor and a callable which returns a list of tensors.
- default: A callable that returns a list of tensors.
- exclusive: True iff at most one predicate is allowed to evaluate to True.
- strict: A boolean that enables/disables ‘strict’ mode; see above.
- name: A name for this operation (optional).
Returns:
The tensors returned by the first pair whose predicate evaluated to True, or those returned by default if none does.
Raises:
- TypeError: If pred_fn_pairs is not a list/dictionary.
- TypeError: If pred_fn_pairs is a list but does not contain 2-tuples.
- TypeError: If fns[i] is not callable for any i, or default is not callable.
tf.stack
也就相当于Tensor拼接
https://www.jianshu.com/p/25706575f8d4
tf.while_loop
https://blog.csdn.net/weixin_38314865/article/details/83305498
https://blog.csdn.net/u011509971/article/details/78805727
tf.TensorArray
tf.map_fn