假设我有一个带有形状[20,]的Tensorflow张量l
,这些是10个坐标打包为[x1,y1,x2,y2,...]
。我需要访问[x1,x2,...]
和[y1,y2,...]
来修改其值(例如,旋转,缩放,移位),然后重新打包为[x1',y1',x1',y2',...]
。
我可以reshape,tf.reshape(l, (10, 2))
,但后来我不确定是使用split还是unstack以及参数应该是什么。什么时候应该使用split而不是unstack?那么如何重新打包修改后的值,使它们采用原始格式?
答案 0 :(得分:1)
这是一种可以通过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]])>