python - 修改张量

标签 python machine-learning tensorflow

假设我有一个这样的张量

[
    [ 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,则交换该行的第一个和第二个元素。结果张量将是

[
    [ 6 -2 -2 -2 -1 -2  -3 -3 -6 -6]
    [ -6 1 -7 -7 -7 -7  -7 -6 -6 -6] #elements swapped
    [ 5 -3 -3 -4 -4 -4  -4 -3 -3 -3]
 ]

我正在使用tensorflow模块在python中工作。请帮忙。

最佳答案

解决此类问题的一般方法是使用 tf.map_fn()通过对每一行应用函数来创建具有适当值的新张量。让我们从如何表达单行的条件开始:

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

现在我们有一个条件,我们可以使用 tf.cond()构建一个条件表达式,如果条件为真,则交换前两个元素:

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)

print sess.run(maybe_swapped, feed_dict={row: [6, -2, -2, -2, -1, -2, -3, -3, -6, -6]}) 
print sess.run(maybe_swapped, feed_dict={row: [1, -6, -7, -7, -7, -7, -7, -6, -6, -6]})
print sess.run(maybe_swapped, feed_dict={row: [5, -3, -3, -4, -4, -4, -4, -3, -3, -3]})

# 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]

最后,我们通过将 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]]

关于python - 修改张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44950998/

相关文章:

image-processing - 大规模图像分类器

python - 将 python float 写入文件时抑制科学记数法

python - twitter api 不工作简单命令

matlab - 根据不同的窗口宽度(非对称窗口宽度)将局部最大值附近的值分配给局部最大值的值

matlab - libSVM 输出 "Line search fails in two-class probability estimates"

python - Tensorflow:多个损失函数与多个训练操作

javascript - 我如何在django中显示以blob形式存储在mysql数据库中的pdf?

python - 如何一次向现有数据框添加多列?

python - TensorFlow - tf.data.Dataset 读取大型 HDF5 文件

python - 使用分布式策略在 Colab TPU 上训练模型