python拆堆和堆叠的操作_python – Tensorflow:堆叠张量的所有行对

使用tf.meshgrid()和一些重塑的解决方案:

import tensorflow as tf

import numpy as np

t = tf.placeholder(tf.int32, [None, 2])

num_rows, size_row = tf.shape(t)[0], tf.shape(t)[1] # actual dynamic dimensions

# Getting pair indices using tf.meshgrid:

idx_range = tf.range(num_rows)

pair_indices = tf.stack(tf.meshgrid(*[idx_range, idx_range]))

pair_indices = tf.transpose(pair_indices, perm=[1, 2, 0])

# Finally gathering the rows accordingly:

res = tf.reshape(tf.gather(t, pair_indices), (-1, size_row * 2))

with tf.Session() as sess:

print(sess.run(res, feed_dict={t: np.array([[1,2], [3,4], [5,6]])}))

# [[1 2 1 2]

# [3 4 1 2]

# [5 6 1 2]

# [1 2 3 4]

# [3 4 3 4]

# [5 6 3 4]

# [1 2 5 6]

# [3 4 5 6]

# [5 6 5 6]]

使用笛卡尔积的解决方案:

import tensorflow as tf

import numpy as np

t = tf.placeholder(tf.int32, [None, 2])

num_rows, size_row = tf.shape(t)[0], tf.shape(t)[1] # actual dynamic dimensions

# Getting pair indices by computing the indices cartesian product:

row_idx = tf.range(num_rows)

row_idx_a = tf.expand_dims(tf.tile(tf.expand_dims(row_idx, 1), [1, num_rows]), 2)

row_idx_b = tf.expand_dims(tf.tile(tf.expand_dims(row_idx, 0), [num_rows, 1]), 2)

pair_indices = tf.concat([row_idx_a, row_idx_b], axis=2)

# Finally gathering the rows accordingly:

res = tf.reshape(tf.gather(t, pair_indices), (-1, size_row * 2))

with tf.Session() as sess:

print(sess.run(res, feed_dict={t: np.array([[1,2], [3,4], [5,6]])}))

# [[1 2 1 2]

# [1 2 3 4]

# [1 2 5 6]

# [3 4 1 2]

# [3 4 3 4]

# [3 4 5 6]

# [5 6 1 2]

# [5 6 3 4]

# [5 6 5 6]]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值