<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Decoding values from OneHotEncoder
Let's say we encoded a categorical variable into one-hot encoding, ie. a binary vector with each column indicating one of the values. The scikit-learn library provides a class called OneHotEncoder to do this job. However, it is not well documented how to decode the binary vectors back to the numeric values, ie. to make an inverse transform. In this notebook we'll explore a very simple way to do it. Since OneHotEncoder supports both dense and spares matrix format, we'll try successfully both.
Step1:  Dense matrix
Step2:  The key insight is that the active_features_ attribute of the OHE model represents the original values for each binary column. Thus we can decode the binary-encoded number by simply computing a dot-product with the index (active_features_). For each data point there's just a 1 at the position of the original value.
Step3:  Sparse matrix
<ASSISTANT_TASK:>
Python Code:
from sklearn.preprocessing import OneHotEncoder
import numpy as np
orig = np.array([6, 9, 8, 2, 5, 4, 5, 3, 3, 6])
Explanation: Decoding values from OneHotEncoder
Let's say we encoded a categorical variable into one-hot encoding, ie. a binary vector with each column indicating one of the values. The scikit-learn library provides a class called OneHotEncoder to do this job. However, it is not well documented how to decode the binary vectors back to the numeric values, ie. to make an inverse transform. In this notebook we'll explore a very simple way to do it. Since OneHotEncoder supports both dense and spares matrix format, we'll try successfully both.
End of explanation
ohe_dense = OneHotEncoder(sparse=False)
# reshape() since it needs input as a 2D matrix
encoded_dense = ohe_dense.fit_transform(orig.reshape(-1, 1))
encoded_dense
ohe_dense.active_features_
Explanation: Dense matrix
End of explanation
decoded_dense = encoded_dense.dot(ohe_dense.active_features_).astype(int)
decoded_dense
np.allclose(orig, decoded_dense)
Explanation: The key insight is that the active_features_ attribute of the OHE model represents the original values for each binary column. Thus we can decode the binary-encoded number by simply computing a dot-product with the index (active_features_). For each data point there's just a 1 at the position of the original value.
End of explanation
ohe_sparse = OneHotEncoder(sparse=True)
encoded_sparse = ohe_sparse.fit_transform(orig.reshape(-1, 1))
encoded_sparse
ohe_sparse.active_features_
np.allclose(orig, encoded_sparse.dot(ohe_sparse.active_features_))
Explanation: Sparse matrix
End of explanation
<END_TASK>