8
votes

I have a Python script which uses Keras for machine learning. I am building X and Y which are features and labels respectively.

The labels are built like this:

def main=():

   depth = 10
   nclass = 101
   skip = True
   output = "True"
   videos = 'sensor'
   img_rows, img_cols, frames = 8, 8, depth
   channel = 1 
   fname_npz = 'dataset_{}_{}_{}.npz'.format(
    nclass, depth, skip)

   vid3d = videoto3d.Videoto3D(img_rows, img_cols, frames)
   nb_classes = nclass

   x, y = loaddata(videos, vid3d, nclass,
                    output, skip)

   X = x.reshape((x.shape[0], img_rows, img_cols, frames, channel))
   Y = np_utils.to_categorical(y, nb_classes) # This needs to be changed

The used function "to_categorical" in Keras is explain as follows:

to_categorical

keras.utils.to_categorical(y, num_classes=None)

Converts a class vector (integers) to binary class matrix.

Now I am using NumPy. May you let me know how the build the same line of code in order to work? In other words, I am looking for the equivalent of the "to_categorical" function in NumPy.

3
to_categorical is written in pure NumPy. You can just copy the source code from it.Yu-Yang
Why don't you just go ahead and use the code from github.com/keras-team/keras/blob/master/keras/utils/np_utils.py referencing its source?wleao

3 Answers

14
votes

Here's one simple way to do it:

np.eye(nb_classes)[y]
1
votes

Try using get_dummies.

>>> pd.core.reshape.get_dummies(df)
Out[30]: 
   cat_a  cat_b  cat_c
0      1      0      0
1      1      0      0
2      1      0      0
3      0      1      0
4      0      1      0
5      0      0      1
0
votes

Something like this (I don't think there is a builtin):

>>> import numpy as np
>>> 
>>> n_cls, n_smp = 3, 10
>>> 
>>> y = np.random.randint(0, n_cls, (n_smp,))
>>> y
array([0, 1, 1, 1, 2, 2, 1, 2, 1, 1])
>>> 
>>> res = np.zeros((y.size, n_cls), dtype=int)
>>> res[np.arange(y.size), y] = 1
>>> res
array([[1, 0, 0],
       [0, 1, 0],
       [0, 1, 0],
       [0, 1, 0],
       [0, 0, 1],
       [0, 0, 1],
       [0, 1, 0],
       [0, 0, 1],
       [0, 1, 0],
       [0, 1, 0]])