Cannot pickle Scikit learn NearestNeighbor classifier - can't pickle instancemethod objects
Question: I'm trying to pickle NearestNeighbor model but it says can't pickle
instancemethod objects.

The code:

    
    
    import cPickle as pickle
    from sklearn.neighbors import NearestNeighbors
    
    nbrs = NearestNeighbors(n_neighbors=50, algorithm='ball_tree', metric=self.distanceCIE2000_classifier)
    nbrs.fit(allValues)
    with open('/home/ubuntu/nbrs.p','wb') as f:
           pickle.dump(nbrs, f)
    

The full traceback:

    
    
      File "/home/ubuntu/colorSetter.py", line 82, in createClassifier
        pickle.dump(nbrs, f)
      File "/usr/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
        raise TypeError, "can't pickle %s objects" % base.__name__
      TypeError: can't pickle instancemethod objects
    


Answer: Somewhere within the `NearestNeighbors` instance is an attribute that refers
to the instance method that you passed to it in the `metric` argument. Pickle
won't pickle instance methods, hence the error.

One way around it is to move method `distanceCIE2000_classifier()` out of your
class to a regular standalone function, if that is possible.

