循环处理张量

2024-03-29 13:53:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个特征地图和一些坐标
我想做如下的事情
通过坐标从要素图中裁剪数据
然后做argmaxconcat(或者stack?)
如何在Tensorflow中执行此操作?在

# num_coor is Not fixed, but fixed is ok!
# it defined before run
num_coor = 4
feature_map = np.transpose(np.reshape(np.arange(100*100*3), (3, 100, 100)), [1, 2, 0])
x_coor = np.array([[0, 20, 40, 60],
                   [15, 35, 55, 75]])  # shape(?, num_coor)
y_coor = np.array([[0, 20, 40, 60],
                   [15, 35, 55, 75]])  # shape(?, num_coor)
crop = []

for batch in xrange(x_coor.shape[0]):
    temp1 = []
    for i in xrange(num_coor - 1):
        temp2 = []
        for j in xrange(num_coor - 1):
            x1 = x_coor[batch, j]
            y1 = y_coor[batch, i]
            x2 = x_coor[batch, j + 1]
            y2 = y_coor[batch, i + 1]

            # slice by coordinate and len(slice_map) is depth
            slice_map = [feature_map[x1:x2, y1:y2, c] for c in xrange(feature_map.shape[2])]
            resmax = [np.amax(slice_map[c]) for c in xrange(len(slice_map))]
            resmax = np.reshape(np.array(resmax), (1, 1, feature_map.shape[2]))
            temp2.append(resmax)
        temp1.append(np.vstack(temp2))
    temp_arr = np.concatenate(temp1, axis=1)
    crop.append(np.array(temp_arr))

crop = np.array(crop) # (2, 3, 3, 3)

x,y的四个坐标可以构成9个面元 我想在每个箱子和每个通道里做最大的池子 所以我可以得到池结果,在这个例子中,形状是(2, 3, 3, 3) # (2, h, w, c)

enter image description here

我想我可以用tf.while_loop来做这个
但我不知道如何访问外部张量并返回结果
我做了一个小测试,它似乎不能访问外部张量

^{pr2}$

Tags: incropmapforisnpbatchslice
1条回答
网友
1楼 · 发布于 2024-03-29 13:53:13

我想您可以在本例中使用一个正则for循环(注意lambda是如何访问外部张量的,在本例中是feature_map):

batch_feature_map_max_fn = lambda xy : tf.reduce_max(feature_map[xy[0]:xy[1], xy[2]:xy[3], -1])

crop = []
for j in range(num_coor-1):
    x1 = x_coor[:, j]
    x2 = x_coor[:, j+1]
    y1 = y_coor[:, j]
    y2 = y_coor[:, j+1]

    temp = tf.map_fn(fn, [x1,x2,y1,y2], dtype=tf.float32)

    crop.append(temp)

crop = tf.pack(crop, axis=1)

至于tf.while_loop,我相信您将能够访问在loop_vars参数中传递的所有张量。你只需返回额外的张量而不做任何更改。不过,我不确定tf.while_loop是否真的适合这种情况。在

相关问题 更多 >