#!/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列