Is there a way to OneHotEncode an entire array? #149
-
Hi, def OneHot(y, NumOfClasses):
e = np.zeros((NumOfClasses, 1))
e[y] = 1.0
return e Basically obviating doing this |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hi @moisestohias, You may want to try Scikit-Learn's OneHotEncoder - http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html |
Beta Was this translation helpful? Give feedback.
-
I have found many solutions on the Internet Resources:!Note: for one hot encoding you can use scipy.sparse as well. __Note: using eye is the only useful solution for an input N-D matrix to one-hot N+1D matrix. __ input_matrix=np.asarray([[0,1,1] , [1,1,2]]) ; np.eye(3)[input_matrix] # output 3D tensor
def one_hot(a, classes=10): return np.eye(classes)[a] # .T Transpose if you don't want torch style
def one_hot(a: np.ndarray):
# a.max()+1 automatically determin the number of classes based on the highest value.
hot = np.zeros((a.size, a.max()+1), dtype=np.float32)
hot[np.arange(a.size),a] = 1.0
return hot
def one_hot(a, classes=10 ):
hot = np.zeros((a.size, classes), dtype=np.float32)
hot[np.arange(a.size),a] = 1.0
return hot |
Beta Was this translation helpful? Give feedback.
Hi @moisestohias,
You may want to try Scikit-Learn's OneHotEncoder - http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html