tensorflow控制流之tf.case
tf.case
case(pred_fn_pairs,
default,
exclusive=False,
strict=False,
name='case')
控制语句还是非常好用的
Defined intensorflow/python/ops/control_flow_ops.py.
See the guide:Control Flow > Control Flow Operations
Create a case operation.
Thepred_fn_pairsparameter is a dict or list of pairs of size N.Each pair contains a boolean scalar tensor and a python callable thatcreates the tensors to be returned if the boolean evaluates to True.defaultis a callable generating a list of tensors. All the callablesinpred_fn_pairsas well asdefaultshould return the same numberand types of tensors.
If exclusive==True, all predicates are evaluated, and an exception isthrown if more than one of the predicates evaluates toTrue.Ifexclusive==False, execution stops are the first predicate whichevaluates to True, and the tensors generated by the corresponding functionare returned immediately. If none of the predicates evaluate to True, thisoperation returns the tensors generated bydefault.
tf.casesupports nested structures as implemented intensorflow.python.util.nest. All of the callables must return the same(possibly nested) value structure of lists, tuples, and/or named tuples.Singleton lists and tuples form the only exceptions to this: when returned bya callable, they are implicitly unpacked to single values. Thisbehavior is disabled by passingstrict=True.
If an unordered dictionary is used forpred_fn_pairs, the order of theconditional tests is not guaranteed. However, the order is guaranteed to bedeterministic, so that variables created in conditional branches are createdin fixed order across runs.
Example 1:
Pseudocode:
if(x
elsereturn23;
Expressions:
f1=lambda:tf.constant(17)
f2=lambda:tf.constant(23)
r=case([(tf.less(x,y),f1)],default=f2)
Example 2:
Pseudocode:
if(xz)raiseOpError("Only one predicate may evaluate true");
if(x
elseif(x>z)return23;
elsereturn-1;
Expressions:
deff1():returntf.constant(17)
deff2():returntf.constant(23)
deff3():returntf.constant(-1)
r=case({tf.less(x,y):f1,tf.greater(x,z):f2}, # case1, case2, case3, ...
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 toTrue.
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 bydefaultif none does.
Raises:
TypeError: Ifpred_fn_pairsis not a list/dictionary.
TypeError: Ifpred_fn_pairsis a list but does not contain 2-tuples.
TypeError: Iffns[i]is not callable for any i, ordefaultis not callable.
tensorflow tf.stack tf.unstack 实例
import tensorflow as tf
a = tf.constant([1,2,3])
b = tf.constant([4,5,6])
c = tf.stack([a,b],axis=1)
d = tf.unstack(c,axis=0)
e = tf.unstack(c,axis=1)
print(c.get_shape())
with tf.Session() as sess:
print(sess.run(c))
print(sess.run(d))
print(sess.run(e))
在安装了epel源的情况下,直接yum就可以安装python3.4
yum install python34 -y
python3 --version
没有自带pip3,从官网安装
wget --no-check-certificate https://bootstrap.pypa.io/get-pip.py
python3 get-pip.py
pip3 -V
tensorflow GPU 安装
http://www.linuxidc.com/Linux/2016-11/137561.htm
http://blog.csdn.net/zhaoyu106/article/details/52793183/
http://blog.csdn.net/liaodong2010/article/details/71482304
Deepin15.4 下 CUDA 配置方法
deepin15.4不仅漂亮而且运行流畅,吸引了大批linuxer,其中也不乏搞cuda的小伙伴。但是有不少童鞋在deepin15.4下配置cuda遇到了困难,所以抽空写个博文说一下我配置的方法。主要针对电脑是intel
核显,nvidia显卡,需要运行cuda,并且有双显卡热切换需求的小朋友。
先说一下我电脑的配置吧,大家的硬件环境不一样,我也没法一一测试。
CPUintel core i5 4210u
显卡nvidia gt840m
系统deepin 15.4 x64
安装nvidia-bumblebee,实现双显卡切换
对于笔记本用户来说,一直开着独显的话发热量会明显增大,并且耗电也会变快,所以需要安装bumblebee来切换显卡,平时只用核显就足够了,需要运行cuda或者玩游戏的话才开启独显。
安装cuda开发工具
cuda在linux下的开发工具基本上够用了,有基于eclipse 的nsight,有visual
profiler性能分析工具,还有pycuda库实现对python运算的加速。但是我以前在deepin上面尝试安装官方的.run包,均以失败告终,很容易把电脑搞崩溃。最近终于找到了从软件源直接安装cuda的方法。
安装nvidia-bumblebee
sudoapt updatesudoapt install bumblebee bumblebee-nvidia nvidia-smi
一行命令搞定nvidia驱动、bumblebee切换程序、和显卡状态监控程序。
不用管nouveau驱动,系统会自己屏蔽掉。
然后重启
sudoreboot
重启之后测试
nvidia-smi
和
optirun nvidia-smi
如果出现如下界面,说明驱动安装成功
安装cuda开发工具
首先安装配置g++,gcc
因为cuda版本原因,cuda8之前都只支持g++-4.8,gcc-4.8
所以gcc需要降级
sudoapt install g++-4.8gcc-4.8
然后更改软连接
cd/usr/binsudorm gcc g++sudoln-sg++-4.8g++sudoln-sgcc-4.8gcc
然后下载开发工具
sudo apt install nvidia-cuda-devnvidia-cuda-toolkitnvidia-nsightnvidia-visual-profiler
使用nsight的方法为:在终端下输入
optirun nsight
tf.while_loop()
tf.while_loop(cond, body, loop_vars, shape_invariants=None,
parallel_iterations=10, back_prop=True, swap_memory=False, name=None)
while_loop可以这么理解
loop_vars = [...]whilecond(*loop_vars): loop_vars = body(*loop_vars)
1
2
3
示例:
importtensorflowastfa = tf.get_variable("a", dtype=tf.int32, shape=[], initializer=tf.ones_initializer())b = tf.constant(2)f = tf.constant(6)# Definition of condition and bodydefcond(a, b, f):returna <3defbody(a, b, f):# do some stuff with a, ba = a +1returna, b, f# Loop, 返回的tensor while 循环后的 a,b,fa, b, f = tf.while_loop(cond, body, [a, b, f])withtf.Session()assess: tf.global_variables_initializer().run() res = sess.run([a, b, f]) print(res)