Fit the LFDA model.

    Parameters
    ----------
    X : (n, d) array-like
        Input data.

    y : (n,) array-like
        Class labels, one per point of data.
769730
def fit(self, X, y):
    '''
    '''
    X, y = self._prepare_inputs(X, y, ensure_min_samples=2)
    unique_classes, y = np.unique(y, return_inverse=True)
    n, d = X.shape
    num_classes = len(unique_classes)

    if self.num_dims is None:
      dim = d
    else:
      if not 0 < self.num_dims <= d:
        raise ValueError('Invalid num_dims, must be in [1,%d]' % d)
      dim = self.num_dims

    if self.k is None:
      k = min(7, d - 1)
    elif self.k >= d:
      warnings.warn('Chosen k (%d) too large, using %d instead.' % (self.k,d-1))
      k = d - 1
    else:
      k = int(self.k)
    tSb = np.zeros((d,d))
    tSw = np.zeros((d,d))

    for c in xrange(num_classes):
      Xc = X[y==c]
      nc = Xc.shape[0]

      # classwise affinity matrix
      dist = pairwise_distances(Xc, metric='l2', squared=True)
      # distances to k-th nearest neighbor
      k = min(k, nc - 1)
      sigma = np.sqrt(np.partition(dist, k, axis=0)[:, k])

      local_scale = np.outer(sigma, sigma)
      with np.errstate(divide='ignore', invalid='ignore'):
        A = np.exp(-dist/local_scale)
        A[local_scale==0] = 0

      G = Xc.T.dot(A.sum(axis=0)[:,None] * Xc) - Xc.T.dot(A).dot(Xc)
      tSb += G/n + (1-nc/n)*Xc.T.dot(Xc) + _sum_outer(Xc)/n
      tSw += G/nc

    tSb -= _sum_outer(X)/n - tSw

    # symmetrize
    tSb = (tSb + tSb.T) / 2
    tSw = (tSw + tSw.T) / 2

    vals, vecs = _eigh(tSb, tSw, dim)
    order = np.argsort(-vals)[:dim]
    vals = vals[order].real
    vecs = vecs[:,order]

    if self.embedding_type == 'weighted':
       vecs *= np.sqrt(vals)
    elif self.embedding_type == 'orthonormalized':
       vecs, _ = np.linalg.qr(vecs)

    self.transformer_ = vecs.T
    return self
723250
def fit(self, x, y, *args, **kwargs):
        

        points = self._dimensionality_check(x)

        # if condition required to address backward compatibility
        if self.method in threed_krige:
            self.model = krige_methods[self.method](
                val=y,
                variogram_model=self.variogram_model,
                nlags=self.nlags,
                weight=self.weight,
                verbose=self.verbose,
                **points
            )
        else:
            self.model = krige_methods[self.method](
                z=y,
                variogram_model=self.variogram_model,
                nlags=self.nlags,
                weight=self.weight,
                verbose=self.verbose,
                **points
            )
383186
def fit_transform(self, X, y=None, **fit_params):
        
        y = column_or_1d(X, warn=True)
        _check_numpy_unicode_bug(X)
        self.classes_, X = np.unique(X, return_inverse=True)
        return X
934353
def fit(self, X):
        
        U, V = self.split_matrix(X)
        self.tau = stats.kendalltau(U, V)[0]
        self.theta = self.compute_theta()
        self.check_theta()
1272489
def fit(self, X, y=None, **fit_params):
        

        # Handle the feature names if they're None.
        if self.features_ is None:

            # If X is a data frame, get the columns off it.
            if is_dataframe(X):
                self.features_ = np.array(X.columns)

            # Otherwise create numeric labels for each column.
            else:
                _, ncols = X.shape
                self.features_ = np.arange(0, ncols)

        return self
135053
def fit(self, X):
        
        D = self._initialize(X)
        for i in range(self.max_iter):
            gamma = self._transform(D, X)
            e = np.linalg.norm(X - gamma.dot(D))
            if e < self.tol:
                break
            D, gamma = self._update_dict(X, D, gamma)

        self.components_ = D
        return self
167683
def fit(self):
        
        # solve for estimator of B
        n,p          = np.shape(self._X)
        self._df     = float(n - p)
        self._Cx     = np.linalg.pinv(np.dot(self._X.T,self._X))
        self._Bhat   = np.dot(np.dot(self._Cx, self._X.T), self._A)
        self._Y_rec  = self._compute_prediction(self._X)
864355
def predict_y(self, xq, sigma=None, k=None, **kwargs):
        
        sigma = sigma or self.sigma
        k = k or self.k
        dists, index = self.dataset.nn_x(xq, k = k)
        w = self._weights(dists, sigma*sigma)
        return np.sum([wi*self.dataset.get_y(idx) for wi, idx in zip(w, index)], axis = 0)
1164104
def fit(self, X, y, **kwargs):
        
        self.estimator.fit(X, y, **kwargs)
        self.draw()
        return self
697382
def fit_select_best(X, y):
    
    models = [fit(X,y) for fit in [fit_linear, fit_quadratic]]
    errors = map(lambda model: mse(y, model.predict(X)), models)

    return min(zip(models, errors), key=itemgetter(1))[0]
623260
def infer_x(self, y):
        
        OptimizedInverseModel.infer_x(self, y)
        if self.fmodel.size() == 0:
            return self._random_x()

        x_guesses = [self._guess_x_simple(y)[0]]

        result = []
        for xg in x_guesses:
            res = cma.fmin(self._error, xg, self.cmaes_sigma,
                           options={'bounds':[self.lower, self.upper],
                           'verb_log':0,
                           'verb_disp':False,
                           'maxfevals':self.maxfevals,
                           'seed': self.seed})
            result.append((res[1], res[0]))

        return [xi for fi, xi in sorted(result)]
1329533
def fit(self, X, y):
    
    X, labels = self._prepare_inputs(X, y, ensure_min_samples=2)
    n, d = X.shape
    num_dims = self.num_dims
    if num_dims is None:
        num_dims = d

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

    # Initialize A to a scaling matrix
    A = np.zeros((num_dims, d))
    np.fill_diagonal(A, 1./(np.maximum(X.max(axis=0)-X.min(axis=0), EPS)))

    # Run NCA
    mask = labels[:, np.newaxis] == labels[np.newaxis, :]
    optimizer_params = {'method': 'L-BFGS-B',
                        'fun': self._loss_grad_lbfgs,
                        'args': (X, mask, -1.0),
                        'jac': True,
                        'x0': A.ravel(),
                        'options': dict(maxiter=self.max_iter),
                        'tol': self.tol
                        }

    # Call the optimizer
    self.n_iter_ = 0
    opt_result = minimize(**optimizer_params)

    self.transformer_ = opt_result.x.reshape(-1, X.shape[1])
    self.n_iter_ = opt_result.nit

    # 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 opt_result.success:
        warnings.warn('[{}] NCA did not converge: {}'.format(
            cls_name, opt_result.message), ConvergenceWarning)

      print('[{}] Training took {:8.2f}s.'.format(cls_name, train_time))

    return self
710489
def fit_predict(self,
                    X,
                    num_epochs=10,
                    updates_epoch=10,
                    stop_param_updates=dict(),
                    batch_size=1,
                    show_progressbar=False):
        """"""
        self.fit(X,
                 num_epochs,
                 updates_epoch,
                 stop_param_updates,
                 batch_size,
                 show_progressbar)

        return self.predict(X, batch_size=batch_size)
415143
def partial_fit(self, X):
        
        from pyemma.coordinates import source

        self._estimate(source(X), partial_fit=True)
        self._estimated = True

        return self
319131
def _fit_bmr_model(self, X, y):
        """"""
        self.f_bmr = BayesMinimumRiskClassifier()
        X_bmr = self.predict_proba(X)
        self.f_bmr.fit(y, X_bmr)
        return self
168856
def fit(self, X, y=None):
        
        if self.normalize:
            X = normalize(X)

        self._check_force_weights()
        random_state = check_random_state(self.random_state)
        X = self._check_fit_data(X)

        (
            self.cluster_centers_,
            self.labels_,
            self.inertia_,
            self.weights_,
            self.concentrations_,
            self.posterior_,
        ) = movMF(
            X,
            self.n_clusters,
            posterior_type=self.posterior_type,
            force_weights=self.force_weights,
            n_init=self.n_init,
            n_jobs=self.n_jobs,
            max_iter=self.max_iter,
            verbose=self.verbose,
            init=self.init,
            random_state=random_state,
            tol=self.tol,
            copy_x=self.copy_x,
        )

        return self
468556
def infer_x(self, y_desired, **kwargs):
        
        
        sigma = kwargs.get('sigma', self.sigma)
        k     = kwargs.get('k', self.k)
         
        xq = self._guess_x(y_desired, k = k, sigma = sigma, **kwargs)[0]    
         
        dists, index = self.fmodel.dataset.nn_x(xq, k = k)

        w = self.fmodel._weights(dists, sigma*sigma)
        
        X   = np.array([self.fmodel.dataset.get_x_padded(i) for i in index])
        Y    = np.array([self.fmodel.dataset.get_y(i) for i in index])
         
        W   = np.diag(w)
        WX  = np.dot(W, X)
        WXT = WX.T
             
        B   = np.dot(np.linalg.pinv(np.dot(WXT, WX)),WXT)
        
        M = np.dot(B, np.dot(W, Y))
        
        _, idx = self.fmodel.dataset.nn_y(y_desired, k=1)        
        ynn = self.fmodel.dataset.get_y(idx[0])
        
        eps = 0.00001
        
        J = np.zeros((len(xq),len(y_desired)), dtype = np.float64)
        for i in range(len(xq)):
            xi = np.array(xq, dtype = np.float64)
            xi[i] = xi[i] + eps
            yi = np.dot(np.append(1.0, xi), M).ravel()
            J[i] = (yi - ynn) / eps
        J = np.transpose(J)
        Jinv = np.linalg.pinv(J)
        x = np.dot(Jinv, y_desired - ynn)
        
        return [x]