gpt4 book ai didi

python - 如何在 tensorflow 中置换转置?

转载 作者:IT老高 更新时间:2023-10-28 21:17:46 26 4
gpt4 key购买 nike

来自 docs :

Transposes a. Permutes the dimensions according to perm.

The returned tensor's dimension i will correspond to the input dimension perm[i]. If perm is not given, it is set to (n-1...0), where n is the rank of the input tensor. Hence by default, this operation performs a regular matrix transpose on 2-D input Tensors.

但我仍然有点不清楚我应该如何对输入张量进行切片。例如。也来自文档:

tf.transpose(x, perm=[0, 2, 1]) ==> [[[1  4]
[2 5]
[3 6]]

[[7 10]
[8 11]
[9 12]]]

为什么 perm=[0,2,1] 会产生一个 1x3x2 的张量?

经过反复试验:

twothreefour = np.array([ [[1,2,3,4], [5,6,7,8], [9,10,11,12]] , 
[[13,14,15,16], [17,18,19,20], [21,22,23,24]] ])
twothreefour

[出]:

array([[[ 1,  2,  3,  4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]],

[[13, 14, 15, 16],
[17, 18, 19, 20],
[21, 22, 23, 24]]])

如果我转置它:

fourthreetwo = tf.transpose(twothreefour) 
with tf.Session() as sess:
init = tf.initialize_all_variables()
sess.run(init)
print (fourthreetwo.eval())

我得到 4x3x2 到 2x3x4,这听起来合乎逻辑。

[出]:

[[[ 1 13]
[ 5 17]
[ 9 21]]

[[ 2 14]
[ 6 18]
[10 22]]

[[ 3 15]
[ 7 19]
[11 23]]

[[ 4 16]
[ 8 20]
[12 24]]]

但是当我使用 perm 参数输出时,我不确定我真正得到了什么:

twofourthree = tf.transpose(twothreefour, perm=[0,2,1]) 
with tf.Session() as sess:
init = tf.initialize_all_variables()
sess.run(init)
print (threetwofour.eval())

[出]:

[[[ 1  5  9]
[ 2 6 10]
[ 3 7 11]
[ 4 8 12]]

[[13 17 21]
[14 18 22]
[15 19 23]
[16 20 24]]]

为什么 perm=[0,2,1] 从 2x3x4 返回 2x4x3 矩阵?

perm=[1,0,2] 再试一次:

threetwofour = tf.transpose(twothreefour, perm=[1,0,2]) 
with tf.Session() as sess:
init = tf.initialize_all_variables()
sess.run(init)
print (threetwofour.eval())

[出]:

[[[ 1  2  3  4]
[13 14 15 16]]

[[ 5 6 7 8]
[17 18 19 20]]

[[ 9 10 11 12]
[21 22 23 24]]]

为什么 perm=[1,0,2] 从 2x3x4 返回 3x2x4?

这是否意味着 perm 参数正在使用我的 np.shape 并根据我的数组形状的元素转置张量?

即:

_size = (2, 4, 3, 5)
randarray = np.random.randint(5, size=_size)

shape_idx = {i:_s for i, _s in enumerate(_size)}

randarray_t_func = tf.transpose(randarray, perm=[3,0,2,1])
with tf.Session() as sess:
init = tf.initialize_all_variables()
sess.run(init)
tranposed_array = randarray_t_func.eval()
print (tranposed_array.shape)

print (tuple(shape_idx[_s] for _s in [3,0,2,1]))

[出]:

(5, 2, 3, 4)
(5, 2, 3, 4)

最佳答案

我认为 perm 正在改变维度。例如 perm=[0,2,1]dim_0 -> dim_0, dim_1 -> dim_2, dim_2 -> dim_1 的缩写。所以对于二维张量,perm=[1,0] 只是矩阵转置。这能回答你的问题吗?

关于python - 如何在 tensorflow 中置换转置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517533/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com