您好我是tensorflow的新手。我想在tensorflow中实现以下python代码。
(string)a<(string)b
答案 0 :(得分:10)
我认为那将是tf.expand_dims
-
tf.expand_dims(a, 1) # Or tf.expand_dims(a, -1)
基本上,我们列出了要插入此新轴的轴ID,并且尾随轴/ dims是被推回。
从链接的文档中,这里有几个扩展维度的例子 -
# '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]
答案 1 :(得分:4)
相应的命令是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
也可以,但如上面的链接中所述,
这些界面更友好,强烈推荐。
答案 2 :(得分:0)
如果您对与NumPy完全相同的类型(例如None
)感兴趣,那么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中执行的操作完全相同。只需在您希望增加它的同一维度使用它。
答案 3 :(得分:0)
# 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)
答案 4 :(得分:0)
a = a[..., tf.newaxis].astype("float32")
这同样有效