gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _partial_fit(self, X, y, classes=None):
    _check_partial_fit_first_call(self, classes)

    super(MLPClassifier, self)._partial_fit(X, y)

    return self


# Traceback (ValueError)
Traceback (most recent call last):
File "fail.py", line 7, in <module>
clf.partial_fit([[4]],["d"])
File "/usr/local/lib/python3.4/dist-packages/sklearn/neural_network/multilayer_perceptron.py", line 989, in _partial_fit
super(MLPClassifier, self)._partial_fit(X, y)
File "/usr/local/lib/python3.4/dist-packages/sklearn/neural_network/multilayer_perceptron.py", line 640, in _partial_fit
return self._fit(X, y, incremental=True)
File "/usr/local/lib/python3.4/dist-packages/sklearn/neural_network/multilayer_perceptron.py", line 375, in _fit
intercept_grads, layer_units, incremental)
File "/usr/local/lib/python3.4/dist-packages/sklearn/neural_network/multilayer_perceptron.py", line 512, in _fit_stochastic
coef_grads, intercept_grads)
File "/usr/local/lib/python3.4/dist-packages/sklearn/neural_network/multilayer_perceptron.py", line 225, in _backprop
loss = LOSS_FUNCTIONS[self.loss](y, activations[-1])
File "/usr/local/lib/python3.4/dist-packages/sklearn/neural_network/_base.py", line 208, in log_loss
return -np.sum(y_true * np.log(y_prob)) / y_prob.shape[0]
ValueError: operands could not be broadcast together with shapes (1,2) (1,3)

# Fixed code
def _partial_fit(self, X, y, classes=None):
    if _check_partial_fit_first_call(self, classes):
        self._label_binarizer = LabelBinarizer()
        if type_of_target(y).startswith("multilabel"):
            self._label_binarizer.fit(y)
        else:
            self._label_binarizer.fit(classes)

    super(MLPClassifier, self)._partial_fit(X, y)

    return self
# Buggy code
def predict_proba(self, X):
    """Posterior probabilities of classification

    This function returns posterior probabilities of classification
    according to each class on an array of test vectors X.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        The samples.

    Returns
    -------
    C : array, shape (n_samples, n_classes)
        The predicted probas.
    """
    check_is_fitted(self, ["classes_", "calibrated_classifiers_"])
    X = check_array(X, accept_sparse=["csc", "csr", "coo"])
    # Compute the arithmetic mean of the predictions of the calibrated
    # classfiers
    mean_proba = np.zeros((X.shape[0], len(self.classes_)))
    for calibrated_classifier in self.calibrated_classifiers_:
        proba = calibrated_classifier.predict_proba(X)
        mean_proba += proba

    mean_proba /= len(self.calibrated_classifiers_)

    return mean_proba


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def predict_proba(self, X):
    """Posterior probabilities of classification

    This function returns posterior probabilities of classification
    according to each class on an array of test vectors X.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        The samples.

    Returns
    -------
    C : array, shape (n_samples, n_classes)
        The predicted probas.
    """
    check_is_fitted(self, ["classes_", "calibrated_classifiers_"])
    X = check_array(X, accept_sparse=["csc", "csr", "coo"], force_all_finite=False)
    # Compute the arithmetic mean of the predictions of the calibrated
    # classfiers
    mean_proba = np.zeros((X.shape[0], len(self.classes_)))
    for calibrated_classifier in self.calibrated_classifiers_:
        proba = calibrated_classifier.predict_proba(X)
        mean_proba += proba

    mean_proba /= len(self.calibrated_classifiers_)

    return mean_proba
# Buggy code
def configuration(parent_package="", top_path=None):
    from numpy.distutils.misc_util import Configuration

    cblas_libs, blas_info = get_blas_info()

    libraries = []
    if os.name == "posix":
        cblas_libs.append("m")
        libraries.append("m")

    config = Configuration("cluster", parent_package, top_path)
    config.add_extension(
        "_hierarchical",
        sources=["_hierarchical.cpp"],
        language="c++",
        include_dirs=[numpy.get_include()],
        libraries=libraries,
    )

    config.add_extension(
        "_k_means",
        libraries=cblas_libs,
        sources=["_k_means.c"],
        include_dirs=[
            join("..", "src", "cblas"),
            numpy.get_include(),
            blas_info.pop("include_dirs", []),
        ],
        extra_compile_args=blas_info.pop("extra_compile_args", []),
        **blas_info,
    )

    return config


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def configuration(parent_package="", top_path=None):
    from numpy.distutils.misc_util import Configuration

    cblas_libs, blas_info = get_blas_info()

    libraries = []
    if os.name == "posix":
        cblas_libs.append("m")
        libraries.append("m")

    config = Configuration("cluster", parent_package, top_path)
    config.add_extension(
        "_dbscan_inner",
        sources=["_dbscan_inner.cpp"],
        include_dirs=[numpy.get_include()],
        language="c++",
    )

    config.add_extension(
        "_hierarchical",
        sources=["_hierarchical.cpp"],
        language="c++",
        include_dirs=[numpy.get_include()],
        libraries=libraries,
    )

    config.add_extension(
        "_k_means",
        libraries=cblas_libs,
        sources=["_k_means.c"],
        include_dirs=[
            join("..", "src", "cblas"),
            numpy.get_include(),
            blas_info.pop("include_dirs", []),
        ],
        extra_compile_args=blas_info.pop("extra_compile_args", []),
        **blas_info,
    )

    return config
# Buggy code
def __init__(
    self, estimator, n_features_to_select=None, step=1, estimator_params={}, verbose=0
):
    self.estimator = estimator
    self.n_features_to_select = n_features_to_select
    self.step = step
    self.estimator_params = estimator_params
    self.verbose = verbose


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def __init__(
    self, estimator, n_features_to_select=None, step=1, estimator_params=None, verbose=0
):
    self.estimator = estimator
    self.n_features_to_select = n_features_to_select
    self.step = step
    self.estimator_params = estimator_params
    self.verbose = verbose
# Buggy code
def __init__(
    self, estimator, step=1, cv=None, scoring=None, estimator_params={}, verbose=0
):
    self.estimator = estimator
    self.step = step
    self.cv = cv
    self.scoring = scoring
    self.estimator_params = estimator_params
    self.verbose = verbose


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def __init__(
    self, estimator, step=1, cv=None, scoring=None, estimator_params=None, verbose=0
):
    self.estimator = estimator
    self.step = step
    self.cv = cv
    self.scoring = scoring
    self.estimator_params = estimator_params
    self.verbose = verbose
# Buggy code
def f_classif(X, y):
    """Compute the Anova F-value for the provided sample

    Parameters
    ----------
    X : {array-like, sparse matrix} shape = [n_samples, n_features]
        The set of regressors that will tested sequentially.

    y : array of shape(n_samples)
        The data matrix.

    Returns
    -------
    F : array, shape = [n_features,]
        The set of F values.

    pval : array, shape = [n_features,]
        The set of p-values.
    """
    X, y = check_X_y(X, y, ["csr", "csc", "coo"])
    args = [X[safe_mask(X, y == k)] for k in np.unique(y)]
    return f_oneway(*args)


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def f_classif(X, y):
    """Compute the ANOVA F-value for the provided sample.

    Parameters
    ----------
    X : {array-like, sparse matrix} shape = [n_samples, n_features]
        The set of regressors that will tested sequentially.

    y : array of shape(n_samples)
        The data matrix.

    Returns
    -------
    F : array, shape = [n_features,]
        The set of F values.

    pval : array, shape = [n_features,]
        The set of p-values.

    See also
    --------
    chi2: Chi-squared stats of non-negative features for classification tasks.
    f_regression: F-value between label/feature for regression tasks.
    """
    X, y = check_X_y(X, y, ["csr", "csc", "coo"])
    args = [X[safe_mask(X, y == k)] for k in np.unique(y)]
    return f_oneway(*args)
# Buggy code
def fit(self, X, y=None, sample_weight=None):
    """Fit Kernel Ridge regression model

    Parameters
    ----------
    X : {array-like, sparse matrix}, shape = [n_samples, n_features]
        Training data

    y : array-like, shape = [n_samples] or [n_samples, n_targets]
        Target values

    sample_weight : float or numpy array of shape [n_samples]
        Individual weights for each sample, ignored if None is passed.

    Returns
    -------
    self : returns an instance of self.
    """
    # Convert data
    X, y = check_X_y(X, y, multi_output=True)

    n_samples = X.shape[0]
    K = self._get_kernel(X)
    alpha = np.atleast_1d(self.alpha)

    ravel = False
    if len(y.shape) == 1:
        y = y.reshape(-1, 1)
        ravel = True

    copy = self.kernel == "precomputed"
    self.dual_coef_ = _solve_cholesky_kernel(K, y, alpha, sample_weight, copy)
    if ravel:
        self.dual_coef_ = self.dual_coef_.ravel()

    self.X_fit_ = X

    return self


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def fit(self, X, y=None, sample_weight=None):
    """Fit Kernel Ridge regression model

    Parameters
    ----------
    X : {array-like, sparse matrix}, shape = [n_samples, n_features]
        Training data

    y : array-like, shape = [n_samples] or [n_samples, n_targets]
        Target values

    sample_weight : float or numpy array of shape [n_samples]
        Individual weights for each sample, ignored if None is passed.

    Returns
    -------
    self : returns an instance of self.
    """
    # Convert data
    X, y = check_X_y(X, y, accept_sparse=("csr", "csc"), multi_output=True)

    n_samples = X.shape[0]
    K = self._get_kernel(X)
    alpha = np.atleast_1d(self.alpha)

    ravel = False
    if len(y.shape) == 1:
        y = y.reshape(-1, 1)
        ravel = True

    copy = self.kernel == "precomputed"
    self.dual_coef_ = _solve_cholesky_kernel(K, y, alpha, sample_weight, copy)
    if ravel:
        self.dual_coef_ = self.dual_coef_.ravel()

    self.X_fit_ = X

    return self
# Buggy code
def transform(self, X):
    """Project data to maximize class separation.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Input data.

    Returns
    -------
    X_new : array, shape (n_samples, n_components)
        Transformed data.
    """
    check_is_fitted(self, ["xbar_", "scalings_"], all_or_any=any)

    X = check_array(X)
    if self.solver == "lsqr":
        raise NotImplementedError(
            "transform not implemented for 'lsqr' solver (use 'svd' or 'eigen')."
        )
    elif self.solver == "svd":
        X_new = np.dot(X - self.xbar_, self.scalings_)
    elif self.solver == "eigen":
        X_new = np.dot(X, self.scalings_)
    n_components = X.shape[1] if self.n_components is None else self.n_components
    return X_new[:, :n_components]


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def transform(self, X):
    """Project data to maximize class separation.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Input data.

    Returns
    -------
    X_new : array, shape (n_samples, n_components)
        Transformed data.
    """
    if self.solver == "lsqr":
        raise NotImplementedError(
            "transform not implemented for 'lsqr' solver (use 'svd' or 'eigen')."
        )
    check_is_fitted(self, ["xbar_", "scalings_"], all_or_any=any)

    X = check_array(X)
    if self.solver == "svd":
        X_new = np.dot(X - self.xbar_, self.scalings_)
    elif self.solver == "eigen":
        X_new = np.dot(X, self.scalings_)
    n_components = X.shape[1] if self.n_components is None else self.n_components
    return X_new[:, :n_components]
# Buggy code
def _mean_and_std(X, axis=0, with_mean=True, with_std=True):
    """Compute mean and std deviation for centering, scaling.

    Zero valued std components are reset to 1.0 to avoid NaNs when scaling.
    """
    X = np.asarray(X)
    Xr = np.rollaxis(X, axis)

    if with_mean:
        mean_ = Xr.mean(axis=0)
    else:
        mean_ = None

    if with_std:
        std_ = Xr.std(axis=0)
        if isinstance(std_, np.ndarray):
            std_[std_ == 0.0] = 1.0
        elif std_ == 0.0:
            std_ = 1.0
    else:
        std_ = None

    return mean_, std_


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def _mean_and_std(X, axis=0, with_mean=True, with_std=True):
    """Compute mean and std deviation for centering, scaling.

    Zero valued std components are reset to 1.0 to avoid NaNs when scaling.
    """
    X = np.asarray(X)
    Xr = np.rollaxis(X, axis)

    if with_mean:
        mean_ = Xr.mean(axis=0)
    else:
        mean_ = None

    if with_std:
        std_ = Xr.std(axis=0)
        if isinstance(std_, np.ndarray):
            std_[std_ == 0.0] = 1.0
        elif std_ == 0.0:
            std_ = 1.0
    else:
        std_ = None

    return mean_, std_
# Buggy code
def fit(self, X, y=None):
    """
    Compute the polynomial feature combinations
    """
    n_samples, n_features = check_array(X).shape
    self.powers_ = self._power_matrix(
        n_features, self.degree, self.interaction_only, self.include_bias
    )
    return self


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def fit(self, X, y=None):
    """
    Compute number of output features.
    """
    n_samples, n_features = check_array(X).shape
    combinations = self._combinations(
        n_features, self.degree, self.interaction_only, self.include_bias
    )
    self.n_input_features_ = n_features
    self.n_output_features_ = sum(1 for _ in combinations)
    return self
# Buggy code
def transform(self, X, y=None):
    """Transform data to polynomial features

    Parameters
    ----------
    X : array with shape [n_samples, n_features]
        The data to transform, row by row.

    Returns
    -------
    XP : np.ndarray shape [n_samples, NP]
        The matrix of features, where NP is the number of polynomial
        features generated from the combination of inputs.
    """
    check_is_fitted(self, "powers_")

    X = check_array(X)
    n_samples, n_features = X.shape

    if n_features != self.powers_.shape[1]:
        raise ValueError("X shape does not match training shape")

    return (X[:, None, :] ** self.powers_).prod(-1)


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def transform(self, X, y=None):
    """Transform data to polynomial features

    Parameters
    ----------
    X : array with shape [n_samples, n_features]
        The data to transform, row by row.

    Returns
    -------
    XP : np.ndarray shape [n_samples, NP]
        The matrix of features, where NP is the number of polynomial
        features generated from the combination of inputs.
    """
    check_is_fitted(self, ["n_input_features_", "n_output_features_"])

    X = check_array(X)
    n_samples, n_features = X.shape

    if n_features != self.n_input_features_:
        raise ValueError("X shape does not match training shape")

    # allocate output data
    XP = np.empty((n_samples, self.n_output_features_), dtype=X.dtype)

    combinations = self._combinations(
        n_features, self.degree, self.interaction_only, self.include_bias
    )
    for i, c in enumerate(combinations):
        XP[:, i] = X[:, c].prod(1)

    return XP
# Buggy code
def predict(self, X):
    """Perform regression on samples in X.

    For an one-class model, +1 or -1 is returned.

    Parameters
    ----------
    X : {array-like, sparse matrix}, shape (n_samples, n_features)

    Returns
    -------
    y_pred : array, shape (n_samples,)
    """
    X = self._validate_for_predict(X)
    predict = self._sparse_predict if self._sparse else self._dense_predict
    return predict(X)


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def predict(self, X):
    """Perform regression on samples in X.

    For an one-class model, +1 or -1 is returned.

    Parameters
    ----------
    X : {array-like, sparse matrix}, shape (n_samples, n_features)
        For kernel="precomputed", the expected shape of X is
        (n_samples_test, n_samples_train).

    Returns
    -------
    y_pred : array, shape (n_samples,)
    """
    X = self._validate_for_predict(X)
    predict = self._sparse_predict if self._sparse else self._dense_predict
    return predict(X)
# Buggy code
def predict(self, X):
    """Perform classification on samples in X.

    For an one-class model, +1 or -1 is returned.

    Parameters
    ----------
    X : {array-like, sparse matrix}, shape = [n_samples, n_features]

    Returns
    -------
    y_pred : array, shape = [n_samples]
        Class labels for samples in X.
    """
    y = super(BaseSVC, self).predict(X)
    return self.classes_.take(np.asarray(y, dtype=np.intp))


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def predict(self, X):
    """Perform classification on samples in X.

    For an one-class model, +1 or -1 is returned.

    Parameters
    ----------
    X : {array-like, sparse matrix}, shape = [n_samples, n_features]
        For kernel="precomputed", the expected shape of X is
        [n_samples_test, n_samples_train]

    Returns
    -------
    y_pred : array, shape = [n_samples]
        Class labels for samples in X.
    """
    y = super(BaseSVC, self).predict(X)
    return self.classes_.take(np.asarray(y, dtype=np.intp))
# Buggy code
def predict_proba(self):
    """Compute probabilities of possible outcomes for samples in X.

    The model need to have probability information computed at training
    time: fit with attribute `probability` set to True.

    Parameters
    ----------
    X : array-like, shape = [n_samples, n_features]

    Returns
    -------
    T : array-like, shape = [n_samples, n_classes]
        Returns the probability of the sample for each class in
        the model. The columns correspond to the classes in sorted
        order, as they appear in the attribute `classes_`.

    Notes
    -----
    The probability model is created using cross validation, so
    the results can be slightly different than those obtained by
    predict. Also, it will produce meaningless results on very small
    datasets.
    """
    self._check_proba()
    return self._predict_proba


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def predict_proba(self):
    """Compute probabilities of possible outcomes for samples in X.

    The model need to have probability information computed at training
    time: fit with attribute `probability` set to True.

    Parameters
    ----------
    X : array-like, shape = [n_samples, n_features]
        For kernel="precomputed", the expected shape of X is
        [n_samples_test, n_samples_train]

    Returns
    -------
    T : array-like, shape = [n_samples, n_classes]
        Returns the probability of the sample for each class in
        the model. The columns correspond to the classes in sorted
        order, as they appear in the attribute `classes_`.

    Notes
    -----
    The probability model is created using cross validation, so
    the results can be slightly different than those obtained by
    predict. Also, it will produce meaningless results on very small
    datasets.
    """
    self._check_proba()
    return self._predict_proba
# Buggy code
def predict_log_proba(self):
    """Compute log probabilities of possible outcomes for samples in X.

    The model need to have probability information computed at training
    time: fit with attribute `probability` set to True.

    Parameters
    ----------
    X : array-like, shape = [n_samples, n_features]

    Returns
    -------
    T : array-like, shape = [n_samples, n_classes]
        Returns the log-probabilities of the sample for each class in
        the model. The columns correspond to the classes in sorted
        order, as they appear in the attribute `classes_`.

    Notes
    -----
    The probability model is created using cross validation, so
    the results can be slightly different than those obtained by
    predict. Also, it will produce meaningless results on very small
    datasets.
    """
    self._check_proba()
    return self._predict_log_proba


# Traceback (AssertionError)
======================================================================
FAIL: Tests that class_weight and sample_weight are multiplicative
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/buildd/scikit-learn-0.16.0~b1+git1-gab4d07d/debian/python-sklearn/usr/lib/python2.7/dist-packages/sklearn/linear_model/tests/test_sgd.py", line 633, in test_weights_multiplied
assert_array_equal(clf1.coef_, clf2.coef_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 718, in assert_array_equal
verbose=verbose, header='Arrays are not equal')
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 644, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal

(mismatch 16.6666666667%)
x: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])
y: array([[-0.34681637, -0.32240913, -0.31335029,  0.34920789,  0.3658206 ,
0.38752489]])

# Fixed code
def predict_log_proba(self):
    """Compute log probabilities of possible outcomes for samples in X.

    The model need to have probability information computed at training
    time: fit with attribute `probability` set to True.

    Parameters
    ----------
    X : array-like, shape = [n_samples, n_features]
        For kernel="precomputed", the expected shape of X is
        [n_samples_test, n_samples_train]

    Returns
    -------
    T : array-like, shape = [n_samples, n_classes]
        Returns the log-probabilities of the sample for each class in
        the model. The columns correspond to the classes in sorted
        order, as they appear in the attribute `classes_`.

    Notes
    -----
    The probability model is created using cross validation, so
    the results can be slightly different than those obtained by
    predict. Also, it will produce meaningless results on very small
    datasets.
    """
    self._check_proba()
    return self._predict_log_proba
# Buggy code
def transform(self, X):
    """Reduce X to the selected features.

    Parameters
    ----------
    X : array of shape [n_samples, n_features]
        The input samples.

    Returns
    -------
    X_r : array of shape [n_samples, n_selected_features]
        The input samples with only the selected features.
    """
    X = check_array(X, accept_sparse="csr")
    mask = self.get_support()
    if len(mask) != X.shape[1]:
        raise ValueError("X has a different shape than during fitting.")
    return check_array(X, accept_sparse="csr")[:, safe_mask(X, mask)]


# Traceback (ValueError)
ValueError                                Traceback (most recent call last)
<ipython-input-7-5cd77e510247> in <module>()
----> 1 asdf.transform(X)

/home/andy/checkout/scikit-learn/sklearn/feature_selection/base.pyc in transform(self, X)
73         """
74         X = check_array(X, accept_sparse='csr')
---> 75         mask = self.get_support()
76         if len(mask) != X.shape[1]:
77             raise ValueError("X has a different shape than during fitting.")

/home/andy/checkout/scikit-learn/sklearn/feature_selection/base.pyc in get_support(self, indices)
44             values are indices into the input feature vector.
45         """
---> 46         mask = self._get_support_mask()
47         return mask if not indices else np.where(mask)[0]
48

/home/andy/checkout/scikit-learn/sklearn/feature_selection/univariate_selection.pyc in _get_support_mask(self)
488         alpha = self.alpha
489         sv = np.sort(self.pvalues_)
--> 490         threshold = sv[sv < alpha * np.arange(len(self.pvalues_))].max()
491         return self.pvalues_ <= threshold
492

/usr/lib/python2.7/dist-packages/numpy/core/_methods.pyc in _amax(a, axis, out, keepdims)
15 def _amax(a, axis=None, out=None, keepdims=False):
16     return um.maximum.reduce(a, axis=axis,
---> 17                             out=out, keepdims=keepdims)
18
19 def _amin(a, axis=None, out=None, keepdims=False):

ValueError: zero-size array to reduction operation maximum which has no identity

# Fixed code
def transform(self, X):
    """Reduce X to the selected features.

    Parameters
    ----------
    X : array of shape [n_samples, n_features]
        The input samples.

    Returns
    -------
    X_r : array of shape [n_samples, n_selected_features]
        The input samples with only the selected features.
    """
    X = check_array(X, accept_sparse="csr")
    mask = self.get_support()
    if not mask.any():
        warn(
            "No features were selected: either the data is"
            " too noisy or the selection test too strict.",
            UserWarning,
        )
        return np.empty(0).reshape((X.shape[0], 0))
    if len(mask) != X.shape[1]:
        raise ValueError("X has a different shape than during fitting.")
    return check_array(X, accept_sparse="csr")[:, safe_mask(X, mask)]
# Buggy code
def _get_support_mask(self):
    check_is_fitted(self, "scores_")

    alpha = self.alpha
    sv = np.sort(self.pvalues_)
    threshold = sv[sv < alpha * np.arange(len(self.pvalues_))].max()
    return self.pvalues_ <= threshold


# Traceback (ValueError)
ValueError                                Traceback (most recent call last)
<ipython-input-7-5cd77e510247> in <module>()
----> 1 asdf.transform(X)

/home/andy/checkout/scikit-learn/sklearn/feature_selection/base.pyc in transform(self, X)
73         """
74         X = check_array(X, accept_sparse='csr')
---> 75         mask = self.get_support()
76         if len(mask) != X.shape[1]:
77             raise ValueError("X has a different shape than during fitting.")

/home/andy/checkout/scikit-learn/sklearn/feature_selection/base.pyc in get_support(self, indices)
44             values are indices into the input feature vector.
45         """
---> 46         mask = self._get_support_mask()
47         return mask if not indices else np.where(mask)[0]
48

/home/andy/checkout/scikit-learn/sklearn/feature_selection/univariate_selection.pyc in _get_support_mask(self)
488         alpha = self.alpha
489         sv = np.sort(self.pvalues_)
--> 490         threshold = sv[sv < alpha * np.arange(len(self.pvalues_))].max()
491         return self.pvalues_ <= threshold
492

/usr/lib/python2.7/dist-packages/numpy/core/_methods.pyc in _amax(a, axis, out, keepdims)
15 def _amax(a, axis=None, out=None, keepdims=False):
16     return um.maximum.reduce(a, axis=axis,
---> 17                             out=out, keepdims=keepdims)
18
19 def _amin(a, axis=None, out=None, keepdims=False):

ValueError: zero-size array to reduction operation maximum which has no identity

# Fixed code
def _get_support_mask(self):
    check_is_fitted(self, "scores_")

    alpha = self.alpha
    sv = np.sort(self.pvalues_)
    selected = sv[sv < alpha * np.arange(len(self.pvalues_))]
    if selected.size == 0:
        return np.zeros_like(self.pvalues_, dtype=bool)
    return self.pvalues_ <= selected.max()
# Buggy code
def __init__(
    self, doc_url, searchindex="searchindex.js", extra_modules_test=None, relative=False
):
    self.doc_url = doc_url
    self.relative = relative
    self._link_cache = {}

    self.extra_modules_test = extra_modules_test
    self._page_cache = {}
    if doc_url.startswith("http://"):
        if relative:
            raise ValueError(
                "Relative links are only supported for local "
                'URLs (doc_url cannot start with "http://)"'
            )
        searchindex_url = doc_url + "/" + searchindex
    else:
        searchindex_url = os.path.join(doc_url, searchindex)

    # detect if we are using relative links on a Windows system
    if os.name.lower() == "nt" and not doc_url.startswith("http://"):
        if not relative:
            raise ValueError(
                "You have to use relative=True for the local"
                " package on a Windows system."
            )
        self._is_windows = True
    else:
        self._is_windows = False

    # download and initialize the search index
    sindex = get_data(searchindex_url)
    filenames, objects = parse_sphinx_searchindex(sindex)

    self._searchindex = dict(filenames=filenames, objects=objects)


# Traceback (IndexError)
======================================================================
ERROR: sklearn.tests.test_common.test_regressors_train('RANSACRegressor', <class 'sklearn.linear_model.ransac.RANSACRegr
essor'>, array([[-0.44836249, -0.47282444, -1.20608008, ..., -0.75500806,
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\nose\case.py", line 197, in runTest
self.test(*self.arg)
File "C:\Python27\lib\site-packages\sklearn\tests\test_common.py", line 850, in check_regressors_train
assert_raises(ValueError, regressor.fit, X, y[:-1])
File "C:\Python27\lib\unittest\case.py", line 473, in assertRaises
callableObj(*args, **kwargs)
File "C:\Python27\lib\site-packages\sklearn\linear_model\ransac.py", line 261, in fit
y_subset = y[subset_idxs]
IndexError: index 199 is out of bounds for axis 0 with size 199

# Fixed code
def __init__(self):
    super(NameFinder, self).__init__()
    self.imported_names = {}
    self.accessed_names = set()
# Buggy code
def _str_references(self):
    out = []
    if self["References"]:
        out += self._str_header("References")
        if isinstance(self["References"], str):
            self["References"] = [self["References"]]
        out.extend(self["References"])
        out += [""]
        # Latex collects all references to a separate bibliography,
        # so we need to insert links to it
        if sphinx.__version__ >= "0.6":
            out += [".. only:: latex", ""]
        else:
            out += [".. latexonly::", ""]
        items = []
        for line in self["References"]:
            m = re.match(r".. \[([a-z0-9._-]+)\]", line, re.I)
            if m:
                items.append(m.group(1))
        out += ["   " + ", ".join(["[%s]_" % item for item in items]), ""]
    return out


# Traceback (IndexError)
======================================================================
ERROR: sklearn.tests.test_common.test_regressors_train('RANSACRegressor', <class 'sklearn.linear_model.ransac.RANSACRegr
essor'>, array([[-0.44836249, -0.47282444, -1.20608008, ..., -0.75500806,
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\nose\case.py", line 197, in runTest
self.test(*self.arg)
File "C:\Python27\lib\site-packages\sklearn\tests\test_common.py", line 850, in check_regressors_train
assert_raises(ValueError, regressor.fit, X, y[:-1])
File "C:\Python27\lib\unittest\case.py", line 473, in assertRaises
callableObj(*args, **kwargs)
File "C:\Python27\lib\site-packages\sklearn\linear_model\ransac.py", line 261, in fit
y_subset = y[subset_idxs]
IndexError: index 199 is out of bounds for axis 0 with size 199

# Fixed code
def _str_references(self):
    out = []
    if self["References"]:
        out += self._str_header("References")
        if isinstance(self["References"], str):
            self["References"] = [self["References"]]
        out.extend(self["References"])
        out += [""]
        # Latex collects all references to a separate bibliography,
        # so we need to insert links to it
        import sphinx  # local import to avoid test dependency

        if sphinx.__version__ >= "0.6":
            out += [".. only:: latex", ""]
        else:
            out += [".. latexonly::", ""]
        items = []
        for line in self["References"]:
            m = re.match(r".. \[([a-z0-9._-]+)\]", line, re.I)
            if m:
                items.append(m.group(1))
        out += ["   " + ", ".join(["[%s]_" % item for item in items]), ""]
    return out
# Buggy code
def wrap_mangling_directive(base_directive, objtype):
    class directive(base_directive):
        def run(self):
            env = self.state.document.settings.env

            name = None
            if self.arguments:
                m = re.match(r"^(.*\s+)?(.*?)(\(.*)?", self.arguments[0])
                name = m.group(2).strip()

            if not name:
                name = self.arguments[0]

            lines = list(self.content)
            mangle_docstrings(env.app, objtype, name, None, None, lines)
            self.content = ViewList(lines, self.content.parent)

            return base_directive.run(self)

    return directive


# Traceback (IndexError)
======================================================================
ERROR: sklearn.tests.test_common.test_regressors_train('RANSACRegressor', <class 'sklearn.linear_model.ransac.RANSACRegr
essor'>, array([[-0.44836249, -0.47282444, -1.20608008, ..., -0.75500806,
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\nose\case.py", line 197, in runTest
self.test(*self.arg)
File "C:\Python27\lib\site-packages\sklearn\tests\test_common.py", line 850, in check_regressors_train
assert_raises(ValueError, regressor.fit, X, y[:-1])
File "C:\Python27\lib\unittest\case.py", line 473, in assertRaises
callableObj(*args, **kwargs)
File "C:\Python27\lib\site-packages\sklearn\linear_model\ransac.py", line 261, in fit
y_subset = y[subset_idxs]
IndexError: index 199 is out of bounds for axis 0 with size 199

# Fixed code
def wrap_mangling_directive(base_directive, objtype):
    class directive(base_directive):
        def run(self):
            env = self.state.document.settings.env

            name = None
            if self.arguments:
                m = re.match(r"^(.*\s+)?(.*?)(\(.*)?", self.arguments[0])
                name = m.group(2).strip()

            if not name:
                name = self.arguments[0]

            lines = list(self.content)
            mangle_docstrings(env.app, objtype, name, None, None, lines)
            # local import to avoid testing dependency
            from docutils.statemachine import ViewList

            self.content = ViewList(lines, self.content.parent)

            return base_directive.run(self)

    return directive