aph*_*ent 28 python max deep-learning tensorflow tensor
我的问题有两个相互关联的部分:
如何计算张量的某个轴上的最大值?例如,如果我有
x = tf.constant([[1,220,55],[4,3,-1]])
Run Code Online (Sandbox Code Playgroud)
我想要类似的东西
x_max = tf.max(x, axis=1)
print sess.run(x_max)
output: [220,4]
Run Code Online (Sandbox Code Playgroud)
我知道有一个tf.argmax
和一个tf.maximum
,但是没有沿着单个张量的轴给出最大值.现在我有一个解决方法:
x_max = tf.slice(x, begin=[0,0], size=[-1,1])
for a in range(1,2):
x_max = tf.maximum(x_max , tf.slice(x, begin=[0,a], size=[-1,1]))
Run Code Online (Sandbox Code Playgroud)
但它看起来不太理想.有一个更好的方法吗?
给定argmax
张量的指数,我如何使用这些指数索引另一个张量?使用x
上面的示例,我如何执行以下操作:
ind_max = tf.argmax(x, dimension=1) #output is [1,0]
y = tf.constant([[1,2,3], [6,5,4])
y_ = y[:, ind_max] #y_ should be [2,6]
Run Code Online (Sandbox Code Playgroud)
我知道切片,就像最后一行一样,在TensorFlow中还不存在(#206).
我的问题是:对于我的特定情况,最好的解决方法是什么(可能使用其他方法,如收集,选择等)?
附加信息:我知道x
并且y
只会是二维张量!
mrr*_*rry 59
该tf.reduce_max()
运营商提供的正是这种功能.默认情况下,它计算给定张量的全局最大值,但您可以指定列表reduction_indices
,其含义与axis
NumPy中的含义相同.要完成您的示例:
x = tf.constant([[1, 220, 55], [4, 3, -1]])
x_max = tf.reduce_max(x, reduction_indices=[1])
print sess.run(x_max) # ==> "array([220, 4], dtype=int32)"
Run Code Online (Sandbox Code Playgroud)
如果使用计算argmax tf.argmax()
,可以y
通过展平y
使用来获取不同张量的值tf.reshape()
,将argmax索引转换为矢量索引,如下所示,并使用tf.gather()
提取适当的值:
ind_max = tf.argmax(x, dimension=1)
y = tf.constant([[1, 2, 3], [6, 5, 4]])
flat_y = tf.reshape(y, [-1]) # Reshape to a vector.
# N.B. Handles 2-D case only.
flat_ind_max = ind_max + tf.cast(tf.range(tf.shape(y)[0]) * tf.shape(y)[1], tf.int64)
y_ = tf.gather(flat_y, flat_ind_max)
print sess.run(y_) # ==> "array([2, 6], dtype=int32)"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
45005 次 |
最近记录: |