张量流可以进行排序,例如冒泡排序甚至是一般排序吗?

时间:2017-12-25 14:26:39

标签: python tensorflow

我写了一个冒泡排序,但它不起作用。希望有人可以纠正。

def BubbleSort(张量):

def outer_loop(i, t):
    cond = lambda j, _: j > i
    loop = tf.while_loop(cond, inner_loop, loop_vars=[j, t])
    print('outer_loop', i+1, length-1)
    return i+1, loop[1]

def inner_loop(j, t):
    body = tf.cond(tf.greater(t[j-1], t[j]),
                lambda: tf.scatter_update(t, [j-1, j], [t[j], t[j-1]]),
                lambda: t)
    print('inner_loop', i, j-1)
    return j-1, body

length = tensor.get_shape()[-1].value
i = 0
j = length-1

cond = lambda i, _: i < length - 1
graph = tf.while_loop(cond, outer_loop, loop_vars=[i, tensor])
return graph

1 个答案:

答案 0 :(得分:0)

下面的冒泡排序代码在tensorflow上运行并启用了急切执行功能。应该也可以不急于执行:)

import tensorflow as tf
import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()

n1= tf.contrib.eager.Variable([1,3,7,5,2])

n1_len= n1.get_shape()[0]
print (n1_len)
for i in range(n1.get_shape()[0]):
    for j in range (n1.get_shape()[0]):
        if  tf.math.less(n1[i],n1[j]):
            temp=n1[i]
            tf.scatter_update(n1,i,n1[j])
            tf.scatter_update(n1,j,temp)
            print (n1)

输出:

<tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([3, 1, 7, 5, 2], dtype=int32)>
<tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([7, 1, 3, 5, 2], dtype=int32)>
<tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([1, 7, 3, 5, 2], dtype=int32)>
<tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([1, 3, 7, 5, 2], dtype=int32)>
<tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([1, 3, 5, 7, 2], dtype=int32)>
<tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([1, 2, 5, 7, 3], dtype=int32)>
<tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([1, 2, 3, 7, 5], dtype=int32)>
<tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([1, 2, 3, 5, 7], dtype=int32)>