【问题标题】:Converting a tensor such that maximum value is 1 and rest is 0转换一个张量,使得最大值为 1,其余为 0
【发布时间】:2020-05-25 19:14:44
【问题描述】:

我正在努力解决一个问题,我需要转换我的张量,以便在总值中,最大值获得 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)

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

【问题讨论】:

    标签: tensorflow machine-learning deep-learning tensor


    【解决方案1】:

    这样试试

    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.]])>
    

    【讨论】:

    • 非常感谢。这个东西工作起来也很容易实现你编写它的方式。
    【解决方案2】:

    使用keras后端K.cast(K.equal(a, K.max(a)), dtype='int8')

    import numpy as np
    
    import tensorflow as tf
    from tensorflow.keras import backend as K
    

    a = np.arange(0, 1, 0.1)
    a = a[:, np.newaxis]
    
    a
    
    
    array([[0. ],
           [0.1],
           [0.2],
           [0.3],
           [0.4],
           [0.5],
           [0.6],
           [0.7],
           [0.8],
           [0.9]], dtype=float32)
    

    tensor = K.cast(a, dtype='float32')
    
    tensor
    
    <tf.Tensor: shape=(10, 1), dtype=float32, numpy=
    array([[0. ],
           [0.1],
           [0.2],
           [0.3],
           [0.4],
           [0.5],
           [0.6],
           [0.7],
           [0.8],
           [0.9]], dtype=float32)>
    

    K.cast(K.equal(a, K.max(a)), dtype='int8')
    
    
    <tf.Tensor: shape=(10, 1), dtype=int8, numpy=
    array([[0],
           [0],
           [0],
           [0],
           [0],
           [0],
           [0],
           [0],
           [0],
           [1]], dtype=int8)>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 2021-03-16
      • 2021-08-18
      • 2018-02-16
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多