copy it from sklearn. It's < 20 lines.