keras.utils.to_categorical() 如何支持多个值?

xiaoxingxing tensorflow 523

原文标题How can keras.utils.to_categorical() support more than one value?

我知道keras.utils.to_categorical()可以用于 one-hot 编码,如转换的示例中2->[0., 0., 1., 0.]但是是否有可能有类似的输出?2, 3->[0., 0., 1., 1.]如果可以,请问如何?

原文链接:https://stackoverflow.com//questions/71984301/how-can-keras-utils-to-categorical-support-more-than-one-value

回复

我来回复
  • Pritam Dodeja的头像
    Pritam Dodeja 评论

    您可以使用以下方法执行此操作:

    layer = tf.keras.layers.CategoryEncoding(output_mode="multi_hot", num_tokens=4)
    
    [nav] In [50]: layer([[2,3]])                                                                                                                                               
    Out[50]: <tf.Tensor: shape=(1, 4), dtype=float32, numpy=array([[0., 0., 1., 1.]], dtype=float32)>   
    

    tf.keras.utils.to_categorical is used in the process to calculate categorical cross entropy, a loss function for binary classification。 Also note that you’ll need to figure out the number of tokens you have, here I am assuming 4 to cover your [2, 3] scenario。 In this case, the encoder can encode [0, 1, 2, 3], you can pass it samples of any length, it will encode them to [0|1, 0|1, 0|1, 0|1].

    1年前 0条评论