19

嗨,我是张量流的新手。我想在 tensorflow 中实现以下 python 代码。

import numpy as np
a = np.array([1,2,3,4,5,6,7,9,0])
print(a) ## [1 2 3 4 5 6 7 9 0]
print(a.shape) ## (9,)
b = a[:, np.newaxis] ### want to write this in tensorflow.
print(b.shape) ## (9,1)
4

5 回答 5

19

相应的命令是tf.newaxis(或None,如 numpy)。它在 tensorflow 的文档中没有自己的条目,但在tf.stride_slice.

x = tf.ones((10,10,10))
y = x[:, tf.newaxis] # or y = x [:, None]
print(y.shape)
# prints (10, 1, 10, 10)

使用tf.expand_dims也很好,但如上面的链接所述,

这些界面更加友好,强烈推荐。

于 2017-06-27T18:23:44.697 回答
16

我想那会是tf.expand_dims——

tf.expand_dims(a, 1) # Or tf.expand_dims(a, -1)

基本上,我们列出了要插入这个新轴的轴 ID,并且后轴/暗淡被推回

从链接的文档中,这里有几个扩展维度的示例 -

# 't' is a tensor of shape [2]
shape(expand_dims(t, 0)) ==> [1, 2]
shape(expand_dims(t, 1)) ==> [2, 1]
shape(expand_dims(t, -1)) ==> [2, 1]

# 't2' is a tensor of shape [2, 3, 5]
shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]
shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]
shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]
于 2017-02-20T12:08:50.267 回答
2
a = a[..., tf.newaxis].astype("float32")

这也有效

于 2020-11-17T05:22:04.620 回答
1

None如果您对与NumPy 中完全相同的类型(即 )tf.newaxis感兴趣,那么np.newaxis.

例子:

In [71]: a1 = tf.constant([2,2], name="a1")

In [72]: a1
Out[72]: <tf.Tensor 'a1_5:0' shape=(2,) dtype=int32>

# add a new dimension
In [73]: a1_new = a1[tf.newaxis, :]

In [74]: a1_new
Out[74]: <tf.Tensor 'strided_slice_5:0' shape=(1, 2) dtype=int32>

# add one more dimension
In [75]: a1_new = a1[tf.newaxis, :, tf.newaxis]

In [76]: a1_new
Out[76]: <tf.Tensor 'strided_slice_6:0' shape=(1, 2, 1) dtype=int32>

这与您在 NumPy 中执行的操作完全相同。只需在您希望增加的相同维度使用它即可。

于 2017-11-13T16:46:05.573 回答
0

考虑tf.keras.layers.Reshape

# as first layer in a Sequential model
model = Sequential()
model.add(Reshape((3, 4), input_shape=(12,)))
# now: model.output_shape == (None, 3, 4)
# note: `None` is the batch dimension

# as intermediate layer in a Sequential model
model.add(Reshape((6, 2)))
# now: model.output_shape == (None, 6, 2)

# also supports shape inference using `-1` as dimension
model.add(Reshape((-1, 2, 2)))
# now: model.output_shape == (None, 3, 2, 2)
于 2019-04-13T20:54:09.203 回答