Convert a 2d matrix to a 3d one hot matrix numpy

前端 未结 3 523
野趣味
野趣味 2020-12-25 14:49

I have np matrix and I want to convert it to a 3d array with one hot encoding of the elements as third dimension. Is there a way to do with without looping over each row eg

3条回答
  •  情歌与酒
    2020-12-25 15:13

    If you are trying to create one-hot tensor for your machine learning models (you have tensorflow or keras installed) then you can use one_hot function from https://www.tensorflow.org/api_docs/python/tf/keras/backend/one_hot or https://www.tensorflow.org/api_docs/python/tf/one_hot

    It's what I'm using and is working well for high dimensional data.

    Here's example usage:

    >>> import tensorflow as tf
    
    >>> tf.one_hot([[0,2],[1,3]], 4).numpy()
    array([[[1., 0., 0., 0.],
            [0., 0., 1., 0.]],
    
           [[0., 1., 0., 0.],
            [0., 0., 0., 1.]]], dtype=float32)
    

提交回复
热议问题