2024-04-18 23:43:37 发布
网友
假设我有这样一个张量
[ [ 6 -2 -2 -2 -1 -2 -3 -3 -6 -6] [ 1 -6 -7 -7 -7 -7 -7 -6 -6 -6] [ 5 -3 -3 -4 -4 -4 -4 -3 -3 -3] ]
我必须对每一行执行以下操作。 如果第一个元素是行中最大的(值)元素,但其值小于4,则交换该行的第一个和第二个元素。得到的张量将是
我使用tensorflow模块在python中工作。请帮忙。在
解决此类问题的一般方法是使用^{}通过对每一行应用一个函数来创建一个具有适当值的新张量。让我们从如何表示单行的条件开始:
row = tf.placeholder(tf.int32, shape=[10]) condition = tf.logical_and( tf.equal(row[0], tf.reduce_max(row)), tf.less(row[0], 4)) sess = tf.Session() print sess.run(condition, feed_dict={row: [6, -2, -2, -2, -1, -2, -3, -3, -6, -6]}) print sess.run(condition, feed_dict={row: [1, -6, -7, -7, -7, -7, -7, -6, -6, -6]}) print sess.run(condition, feed_dict={row: [5, -3, -3, -4, -4, -4, -4, -3, -3, -3]}) # Prints the following: # False # True # False
现在我们有了一个条件,我们可以使用^{}构建一个条件表达式,如果条件为真,则交换前两个元素:
最后,我们将maybe_swapped的计算打包到一个函数中,并将其传递给tf.map_fn():
maybe_swapped
tf.map_fn()
matrix = tf.constant([ [6, -2, -2, -2, -1, -2, -3, -3, -6, -6], [1, -6, -7, -7, -7, -7, -7, -6, -6, -6], [5, -3, -3, -4, -4, -4, -4, -3, -3, -3], ]) def row_function(row): condition = tf.logical_and( tf.equal(row[0], tf.reduce_max(row)), tf.less(row[0], 4)) def swap_first_two(x): swapped_first_two = tf.stack([x[1], x[0]]) rest = x[2:] return tf.concat([swapped_first_two, rest], 0) maybe_swapped = tf.cond(condition, lambda: swap_first_two(row), lambda: row) return maybe_swapped result = tf.map_fn(row_function, matrix) print sess.run(result) # Prints the following: # [[ 6 -2 -2 -2 -1 -2 -3 -3 -6 -6] # [-6 1 -7 -7 -7 -7 -7 -6 -6 -6] # [ 5 -3 -3 -4 -4 -4 -4 -3 -3 -3]]
解决此类问题的一般方法是使用^{} 通过对每一行应用一个函数来创建一个具有适当值的新张量。让我们从如何表示单行的条件开始:
现在我们有了一个条件,我们可以使用^{} 构建一个条件表达式,如果条件为真,则交换前两个元素:
^{pr2}$最后,我们将
maybe_swapped
的计算打包到一个函数中,并将其传递给tf.map_fn()
:相关问题 更多 >
编程相关推荐