tensorflow 通过(不同范围的 2d)切片列表更改/分配矩阵元素值

标签 tensorflow matrix slice

我有一个零矩阵(我们可以将其视为图片):

matrix = tf.zeros(name="matrix", shape=(4, 5), dtype=tf.int32)

和指示此矩阵上一些“框”(通过左上角和右下角顶点,可能重叠)的四分体张量:

(第一行,第一列,第二行,第二列)

此处,[first_row:second_row, first_column,second_column]矩阵 上形成一个框。

问题是:如何使用切片 [first_row] 将图片上的所有“盒装值”从 0 分配/更改为 1 :second_row, first_column,second_column] 或其他 tensorflow 函数?

更新:

输入:

matrix = tf.zeros(name="matrix", shape=(4, 5), dtype=tf.int32)

first_row = tf.constant([0,2])
first_column = tf.constant([2,1])
second_row = tf.constant([3,3])
second_column = tf.constant([3,3])

预期输出(通过框示例 (0,2,3,3)(2,1,3,3)):

array([[0, 0, 1, 1, 0],
       [0, 0, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0]])

最佳答案

这会有所帮助。但如果没有,您可以澄清您的问题。

import tensorflow as tf

tensor = tf.Variable(
    [[0, 0, 1, 1, 0],
     [0, 0, 1, 1, 0],
     [0, 1, 1, 1, 0],
     [0, 1, 1, 1, 0]])


with tf.Session() as sess :
  sess.run( tf.global_variables_initializer() )
  print(sess.run( tf.assign(tensor[0:1,2:3] , [[9]] )))

输出是这样的。

[[0 0 9 1 0]
 [0 0 1 1 0]
 [0 1 1 1 0]
 [0 1 1 1 0]]

如果你将最后一行更改为 print(sess.run( tf.assign(tensor[0:1,2:4] , [[9,9]] ))) 你得到

[[0 0 9 9 0]
 [0 0 1 1 0]
 [0 1 1 1 0]
 [0 1 1 1 0]]

当我无法确保分配的左侧在形状方面与右侧不匹配时,我会收到此错误。这应该对您有所帮助。

sliced l-value shape [1,2] does not match r-value shape [1,1]

例子 print(sess.run( tf.assign(tensor[0:2,2:4] , [[9,9],[9,9]] )))打印

[[0 0 9 9 0]
 [0 0 9 9 0]
 [0 1 1 1 0]
 [0 1 1 1 0]]

关于 tensorflow 通过(不同范围的 2d)切片列表更改/分配矩阵元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55570319/

相关文章:

scala - 使用这些集合中元素的增量阴影计算每个元素上的函数的最佳方法

php - 假数组切片操作符 : Make it shorter

python - 必须完全定义新变量的形状,而不是 (?, 128)

python - ssim 作为自动编码器中的自定义损失函数(keras 或/和tensorflow)

neural-network - tf.nn.conv2d 在 tensorflow 中做什么?

r - 将新行一一添加到矩阵

python - 没有注册 OpKernel 来支持具有这些属性的 Op 'Conv2D'

python-3.x - 填充 NxM 矩阵使得 A[i,j]=A[i-1,j] NAND A[i,j-1]

java - 从一个类到另一个类获取数组长度

python - 什么是 { :4} mean in this matrix printing solution in python?