gpt4 book ai didi

python - Tensorflow split 或 unstack 以处理交错值

转载 作者:行者123 更新时间:2023-12-01 09:29:58 27 4
gpt4 key购买 nike

假设我有一个形状为 [20,] 的 Tensorflow 张量 l,这些 10 个坐标打包为 [x1,y1,x2,y2,...] 。我需要访问 [x1,x2,...][y1,y2,...] 来修改它们的值(例如 、旋转、缩放、平移),然后重新打包为 [x1',y1',x1',y2',...]

我可以reshapetf.reshape(l, (10, 2)),但随后我不确定是否使用 splitunstack以及论点应该是什么。什么时候应该使用 split 而不是 unstack?那么修改后的值应该如何重新打包以使其保持原始格式?

最佳答案

这是一种可以通过 tensorflow 的急切执行模式轻松验证的东西:

import numpy as np
import tensorflow as tf

tf.enable_eager_execution()

l = np.arange(20)
y = tf.reshape(l, [10, 2])
a = tf.split(y, num_or_size_splits=2, axis=1)
b = tf.unstack(y, axis=1)

print('reshaped:', y, sep='\n', end='\n\n')

for operation, c in zip(('split', 'unstack'), (a, b)):
print('%s:' % operation, c, sep='\n', end='\n\n')
reshaped:
tf.Tensor(
[[ 0 1]
[ 2 3]
...
[16 17]
[18 19]], shape=(10, 2), dtype=int64)

split:
[<tf.Tensor: id=5, shape=(10, 1), dtype=int64, numpy=
array([[ 0],
[ 2],
...
[16],
[18]])>,
<tf.Tensor: id=6, shape=(10, 1), dtype=int64, numpy=
array([[ 1],
[ 3],
...
[17],
[19]])>]

unstack:
[<tf.Tensor: id=7, shape=(10,), dtype=int64, numpy=array([ 0, 2, ... 16, 18])>,
<tf.Tensor: id=8, shape=(10,), dtype=int64, numpy=array([ 1, 3, ... 17, 19])>]

因此,使用这些参数,它们几乎是相同的;除了:

  • tf.split 始终会将张量沿着 axis 分割为 num_or_size_splits 个分割,这可能与数字不同维度为 shape[axis],因此需要保留原始等级,输出形状为 [10, n/num_or_size_splits] = [10, 2/2] = [10, 1] 的张量.

    可以通过连接a中的所有拆分部分来执行重新打包:

    c=tf.concat(a, axis=1)
    print(c)
    array([[ 0, 1],
    [ 2, 3],
    ...
    [16, 17],
    [18, 19]])>
  • tf.unstack 会将张量沿 axis 拆分为精确的维度数 shape[axis],并且可以因此,明确地将等级降低 1,从而得到形状为 [10] 的张量。

    可以通过将所有拆分部分堆叠在b中来执行重新打包:

    c=tf.stack(b, axis=1)
    print(c)
    array([[ 0, 1],
    [ 2, 3],
    ...
    [16, 17],
    [18, 19]])>

关于python - Tensorflow split 或 unstack 以处理交错值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50051685/

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