2024-10-20 03:54:16 发布
网友
嗨,我是新来的tensorflow。我想在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)
相应的命令是tf.newaxis(或者None,如在numpy中)。在tensorflow的文档中,它本身没有一个条目,但是在^{}的doc页面中有简要介绍。
tf.newaxis
None
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也可以,但是,如上面链接所述
tf.expand_dims
Those interfaces are much more friendly, and highly recommended.
我想应该是^{}-
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]
如果您对与NumPy中完全相同的类型(即None)感兴趣,那么tf.newaxis是np.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>
这和你在纽比做的手术完全一样。只需在你想增加它的地方使用它。
相应的命令是} 的doc页面中有简要介绍。
tf.newaxis
(或者None
,如在numpy中)。在tensorflow的文档中,它本身没有一个条目,但是在^{使用
tf.expand_dims
也可以,但是,如上面链接所述我想应该是^{} -
基本上,我们列出了要插入新轴的轴ID,并将后轴/维度向后推。
在链接的文档中,这里有几个扩展维度的示例-
如果您对与NumPy中完全相同的类型(即
None
)感兴趣,那么tf.newaxis
是np.newaxis
的确切替代方法。示例:
这和你在纽比做的手术完全一样。只需在你想增加它的地方使用它。
相关问题 更多 >
编程相关推荐