tensorflow随笔-条件循环控制(3)

这篇博客探讨了在TensorFlow中使用条件循环控制的方法,通过一个具体的例子展示了如何更新命名元组Pair的值,每次迭代j更新为j+k,k更新为j-k。文章还展示了循环过程中的中间结果,并强调形状不变量`tf.TensorShape([None, 2])`在保持矩阵形状为任意行、2列方面的重要性。" 78981539,692471,D3.js力导向图详解:d3.layout.force()解析,"['前端开发', '数据可视化', 'JavaScript', 'D3.js']
摘要由CSDN通过智能技术生成
#!/usr/bin/env python2
# -*- coding: utf-8 -*-


import tensorflow as tf
import collections
Pair = collections.namedtuple('Pair', 'j, k')
ijk_0 = (tf.constant(0), Pair(tf.constant(1), tf.constant(2)))
c = lambda i, p: i < 10
b = lambda i, p: (i + 1, Pair((p.j + p.k), (p.j - p.k)))
ijk_final = tf.while_loop(c, b, ijk_0)

sess=tf.Session()
with sess:
    print sess.run(ijk_final)
(10, Pair(j=32, k=64))

循环,以命名元组Pair的值为初值,每次循环将其j更新为j+k,k更新为j-k,并返回一个新的命名元组对象。

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])  
>>> p = Point(12, y=16) 
>>> p
Point(x=12, y=16)
>>> p.x + p.y
28
>>> p[0] + p[1]  
28
>>> x, y = p  
>>> x
12
>>> y
16

#!/usr/bin/env python2
# -*- coding: utf-8 -*-


import tensorflow as tf
i0 = tf.constant(0)
m0 = tf.ones([2, 2])
c = lambda i, m: i < 5
b = lambda i, m: [i+1, tf.concat([m, m], axis=0)]
ijk_final=tf.while_loop(
    c, b, loop_vars=[i0, m0],
    shape_invariants=[i0.get_shape(), tf.TensorShape([None, 2])])

sess=tf.Session()
with sess:
    print sess.run(ijk_final)

[5, array([[1., 1.],
[1., 1.],
[1., 1.],
…,
[1., 1.],
[1., 1.],
[1., 1.]], dtype=float32)]

#!/usr/bin/env python2
# -*- coding: utf-8 -*-


import tensorflow as tf
i0 = tf.constant(0)
m0 = tf.ones([2, 2])
c = lambda i, m: i < 5
b = lambda i, m: [i+1, tf.concat([m+1, m], axis=0)]
ijk_final=tf.while_loop(
    c, b, loop_vars=[i0, m0],
    shape_invariants=[i0.get_shape(), tf.TensorShape([None, 2])])

sess=tf.Session()
with sess:
    print sess.run(ijk_final)

[5, array([[6., 6.],
[6., 6.],
[5., 5.],
…,
[2., 2.],
[1., 1.],
[1., 1.]], dtype=float32)]
形状不变量tf.TensorShape([None, 2])控制了m的形状 为任意行,2列

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值