# Buggy code
def fit(self, X, y, sample_weight=None):
    """Build a forest of trees from the training set (X, y).

    Parameters
    ----------
    X : array-like or sparse matrix of shape = [n_samples, n_features]
        The training input samples. Internally, its dtype will be converted to
        ``dtype=np.float32``. If a sparse matrix is provided, it will be
        converted into a sparse ``csc_matrix``.

    y : array-like, shape = [n_samples] or [n_samples, n_outputs]
        The target values (class labels in classification, real numbers in
        regression).

    sample_weight : array-like, shape = [n_samples] or None
        Sample weights. If None, then samples are equally weighted. Splits
        that would create child nodes with net zero or negative weight are
        ignored while searching for a split in each node. In the case of
        classification, splits are also ignored if they would result in any
        single class carrying a negative weight in either child node.

    Returns
    -------
    self : object
        Returns self.
    """
    # Validate or convert input data
    X = check_array(X, accept_sparse="csc", dtype=DTYPE)
    y = check_array(y, accept_sparse="csc", ensure_2d=False, dtype=None)
    if issparse(X):
        # Pre-sort indices to avoid that each individual tree of the
        # ensemble sorts the indices.
        X.sort_indices()

    # Remap output
    n_samples, self.n_features_ = X.shape

    y = np.atleast_1d(y)
    if y.ndim == 2 and y.shape[1] == 1:
        warn(
            "A column-vector y was passed when a 1d array was"
            " expected. Please change the shape of y to "
            "(n_samples,), for example using ravel().",
            DataConversionWarning,
            stacklevel=2,
        )

    if y.ndim == 1:
        # reshape is necessary to preserve the data contiguity against vs
        # [:, np.newaxis] that does not.
        y = np.reshape(y, (-1, 1))

    self.n_outputs_ = y.shape[1]

    y, expanded_class_weight = self._validate_y_class_weight(y)

    if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous:
        y = np.ascontiguousarray(y, dtype=DOUBLE)

    if expanded_class_weight is not None:
        if sample_weight is not None:
            sample_weight = sample_weight * expanded_class_weight
        else:
            sample_weight = expanded_class_weight

    # Check parameters
    self._validate_estimator()

    if not self.bootstrap and self.oob_score:
        raise ValueError("Out of bag estimation only available if bootstrap=True")

    random_state = check_random_state(self.random_state)

    if not self.warm_start or not hasattr(self, "estimators_"):
        # Free allocated memory, if any
        self.estimators_ = []

    n_more_estimators = self.n_estimators - len(self.estimators_)

    if n_more_estimators < 0:
        raise ValueError(
            "n_estimators=%d must be larger or equal to "
            "len(estimators_)=%d when warm_start==True"
            % (self.n_estimators, len(self.estimators_))
        )

    elif n_more_estimators == 0:
        warn(
            "Warm-start fitting without increasing n_estimators does not fit new trees."
        )
    else:
        if self.warm_start and len(self.estimators_) > 0:
            # We draw from the random state to get the random state we
            # would have got if we hadn't used a warm_start.
            random_state.randint(MAX_INT, size=len(self.estimators_))

        trees = []
        for i in range(n_more_estimators):
            tree = self._make_estimator(append=False, random_state=random_state)
            trees.append(tree)

        # Parallel loop: we use the threading backend as the Cython code
        # for fitting the trees is internally releasing the Python GIL
        # making threading always more efficient than multiprocessing in
        # that case.
        trees = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, backend="threading")(
            delayed(_parallel_build_trees)(
                t,
                self,
                X,
                y,
                sample_weight,
                i,
                len(trees),
                verbose=self.verbose,
                class_weight=self.class_weight,
            )
            for i, t in enumerate(trees)
        )

        # Collect newly grown trees
        self.estimators_.extend(trees)

    if self.oob_score:
        self._set_oob_score(X, y)

    # Decapsulate classes_ attributes
    if hasattr(self, "classes_") and self.n_outputs_ == 1:
        self.n_classes_ = self.n_classes_[0]
        self.classes_ = self.classes_[0]

    return self


# Traceback (JoblibException)
---------------------------------------------------------------------------
JoblibException                           Traceback (most recent call last)
<ipython-input-10-020f007024f9> in <module>()
2 # random_search_rf = tune_rf(X_train, Y_train, cv, n_iter=n_iter_search, scoring=scoring)
3 random_search_rf = tune_rf(X_train, Y_train, cv, n_iter=n_iter_search, n_jobs=-1,
----> 4                            scoring=scoring, weights=train_weights)
5 print('RandomizedSearchCV took %.2f seconds for %d candidates'
6       ' parameter settings.' % ((time() - start), n_iter_search))

/Users/icassidy/Desktop/mackbet/model/helper_functions.py in tune_rf(X_train, Y_train, cv, n_iter, scoring, weights, n_jobs)
186                                            cv=cv,
187                                            fit_params={'sample_weight': weights})
--> 188     random_search.fit(X_train, Y_train)
189     return random_search
190

/Users/icassidy/Documents/Development/venv/lib/python2.7/site-packages/sklearn/model_selection/_search.pyc in fit(self, X, y, groups)
1183                                           self.n_iter,
1184                                           random_state=self.random_state)
-> 1185         return self._fit(X, y, groups, sampled_params)

/Users/icassidy/Documents/Development/venv/lib/python2.7/site-packages/sklearn/model_selection/_search.pyc in _fit(self, X, y, groups, parameter_iterable)
560                                   return_times=True, return_parameters=True,
561                                   error_score=self.error_score)
--> 562           for parameters in parameter_iterable
563           for train, test in cv.split(X, y, groups))
564

/Users/icassidy/Documents/Development/venv/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in __call__(self, iterable)
766                 # consumption.
767                 self._iterating = False
--> 768             self.retrieve()
769             # Make sure that we get a last message telling us we are done
770             elapsed_time = time.time() - self._start_time

/Users/icassidy/Documents/Development/venv/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in retrieve(self)
717                     ensure_ready = self._managed_backend
718                     backend.abort_everything(ensure_ready=ensure_ready)
--> 719                 raise exception
720
721     def __call__(self, iterable):

JoblibException: JoblibException
___________________________________________________________________________
Multiprocessing exception:
...........................................................................
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py in _run_module_as_main(mod_name='ipykernel.__main__', alter_argv=1)
157     pkg_name = mod_name.rpartition('.')[0]
158     main_globals = sys.modules["__main__"].__dict__
159     if alter_argv:
160         sys.argv[0] = fname
161     return _run_code(code, main_globals, None,
--> 162                      "__main__", fname, loader, pkg_name)
fname = '/Users/icassidy/Documents/Development/venv/lib/python2.7/site-packages/ipykernel/__main__.py'
loader = <pkgutil.ImpLoader instance>
pkg_name = 'ipykernel'

# Fixed code
def fit(self, X, y, sample_weight=None):
    """Build a forest of trees from the training set (X, y).

    Parameters
    ----------
    X : array-like or sparse matrix of shape = [n_samples, n_features]
        The training input samples. Internally, its dtype will be converted to
        ``dtype=np.float32``. If a sparse matrix is provided, it will be
        converted into a sparse ``csc_matrix``.

    y : array-like, shape = [n_samples] or [n_samples, n_outputs]
        The target values (class labels in classification, real numbers in
        regression).

    sample_weight : array-like, shape = [n_samples] or None
        Sample weights. If None, then samples are equally weighted. Splits
        that would create child nodes with net zero or negative weight are
        ignored while searching for a split in each node. In the case of
        classification, splits are also ignored if they would result in any
        single class carrying a negative weight in either child node.

    Returns
    -------
    self : object
        Returns self.
    """
    # Validate or convert input data
    X = check_array(X, accept_sparse="csc", dtype=DTYPE)
    y = check_array(y, accept_sparse="csc", ensure_2d=False, dtype=None)
    if sample_weight is not None:
        sample_weight = check_array(sample_weight, ensure_2d=False)
    if issparse(X):
        # Pre-sort indices to avoid that each individual tree of the
        # ensemble sorts the indices.
        X.sort_indices()

    # Remap output
    n_samples, self.n_features_ = X.shape

    y = np.atleast_1d(y)
    if y.ndim == 2 and y.shape[1] == 1:
        warn(
            "A column-vector y was passed when a 1d array was"
            " expected. Please change the shape of y to "
            "(n_samples,), for example using ravel().",
            DataConversionWarning,
            stacklevel=2,
        )

    if y.ndim == 1:
        # reshape is necessary to preserve the data contiguity against vs
        # [:, np.newaxis] that does not.
        y = np.reshape(y, (-1, 1))

    self.n_outputs_ = y.shape[1]

    y, expanded_class_weight = self._validate_y_class_weight(y)

    if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous:
        y = np.ascontiguousarray(y, dtype=DOUBLE)

    if expanded_class_weight is not None:
        if sample_weight is not None:
            sample_weight = sample_weight * expanded_class_weight
        else:
            sample_weight = expanded_class_weight

    # Check parameters
    self._validate_estimator()

    if not self.bootstrap and self.oob_score:
        raise ValueError("Out of bag estimation only available if bootstrap=True")

    random_state = check_random_state(self.random_state)

    if not self.warm_start or not hasattr(self, "estimators_"):
        # Free allocated memory, if any
        self.estimators_ = []

    n_more_estimators = self.n_estimators - len(self.estimators_)

    if n_more_estimators < 0:
        raise ValueError(
            "n_estimators=%d must be larger or equal to "
            "len(estimators_)=%d when warm_start==True"
            % (self.n_estimators, len(self.estimators_))
        )

    elif n_more_estimators == 0:
        warn(
            "Warm-start fitting without increasing n_estimators does not fit new trees."
        )
    else:
        if self.warm_start and len(self.estimators_) > 0:
            # We draw from the random state to get the random state we
            # would have got if we hadn't used a warm_start.
            random_state.randint(MAX_INT, size=len(self.estimators_))

        trees = []
        for i in range(n_more_estimators):
            tree = self._make_estimator(append=False, random_state=random_state)
            trees.append(tree)

        # Parallel loop: we use the threading backend as the Cython code
        # for fitting the trees is internally releasing the Python GIL
        # making threading always more efficient than multiprocessing in
        # that case.
        trees = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, backend="threading")(
            delayed(_parallel_build_trees)(
                t,
                self,
                X,
                y,
                sample_weight,
                i,
                len(trees),
                verbose=self.verbose,
                class_weight=self.class_weight,
            )
            for i, t in enumerate(trees)
        )

        # Collect newly grown trees
        self.estimators_.extend(trees)

    if self.oob_score:
        self._set_oob_score(X, y)

    # Decapsulate classes_ attributes
    if hasattr(self, "classes_") and self.n_outputs_ == 1:
        self.n_classes_ = self.n_classes_[0]
        self.classes_ = self.classes_[0]

    return self