Fit scipy model to an array of values.

        Args:
            X(`np.ndarray` or `pd.DataFrame`):  Datapoints to be estimated from. Must be 1-d

        Returns:
            None
542179
def fit(self, X, *args, **kwargs):
        

        self.constant_value = self._get_constant_value(X)

        if self.constant_value is None:
            if self.unfittable_model:
                self.model = getattr(scipy.stats, self.model_class)(*args, **kwargs)
            else:
                self.model = getattr(scipy.stats, self.model_class)(X, *args, **kwargs)

            for name in self.METHOD_NAMES:
                attribute = getattr(self.__class__, name)
                if isinstance(attribute, str):
                    setattr(self, name, getattr(self.model, attribute))

                elif attribute is None:
                    setattr(self, name, missing_method_scipy_wrapper(lambda x: x))

        else:
            self._replace_constant_methods()

        self.fitted = True
28777
def predict(self, X):
        

        if X.ndim==1: X = X[None,:]
        ps = self.model.param_array.copy()
        means = []
        stds = []
        for s in self.hmc_samples:
            if self.model._fixes_ is None:
                self.model[:] = s
            else:
                self.model[self.model._fixes_] = s
            self.model._trigger_params_changed()
            m, v = self.model.predict(X)
            means.append(m)
            stds.append(np.sqrt(np.clip(v, 1e-10, np.inf)))
        self.model.param_array[:] = ps
        self.model._trigger_params_changed()
        return means, stds
758850
def fit(self, x, y):
        
        verbose = self.verbose
        # Create temporary files
        data_file = tempfile.NamedTemporaryFile("w+b", delete=False)
        label_file = tempfile.NamedTemporaryFile("w+b", delete=False)

        start = time.time()
        raw_rules = categorical2pysbrl_data(x, y, data_file.name, label_file.name, supp=self.min_support,
                                            zmin=self.min_rule_len, zmax=self.max_rule_len, method=self.fim_method)
        if verbose > 1:
            print("Info: sbrl data files saved to %s and %s temporarily" % (data_file.name, label_file.name))
        data_file.close()
        label_file.close()
        cat_time = time.time() - start
        if verbose:
            print("Info: time for rule mining: %.4fs" % cat_time)
        n_labels = int(np.max(y)) + 1
        start = time.time()
        _model = train_sbrl(data_file.name, label_file.name, self.lambda_, eta=self.eta,
                            max_iters=self.iters, n_chains=self.n_chains, seed=self.seed,
                            alpha=self.alpha, verbose=verbose)
        train_time = time.time() - start
        if verbose:
            print("Info: training time: %.4fs" % train_time)

        # update model parameters
        self._n_classes = n_labels
        self._n_features = x.shape[1]

        # convert the raw parameters to rules
        self.from_raw(_model[0], _model[1], raw_rules)
        self._supports = self.compute_support(x, y)

        # Close the temp files
        os.unlink(data_file.name)
        os.unlink(label_file.name)
47670
def _evaluate_fits(self, x, fit_key):
        
        fit = self.fits[fit_key]
        fit_params = self._get_fit_params(np.copy(x), fit_key)
        if type(fit) == list:
            res = []
            for i in range(len(fit)):
                res.append(fit[i](fit_params))
            return np.array(res)
        else:
            return fit(fit_params)
882213
def fit(self, X, y=None):
        
        for columns, transformer in self.mapping:
            if transformer is not None:
                transformer.fit(self._get_columns(X, columns))
        return self
496199
def cumulative_distribution(self, X):
        
        self.check_fit()

        low_bounds = self.model.dataset.mean() - (5 * self.model.dataset.std())

        result = []
        for value in X:
            result.append(self.model.integrate_box_1d(low_bounds, value))

        return np.array(result)
1125515
def fit(self, X):
        
        self.centers_, self.labels_, self.sse_arr_, self.n_iter_ = \
              _kmedoids(X, self.n_clusters, self.distance, self.max_iter, self.n_trials, self.tol, self.rng)
1113095
def _fit_null(self, Y, X_base, scan_onsets=None):
        
        n_V = np.size(Y, axis=1)
        n_T = np.size(Y, axis=0)
        t_start = time.time()

        D, F, run_TRs, n_run = self._prepare_DF(
            n_T, scan_onsets=scan_onsets)
        YTY_diag = np.sum(Y * Y, axis=0)
        YTDY_diag = np.sum(Y * np.dot(D, Y), axis=0)
        YTFY_diag = np.sum(Y * np.dot(F, Y), axis=0)

        tol = self.tol
        n_iter = self.n_iter
        logger.info('Fitting null model'
                    ' for maximum {} times'.format(n_iter))

        # Add DC components capturing run-specific baselines.
        X_DC = self._gen_X_DC(run_TRs)
        X_DC, X_base, idx_DC = self._merge_DC_to_base(
            X_DC, X_base, no_DC=False)
        X_res = None
        param0 = np.zeros(n_V)
        for it in range(0, n_iter):
            if X_res is None:
                X0 = X_base
            else:
                X0 = np.concatenate((X_base, X_res), axis=1)
            n_X0 = X0.shape[1]
            X0TX0, X0TDX0, X0TFX0 = self._make_templates(D, F, X0, X0)
            X0TY, X0TDY, X0TFY = self._make_templates(D, F, X0, Y)
            res_null = scipy.optimize.minimize(
                self._loglike_AR1_null, param0, args=(
                    YTY_diag, YTDY_diag, YTFY_diag,
                    X0TX0, X0TDX0, X0TFX0, X0TY, X0TDY, X0TFY,
                    n_T, n_V, n_run, n_X0),
                method=self.optimizer, jac=True, tol=tol,
                options=self.minimize_options)
            param_change = res_null.x - param0
            param0 = res_null.x.copy()
            est_rho1_AR1_null = 2.0 / np.pi * np.arctan(param0)
            if self.auto_nuisance:
                X0TAX0 = X0TX0[None, :, :] \
                    - est_rho1_AR1_null[:, None, None] \
                    * X0TDX0[None, :, :] \
                    + est_rho1_AR1_null[:, None, None]**2 \
                    * X0TFX0[None, :, :]
                # dimension: space*#baseline*#baseline
                X0TAY = self._make_ar1_quad_form(X0TY, X0TDY, X0TFY,
                                                 est_rho1_AR1_null)
                # dimension: #baseline*space
                beta0s = np.linalg.solve(X0TAX0, X0TAY.T).T
                residuals = Y - np.dot(X_base, beta0s[:np.shape(X_base)[1], :])
                X_res = self.nureg_method(self.n_nureg_).fit_transform(
                    self.preprocess_residual(residuals))
            if np.max(np.abs(param_change)) < self.tol:
                logger.info('The change of parameters is smaller than '
                            'the tolerance value {}. Fitting is finished '
                            'after {} iterations'.format(self.tol, it + 1))
                break
        X0TAX0 = X0TX0[None, :, :] \
            - est_rho1_AR1_null[:, None, None] \
            * X0TDX0[None, :, :] \
            + est_rho1_AR1_null[:, None, None]**2 \
            * X0TFX0[None, :, :]
        # dimension: space*#baseline*#baseline
        X0TAY = self._make_ar1_quad_form(X0TY, X0TDY, X0TFY,
                                         est_rho1_AR1_null)
        # dimension: #baseline*space
        est_beta0_AR1_null = np.linalg.solve(X0TAX0, X0TAY.T).T

        YTAY = self._make_ar1_quad_form(YTY_diag, YTDY_diag, YTFY_diag,
                                        est_rho1_AR1_null)
        # dimension: space,
        YTAcorrY = YTAY - np.sum(X0TAY * est_beta0_AR1_null, axis=0)
        # dimension: space,
        est_sigma_AR1_null = (YTAcorrY / (n_T - n_X0)) ** 0.5
        if idx_DC.size > 1:
            collapsed_DC = np.sum(X0[:, idx_DC], axis=1)
            X0 = np.insert(np.delete(X0, idx_DC, axis=1), 0,
                           collapsed_DC, axis=1)
            collapsed_beta0 = np.mean(est_beta0_AR1_null[idx_DC, :], axis=0)
            est_beta0_AR1_null = np.insert(
                np.delete(est_beta0_AR1_null, idx_DC, axis=0),
                0, collapsed_beta0, axis=0)
        t_finish = time.time()
        logger.info(
            'total time of fitting: {} seconds'.format(t_finish - t_start))
        return est_beta0_AR1_null, est_sigma_AR1_null, est_rho1_AR1_null, X0
140996
def _dense_fit(self, X, strategy, missing_values, fill_value):
        """"""
        mask = _get_mask(X, missing_values)
        masked_X = ma.masked_array(X, mask=mask)

        # Mean
        if strategy == "mean":
            mean_masked = np.ma.mean(masked_X, axis=0)
            # Avoid the warning "Warning: converting a masked element to nan."
            mean = np.ma.getdata(mean_masked)
            mean[np.ma.getmask(mean_masked)] = np.nan

            return mean

        # Median
        elif strategy == "median":
            median_masked = np.ma.median(masked_X, axis=0)
            # Avoid the warning "Warning: converting a masked element to nan."
            median = np.ma.getdata(median_masked)
            median[np.ma.getmaskarray(median_masked)] = np.nan

            return median

        # Most frequent
        elif strategy == "most_frequent":
            # scipy.stats.mstats.mode cannot be used because it will no work
            # properly if the first element is masked and if its frequency
            # is equal to the frequency of the most frequent valid element
            # See https://github.com/scipy/scipy/issues/2636

            # To be able access the elements by columns
            X = X.transpose()
            mask = mask.transpose()

            if X.dtype.kind == "O":
                most_frequent = np.empty(X.shape[0], dtype=object)
            else:
                most_frequent = np.empty(X.shape[0])

            for i, (row, row_mask) in enumerate(zip(X[:], mask[:])):
                row_mask = np.logical_not(row_mask).astype(np.bool)
                row = row[row_mask]
                most_frequent[i] = _most_frequent(row, np.nan, 0)

            return most_frequent

        # Constant
        elif strategy == "constant":
            # for constant strategy, self.statistcs_ is used to store
            # fill_value in each column
            return np.full(X.shape[1], fill_value, dtype=X.dtype)
65417
def fit_transform(self, X, y=None):
        

        self.label_encoders = [None] * X.shape[1]
        self.label_maxes = [None] * X.shape[1]

        for i, col in enumerate(X.columns):
            self.label_encoders[i], self.label_maxes[i] = \
                self._get_label_encoder_and_max(X[col])

            X.loc[:, col] = X[col].fillna(NAN_INT).map(self.label_encoders[i]).fillna(0)

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

        return self.transform(X, batch_size=batch_size)
881128
def first_fit(self, train_x, train_y):
        
        train_x, train_y = np.array(train_x), np.array(train_y)

        self._x = np.copy(train_x)
        self._y = np.copy(train_y)

        self._distance_matrix = edit_distance_matrix(self._x)
        k_matrix = bourgain_embedding_matrix(self._distance_matrix)
        k_matrix[np.diag_indices_from(k_matrix)] += self.alpha

        self._l_matrix = cholesky(k_matrix, lower=True)  # Line 2

        self._alpha_vector = cho_solve((self._l_matrix, True), self._y)  # Line 3

        self._first_fitted = True
        return self
1252842
def fit(self, X, y=None):
    
    X = self._prepare_inputs(X, ensure_min_samples=2)
    M = np.cov(X, rowvar = False)
    if M.ndim == 0:
      M = 1./M
    else:
      M = np.linalg.inv(M)

    self.transformer_ = transformer_from_metric(np.atleast_2d(M))
    return self
279046
def X(self) -> Optional[Union[np.ndarray, sparse.spmatrix, ArrayView]]:
        """"""
        if self.isbacked:
            if not self.file.isopen: self.file.open()
            X = self.file['X']
            if self.isview:
                X = X[self._oidx, self._vidx]
            return X
        else:
            if self.n_obs == 1 and self.n_vars == 1:
                return self._X[0, 0]
            elif self.n_obs == 1 or self.n_vars == 1:
                X = self._X
                if issparse(self._X): X = self._X.toarray()
                return X.flatten()
            else:
                return self._X
1164104
def fit(self, X, y, **kwargs):
        
        self.estimator.fit(X, y, **kwargs)
        self.draw()
        return self
97671
def fit(self, X):
        
        logger.info('Starting RSRM')

        # Check that the regularizer value is positive
        if 0.0 >= self.lam:
            raise ValueError("Gamma parameter should be positive.")

        # Check the number of subjects
        if len(X) <= 1:
            raise ValueError("There are not enough subjects in the input "
                             "data to train the model.")

        # Check for input data sizes
        if X[0].shape[1] < self.features:
            raise ValueError(
                "There are not enough timepoints to train the model with "
                "{0:d} features.".format(self.features))

        # Check if all subjects have same number of TRs for alignment
        number_trs = X[0].shape[1]
        number_subjects = len(X)
        for subject in range(number_subjects):
            assert_all_finite(X[subject])
            if X[subject].shape[1] != number_trs:
                raise ValueError("Different number of alignment timepoints "
                                 "between subjects.")

        # Create a new random state
        self.random_state_ = np.random.RandomState(self.rand_seed)

        # Run RSRM
        self.w_, self.r_, self.s_ = self._rsrm(X)

        return self
1019134
def fit(self, X, y=None, **kwargs):
        
        X = pandas_to_numpy(X)

        random_state = check_random_state(self.random_state)
        self._enc_cluster_centroids, self._enc_map, self.labels_,\
            self.cost_, self.n_iter_ = k_modes(X,
                                               self.n_clusters,
                                               self.max_iter,
                                               self.cat_dissim,
                                               self.init,
                                               self.n_init,
                                               self.verbose,
                                               random_state,
                                               self.n_jobs)
        return self