Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy equivalent to Keras function utils.to_categorical

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.

like image 856
Danny Avatar asked Apr 06 '18 02:04

Danny


People also ask

What is keras utils to_categorical do?

to_categorical function Converts a class vector (integers) to binary class matrix. E.g. for use with categorical_crossentropy . Arguments. y: Array-like with class values to be converted into a matrix (integers from 0 to num_classes - 1 ). num_classes: Total number of classes.

What is keras utils?

Keras provides numpy utility library, which provides functions to perform actions on numpy arrays.

Why is to_categorical used?

You use to_categorical to transform your training data before you pass it to your model. If your training data uses classes as numbers, to_categorical will transform those numbers in proper vectors for using with models.

What is the use of Np_utils?

np_utils. to_categorical is used to convert array of labeled data(from 0 to nb_classes - 1 ) to one-hot vector. The official doc with an example.


1 Answers

Here's one simple way to do it:

np.eye(nb_classes)[y]
like image 51
rvinas Avatar answered Oct 01 '22 19:10

rvinas