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.
这是一个简单的方法:
np.eye(nb_classes)[y]
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]])
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.