1
$\begingroup$

Is there a way (other than manually creating dictionaries) to one hot encode sequences in which not all values can be present in a sequence? sklearn's OneHotEncoder and numpy's to_categorical only account for the values in the current sample so for example, encoding DNA sequences of 'AT' and 'CG' would both be [[1, 0], [0, 1]]. However, I want A, T, C, and G to be accounted for in all sequences so 'AT' should be [[1, 0, 0, 0], [0, 1, 0, 0]] and 'CG' should be [[0, 0, 1, 0], [0, 0, 0, 1]].

$\endgroup$
1
  • $\begingroup$ consider preprocessing them in the way that you want to be one hot encoded before appying the OneHotEncoder $\endgroup$ Mar 15 '20 at 8:40
0
$\begingroup$

You can use scikit-learn's OneHotEncoder like this:

from sklearn.preprocessing import OneHotEncoder

X = [['A', 'T'], ['C', 'G']]
enc = OneHotEncoder()
enc.fit_transform(X).toarray()

The result is

array([[1., 0., 0., 1.],
       [0., 1., 1., 0.]])
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.