Argmax on a tensor and ceiling in Tensorflow

帅比萌擦擦* 提交于 2019-12-08 12:20:45

问题


Suppose I have a tensor in Tensorflow that its values are like:

A = [[0.7, 0.2, 0.1],[0.1, 0.4, 0.5]]

How can I change this tensor into the following:

B = [[1, 0, 0],[0, 0, 1]] 

In other words I want to just keep the maximum and replace it with 1.
Any help would be appreciated.


回答1:


I think that you can solve it with a one-liner:

import tensorflow as tf
import numpy as np

x_data = [[0.7, 0.2, 0.1],[0.1, 0.4, 0.5]]
# I am using hard-coded dimensions for simplicity
x = tf.placeholder(dtype=tf.float32, name="x", shape=(2,3))

session = tf.InteractiveSession()

session.run(tf.one_hot(tf.argmax(x, 1), 3), {x: x_data})

The result is the one that you expect:

Out[6]: 
array([[ 1.,  0.,  0.],
       [ 0.,  0.,  1.]], dtype=float32)


来源:https://stackoverflow.com/questions/44834739/argmax-on-a-tensor-and-ceiling-in-tensorflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!