How to get number of dimensions in OneHotEncoder in Scikit-learn
<p>I am using the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html" rel="nofollow"><code>OneHotEncoder</code></a> from Scikit-learn in my project. And I need to know what would be the size of each one-hot vector when the <code>n_value</code> is set to be <code>auto</code>. I thought <code>n_value_</code> would show that but it seems I have no way other than trying out training samples. I made this toy example code to show the problem. Do you know any other solution?</p>

<pre><code>from sklearn.preprocessing import OneHotEncoder

data = [[1], [3], [5]] # 3 different features

encoder = OneHotEncoder()
encoder.fit(data)

print(len(encoder.transform([data[0]]).toarray()[0])) # 3 number of dimensions in one-hot-vector
print(encoder.n_values_) # [6] == len(range(5))
</code></pre>

<p>I think the better solution is to define the vector size in <code>n_values</code>. Because the automatic option creates odd behavior with missing features comparing to out of range feature numbers. Trying this example again, it produces zero vector for missing numbers:</p>

<pre><code>from sklearn.preprocessing import OneHotEncoder

data = [[1], [3], [5]] 

encoder = OneHotEncoder()
encoder.fit(data)

print(encoder.transform([
            [0],
            [1],
            [2],
            [3],
            [4],
            [5]
        ]).toarray()) 
</code></pre>

<p>The result is as following:</p>

<pre><code>[[ 0.  0.  0.]
 [ 1.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  1.]]
</code></pre>

<p>And if I try <code>6</code>it just throws errors:</p>

<pre><code>print(encoder.transform([[6]]).toarray()) 
</code></pre>

<p>result:</p>

<pre><code>ValueError: unknown categorical feature present [6] during transform.
</code></pre>

<p>As I mentioned earlier, the best practice is to define the size of vectors from the beginning:</p>

<pre><code>from sklearn.preprocessing import OneHotEncoder

data = [[1], [3], [5]] 

encoder = OneHotEncoder(n_values=50) # maximum size for my vocabulary, fits for my memory and my future development.
encoder.fit(data)
</code></pre>

<p>Keep in mind that in this case, there won't be any <code>active_features_</code> attribute for <code>encoder</code> anymore.</p>

python machine-learning scikit-learn one-hot-encoding