tensorflow - 转换张量,使得最大值为 1,其余为 0

标签 tensorflow machine-learning deep-learning tensor

我正在努力解决一个问题,我需要转换张量,以便在总值中,最大值为 1,其余为 0。

tf.Tensor(
    [[0.05]
     [0.1]
     [0.5]
     [0.35]],shape=(4,1),dtype = float32)

我试过了

out = tf.sparse_to_dense(tf.argmax(a),tf.cast(tf.shape(a), dtype=tf.int64), tf.reduce_max(a))

但不幸的是,出现错误

Input must be a SparseTensor.

我想要输出为

tf.Tensor(
    [[0]
     [0]
     [1]
     [0]],shape=(4,1),dtype = float32)

请帮我解决这个问题。 非常感谢

最佳答案

按这个方法试试

x = tf.constant(
    [[0.05],
     [0.1],
     [0.5],
     [0.35]])

top_values, top_indices = tf.nn.top_k(tf.reshape(x, (-1,)), 1)
tf.cast(tf.greater_equal(x, top_values), tf.float64)

输出

<tf.Tensor: shape=(4, 1), dtype=float64, numpy=
array([[0.],
       [0.],
       [1.],
       [0.]])>

关于tensorflow - 转换张量,使得最大值为 1,其余为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62009184/

相关文章:

python - 有没有办法在 python 中使用 opencv 获得更清晰和连续的边缘?

python - 为什么我会收到此图表已断开连接的错误?

c - 使用 TF_SessionRun 在 C(而非 C++)中运行 TensorFlow 图形时出现段错误

c++ - Dlib - 如何使用 loss_mean_squared_multioutput 训练标签类型?

python - keras model.fit_generator() 比 model.fit() 慢几倍

optimization - Tensorflow:从训练中选择最佳模型

python - 如何在 TFRecord 中保存不同长度的列表列表?

machine-learning - 机器学习 (CNN/RNN) 的不平衡训练数据

python - 如何使用函数式 API 调用 Keras 中的自定义层

python - 模块未找到错误: No module named 'tensorflow.contrib.framework'