当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.NotFittedError方法代码示例

本文整理汇总了Python中sklearn.exceptions.NotFittedError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.NotFittedError方法的具体用法?Python exceptions.NotFittedError怎么用?Python exceptions.NotFittedError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sklearn.exceptions的用法示例。


在下文中一共展示了exceptions.NotFittedError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_elliptic_envelope

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def test_elliptic_envelope():
    rnd = np.random.RandomState(0)
    X = rnd.randn(100, 10)
    clf = EllipticEnvelope(contamination=0.1)
    assert_raises(NotFittedError, clf.predict, X)
    assert_raises(NotFittedError, clf.decision_function, X)
    clf.fit(X)
    y_pred = clf.predict(X)
    scores = clf.score_samples(X)
    decisions = clf.decision_function(X)

    assert_array_almost_equal(
        scores, -clf.mahalanobis(X))
    assert_array_almost_equal(clf.mahalanobis(X), clf.dist_)
    assert_almost_equal(clf.score(X, np.ones(100)),
                        (100 - y_pred[y_pred == -1].size) / 100.)
    assert(sum(y_pred == -1) == sum(decisions < 0)) 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:19,代码来源:test_elliptic_envelope.py

示例2: diff_op

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def diff_op(self):
        """The diffusion operator calculated from the data
        """
        if self.graph is not None:
            if isinstance(self.graph, graphtools.graphs.LandmarkGraph):
                diff_op = self.graph.landmark_op
            else:
                diff_op = self.graph.diff_op
            if sparse.issparse(diff_op):
                diff_op = diff_op.toarray()
            return diff_op
        else:
            raise NotFittedError(
                "This PHATE instance is not fitted yet. Call "
                "'fit' with appropriate arguments before "
                "using this method."
            ) 
开发者ID:KrishnaswamyLab,项目名称:PHATE,代码行数:19,代码来源:phate.py

示例3: test_keras_autoencoder_scoring

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def test_keras_autoencoder_scoring(model, kind, n_features_out):
    """
    Test the KerasAutoEncoder and KerasLSTMAutoEncoder have a working scoring function
    """
    Model = pydoc.locate(f"gordo.machine.model.models.{model}")
    model = Pipeline([("model", Model(kind=kind))])
    X = np.random.random((8, 2))

    # Should be able to deal with y output different than X input features
    y = np.random.random((8, n_features_out))

    with pytest.raises(NotFittedError):
        model.score(X, y)

    model.fit(X, y)
    score = model.score(X, y)
    logger.info(f"Score: {score:.4f}") 
开发者ID:equinor,项目名称:gordo,代码行数:19,代码来源:test_model.py

示例4: test_notfitted

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def test_notfitted():
    eclf = VotingClassifier(estimators=[('lr1', LogisticRegression()),
                                        ('lr2', LogisticRegression())],
                            voting='soft')
    ereg = VotingRegressor([('dr', DummyRegressor())])
    msg = ("This %s instance is not fitted yet. Call \'fit\'"
           " with appropriate arguments before using this method.")
    assert_raise_message(NotFittedError, msg % 'VotingClassifier',
                         eclf.predict, X)
    assert_raise_message(NotFittedError, msg % 'VotingClassifier',
                         eclf.predict_proba, X)
    assert_raise_message(NotFittedError, msg % 'VotingClassifier',
                         eclf.transform, X)
    assert_raise_message(NotFittedError, msg % 'VotingRegressor',
                         ereg.predict, X_r)
    assert_raise_message(NotFittedError, msg % 'VotingRegressor',
                         ereg.transform, X_r) 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:19,代码来源:test_voting.py

示例5: test_gaussian_mixture_predict_predict_proba

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def test_gaussian_mixture_predict_predict_proba():
    rng = np.random.RandomState(0)
    rand_data = RandomData(rng)
    for covar_type in COVARIANCE_TYPE:
        X = rand_data.X[covar_type]
        Y = rand_data.Y
        g = GaussianMixture(n_components=rand_data.n_components,
                            random_state=rng, weights_init=rand_data.weights,
                            means_init=rand_data.means,
                            precisions_init=rand_data.precisions[covar_type],
                            covariance_type=covar_type)

        # Check a warning message arrive if we don't do fit
        assert_raise_message(NotFittedError,
                             "This GaussianMixture instance is not fitted "
                             "yet. Call 'fit' with appropriate arguments "
                             "before using this method.", g.predict, X)

        g.fit(X)
        Y_pred = g.predict(X)
        Y_pred_proba = g.predict_proba(X).argmax(axis=1)
        assert_array_equal(Y_pred, Y_pred_proba)
        assert_greater(adjusted_rand_score(Y, Y_pred), .95) 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:25,代码来源:test_gaussian_mixture.py

示例6: transform

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def transform(self, df: pd.DataFrame) -> Union[sparse_matrix, np.ndarray]:
        try:
            self.one_hot_enc.categories_
        except:
            raise NotFittedError(
                "This WidePreprocessor instance is not fitted yet. "
                "Call 'fit' with appropriate arguments before using this estimator."
            )
        df_wide = df.copy()[self.wide_cols]
        if self.crossed_cols is not None:
            df_wide, _ = self._cross_cols(df_wide)
        if self.already_dummies:
            X_oh_1 = df_wide[self.already_dummies].values
            dummy_cols = [
                c for c in self.wide_crossed_cols if c not in self.already_dummies
            ]
            X_oh_2 = self.one_hot_enc.transform(df_wide[dummy_cols])
            return np.hstack((X_oh_1, X_oh_2))
        else:
            return self.one_hot_enc.transform(df_wide[self.wide_crossed_cols]) 
开发者ID:jrzaurin,项目名称:pytorch-widedeep,代码行数:22,代码来源:_preprocessors.py

示例7: transform

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def transform(self, X, y=None):
        """Binarize X based on the fitted cut points."""

        # scikit-learn checks
        X = check_array(X)

        if self.cut_points is None:
            raise NotFittedError('Estimator not fitted, call `fit` before exploiting the model.')

        if X.shape[1] != len(self.cut_points):
            raise ValueError("Provided array's dimensions do not match with the ones from the "
                             "array `fit` was called on.")

        binned = np.array([
            np.digitize(x, self.cut_points[i])
            if len(self.cut_points[i]) > 0
            else np.zeros(x.shape)
            for i, x in enumerate(X.T)
        ]).T

        return binned 
开发者ID:MaxHalford,项目名称:xam,代码行数:23,代码来源:base.py

示例8: _compute_output

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def _compute_output(self, X):
        """Get the outputs of the network, for use in prediction methods."""

        if not self._is_fitted:
            raise NotFittedError("Call fit before prediction")

        X = self._check_X(X)

        # Make predictions in batches.
        pred_batches = []
        start_idx = 0
        n_examples = X.shape[0]
        with self.graph_.as_default():
            while start_idx < n_examples:
                X_batch = \
                    X[start_idx:min(start_idx + self.batch_size, n_examples)]
                feed_dict = self._make_feed_dict(X_batch)
                start_idx += self.batch_size
                pred_batches.append(
                    self._session.run(self.output_layer_, feed_dict=feed_dict))
        y_pred = np.concatenate(pred_batches)
        return y_pred 
开发者ID:civisanalytics,项目名称:muffnn,代码行数:24,代码来源:base.py

示例9: predict_log_proba

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def predict_log_proba(self, X):
        """Compute log p(y=1).

        Parameters
        ----------
        X : numpy array or sparse matrix [n_samples, n_features]
            Data.

        Returns
        -------
        numpy array [n_samples]
            Log probabilities.
        """
        if not self._is_fitted:
            raise NotFittedError("Call fit before predict_log_proba!")
        return np.log(self.predict_proba(X)) 
开发者ID:civisanalytics,项目名称:muffnn,代码行数:18,代码来源:fm_classifier.py

示例10: predict

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def predict(self, X):
        """Compute the predicted class.

        Parameters
        ----------
        X : numpy array or sparse matrix [n_samples, n_features]
            Data.

        Returns
        -------
        numpy array [n_samples]
            Predicted class.
        """
        if not self._is_fitted:
            raise NotFittedError("Call fit before predict!")
        return self.classes_[self.predict_proba(X).argmax(axis=1)] 
开发者ID:civisanalytics,项目名称:muffnn,代码行数:18,代码来源:fm_classifier.py

示例11: _fit_models

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def _fit_models(vmodel, tmodel, x, model_is_fit):
    if model_is_fit==True:
        return
    if vmodel is not None:
        try:
            check_is_fitted(vmodel, ['vocabulary_'])
        except NotFittedError:
            vmodel.fit(np.vstack(x).ravel())
    if tmodel is not None:
        try:
            check_is_fitted(tmodel, ['components_'])
        except NotFittedError:
            if isinstance(tmodel, Pipeline):
                tmodel.fit(np.vstack(x).ravel())
            else:
                tmodel.fit(vmodel.transform(np.vstack(x).ravel())) 
开发者ID:ContextLab,项目名称:hypertools,代码行数:18,代码来源:text2mat.py

示例12: test_event_transfer

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def test_event_transfer():
    es = EventSegment(2)
    sample_data = np.asarray([[1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1]])

    with pytest.raises(NotFittedError):
        seg = es.find_events(sample_data.T)[0]
        pytest.fail("Should need to set variance")

    with pytest.raises(NotFittedError):
        seg = es.find_events(sample_data.T, np.asarray([1, 1]))[0]
        pytest.fail("Should need to set patterns")

    es.set_event_patterns(np.asarray([[1, 0], [0, 1]]))
    seg = es.find_events(sample_data.T, np.asarray([1, 1]))[0]

    events = np.argmax(seg, axis=1)
    assert np.array_equal(events, [0, 0, 0, 1, 1, 1, 1]),\
        "Failed to correctly transfer two events to new data" 
开发者ID:brainiak,项目名称:brainiak,代码行数:20,代码来源:test_event.py

示例13: test_stack_copy_function_only_model

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def test_stack_copy_function_only_model(self):
        first_layer = Layer([LinearRegression(), LogisticRegression()])
        second_layer = Layer([LinearRegression()])
        model = Stack([first_layer, second_layer])

        X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
        y = np.dot(X, np.array([1, 2])) + 3
        model.fit(X, y)
        model2 = model.copy()
        gotError = False
        try:
            model2.predict([1, 2])
        except(NotFittedError):
            gotError = True

        assert gotError, "Model failed the copy Test: When copying, a deep copy was produced" 
开发者ID:picknmix,项目名称:picknmix,代码行数:18,代码来源:test_stack.py

示例14: test_stack_copy_function_model_and_preprocessor

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def test_stack_copy_function_model_and_preprocessor(self):
        first_layer = Layer(models=[LogisticRegression(), LinearRegression()], preprocessors=[MinMaxScaler(), None])
        second_layer = Layer([LinearRegression()], preprocessors=[MinMaxScaler()])
        model = Stack([first_layer, second_layer])

        X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
        y = np.dot(X, np.array([1, 2])) + 3
        model.fit(X, y)
        model2 = model.copy()
        gotError = False
        try:
            model2.predict([1,2])
        except(NotFittedError):
            gotError = True

        assert gotError, "Model failed the copy Test: When copying, a deep copy was produced" 
开发者ID:picknmix,项目名称:picknmix,代码行数:18,代码来源:test_stack.py

示例15: test_nested_model

# 需要导入模块: from sklearn import exceptions [as 别名]
# 或者: from sklearn.exceptions import NotFittedError [as 别名]
def test_nested_model(teardown):
    x_data = iris.data
    y_t_data = iris.target

    # Sub-model
    x = Input()
    y_t = Input()
    h = PCA(n_components=2)(x)
    y = LogisticRegression()(h, y_t)
    submodel = Model(x, y, y_t)

    # Model
    x = Input()
    y_t = Input()
    y = submodel(x, y_t)
    model = Model(x, y, y_t)

    with raises_with_cause(RuntimeError, NotFittedError):
        submodel.predict(x_data)

    model.fit(x_data, y_t_data)
    y_pred = model.predict(x_data)
    y_pred_sub = submodel.predict(x_data)

    assert_array_equal(y_pred, y_pred_sub) 
开发者ID:alegonz,项目名称:baikal,代码行数:27,代码来源:test_model.py


注:本文中的sklearn.exceptions.NotFittedError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。