Beispiel #1
0
def test__check_n_components():
    """Checks that n_components returns what is expected
  (including the errors)"""
    dim = _check_n_components(5, None)
    assert dim == 5

    dim = _check_n_components(5, 3)
    assert dim == 3

    with pytest.raises(ValueError) as expected_err:
        _check_n_components(5, 10)
    assert str(expected_err.value) == 'Invalid n_components, must be in [1, 5]'

    with pytest.raises(ValueError) as expected_err:
        _check_n_components(5, 0)
    assert str(expected_err.value) == 'Invalid n_components, must be in [1, 5]'
Beispiel #2
0
    def fit(self, X, y):
        """
      Fit MLKR model

      Parameters
      ----------
      X : (n x d) array of samples
      y : (n) data labels
      """
        if self.A0 != 'deprecated':
            warnings.warn(
                '"A0" parameter is not used.'
                ' It has been deprecated in version 0.5.0 and will be'
                'removed in 0.6.0. Use "init" instead.', DeprecationWarning)

        if self.num_dims != 'deprecated':
            warnings.warn(
                '"num_dims" parameter is not used.'
                ' It has been deprecated in version 0.5.0 and will be'
                ' removed in 0.6.0. Use "n_components" instead',
                DeprecationWarning)

        X, y = self._prepare_inputs(X, y, y_numeric=True, ensure_min_samples=2)
        n, d = X.shape
        if y.shape[0] != n:
            raise ValueError('Data and label lengths mismatch: %d != %d' %
                             (n, y.shape[0]))

        m = _check_n_components(d, self.n_components)
        m = self.n_components
        if m is None:
            m = d
        # if the init is the default (None), we raise a warning
        if self.init is None:
            # TODO:
            #  replace init=None by init='auto' in v0.6.0 and remove the warning
            msg = (
                "Warning, no init was set (`init=None`). As of version 0.5.0, "
                "the default init will now be set to 'auto', instead of 'pca'. "
                "If you still want to use PCA as an init, set init='pca'. "
                "This warning will disappear in v0.6.0, and `init` parameter's"
                " default value will be set to 'auto'.")
            warnings.warn(msg, ChangedBehaviorWarning)
            init = 'auto'
        else:
            init = self.init
        A = _initialize_components(
            m,
            X,
            y,
            init=init,
            random_state=self.random_state,
            # MLKR works on regression targets:
            has_classes=False)

        # Measure the total training time
        train_time = time.time()

        self.n_iter_ = 0
        res = minimize(self._loss,
                       A.ravel(), (X, y),
                       method='L-BFGS-B',
                       jac=True,
                       tol=self.tol,
                       options=dict(maxiter=self.max_iter))
        self.components_ = res.x.reshape(A.shape)

        # Stop timer
        train_time = time.time() - train_time
        if self.verbose:
            cls_name = self.__class__.__name__
            # Warn the user if the algorithm did not converge
            if not res.success:
                warnings.warn(
                    '[{}] MLKR did not converge: {}'.format(
                        cls_name, res.message), ConvergenceWarning)
            print('[{}] Training took {:8.2f}s.'.format(cls_name, train_time))

        return self