Numpy one hot encoder is only displaying huge arrays with zeros
<p>I have a <code>(400, 1)</code> numpy array that has values such <code>4300, 4450, 4650...</code> where these values can be distributed around 20 classes i.e. <code>4300 class 1, 4450 class 2...</code> and tried the below code to transform that array to one hot encoded list. The <code>y_train_onehot</code> is showing a list of 400 arrays where each array has a size > 4000 i.e. each array has around 4000 zeros. How can I fix that in order to have one hot encoded vectors for each value i.e. <code>4300</code> can be <code>00001</code>.</p>

<pre><code>def convertOneHot(data):
    y=np.array([int(i[0]) for i in data])
    y_onehot=[0]*len(y)
    for i,j in enumerate(y):
        y_onehot[i]=[0]*(y.max() + 1)
        y_onehot[i][j]=1
    return (y,y_onehot)

y_train,y_train_onehot = convertOneHot(data)
</code></pre>

<p><a href="http://i.stack.imgur.com/LvPqs.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/LvPqs.jpg" alt="sample from y_train_onehot"></a></p>

<p>Here is some not optimized example:</p>

<pre><code>def convert_to_one_hot(y):
  levels=np.unique(y)
  n_classes=levels.shape[0]
  one_hot=np.zeros((y.shape[0],n_classes),"uint8")
  for i in xrange(y.shape[0]):
    for index,level in enumerate(levels):
      if  y[i]==level:
        one_hot[i,index]=1
  return one_hot
</code></pre>

<p><strong>EDIT 1</strong> One less readable but more elegant version:</p>

<pre><code>def convert_to_one_hot2(y):
  levels=np.unique(y)
  one_hot=(y==levels).astype("uint8")
  return one_hot 
</code></pre>

python numpy