title: How can I evenly split a dataset with uneven classes
body: <p>I have a dataset that I am trying to use with a neural network. </p>
  
  <p>The real data looks something like</p>
  
  <pre><code>import numpy as np
  
  features = np.random.rand(1000, 5)
  labels = np.array([1 if sum(e)&gt;1 else 0 for e in features])
  </code></pre>
  
  <p>so roughly 80% of my samples will have the label <code>1</code> and the rest will have the label <code>0</code>. </p>
  
  <p>I can split this into training and testing data using a scikit-learn function</p>
  
  <pre><code>from sklearn import
  
  x_train, x_test, y_train, y_test = train_test_split(features, labels, test_size=0.9)
  </code></pre>
  
  <p>But this will make my training data be strongly skewed, and not very representative of the <code>0</code> label. I would like to split my data so that there are as many <code>0</code>s as there are <code>1</code>s in the training sample. </p>
  
  <hr>
  
  <p>I could do this by hand</p>
  
  <pre><code># separate 1s and 0s
  feat0 = np.array([a if b==0 for a, b in zip(features, labels)])
  feat1 = np.array([a if b==1 for a, b in zip(features, labels)])
  labl0 = np.zeros((len(labels)-sum(labels)))
  labl1 = np.ones((sum(labels)))
  
  # split into training and testing sets
  x_train0, x_test0, y_train0, y_test0 = train_test_split(feat0, labl0, test_size=0.5)
  x_train1, x_test1, y_train1, y_test1 = train_test_split(feat1, labl1, test_size=0.5)
  
  # recombine
  x_train = np.concatenate(x_train0[:100], x_train1[:100])
  y_train = np.concatenate(y_train[:100], y_train[:100])
  </code></pre>
  
  <p>but I would like to know if there is a built-in function to do this, or perhaps a more elegant way. </p>
  
  <hr>
  
  <p>I looked at <code>StratifiedKFold</code>, but </p>
  
  <blockquote>
    <p>The folds are made by preserving the percentage of samples for each class.</p>
  </blockquote>
  
  <p>and this is not what I want to do. I want to force a different percentage of samples for each class. </p>
  
  <p>The <code>1</code> to <code>0</code> ratio in my initial dataset is 80/20. The ratio I want in my training set is 50/50. How do I do this?</p>