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.
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.
Keras provides numpy utility library, which provides functions to perform actions on numpy arrays.
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.
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.
Here's one simple way to do it:
np.eye(nb_classes)[y]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With