Fit function for fitters.
552008
def _fit(
        self,
        minimizing_function_args,
        iterative_fitting,
        initial_params,
        params_size,
        disp,
        tol=1e-6,
        fit_method="Nelder-Mead",
        maxiter=2000,
        **kwargs
    ):
        """"""
        ll = []
        sols = []

        if iterative_fitting <= 0:
            raise ValueError("iterative_fitting parameter should be greater than 0 as of lifetimes v0.2.1")

        if iterative_fitting > 1 and initial_params is not None:
            raise ValueError(
                "iterative_fitting and initial_params should not be both set, as no improvement could be made."
            )

        # set options for minimize, if specified in kwargs will be overwritten
        minimize_options = {}
        minimize_options["disp"] = disp
        minimize_options["maxiter"] = maxiter
        minimize_options.update(kwargs)

        total_count = 0
        while total_count < iterative_fitting:
            current_init_params = (
                np.random.normal(1.0, scale=0.05, size=params_size) if initial_params is None else initial_params
            )
            if minimize_options["disp"]:
                print("Optimize function with {}".format(fit_method))

            output = minimize(
                self._negative_log_likelihood,
                method=fit_method,
                tol=tol,
                x0=current_init_params,
                args=minimizing_function_args,
                options=minimize_options,
            )
            sols.append(output.x)
            ll.append(output.fun)

            total_count += 1
        argmin_ll, min_ll = min(enumerate(ll), key=lambda x: x[1])
        minimizing_params = sols[argmin_ll]
        return minimizing_params, min_ll
1201929
def apply_fit(xy,coeffs):
    
    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]
    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]

    return x_new,y_new
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)
1032425
def fit_transform(self, X, y, step_size=0.1, init_weights=None, warm_start=False):
        """"""
        self.fit(X=X, y=y, step_size=step_size, init_weights=init_weights, warm_start=warm_start)

        return self.transform(X=X)
671189
def fit(self, X, y=None):
        
        X = self._check_array(X)

        if self.categories is not None:
            # some basic validation
            columns = pd.Index(self.categories)
            categories = self.categories

        elif isinstance(X, pd.DataFrame):
            columns, categories = self._fit(X)
        else:
            columns, categories = self._fit_dask(X)

        self.columns_ = columns
        self.categories_ = categories
        return self
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
920503
def _fit(self, index, width, height):
        """"""
        node = self._atlas_nodes[index]
        x, y = node[0], node[1]
        width_left = width
        if x+width > self._shape[1]:
            return -1
        i = index
        while width_left > 0:
            node = self._atlas_nodes[i]
            y = max(y, node[1])
            if y+height > self._shape[0]:
                return -1
            width_left -= node[2]
            i += 1
        return y
1003318
def show_fit(w_fit, C_fit, r_fit, Xs):
    '''
    '''

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    
    # Plot the data points
    
    ax.scatter([X[0] for X in Xs], [X[1] for X in Xs], [X[2] for X in Xs])
   
    # Get the transformation matrix

    theta = np.arccos(np.dot(w_fit, np.array([0, 0, 1])))
    phi = np.arctan2(w_fit[1], w_fit[0])

    M = np.dot(rotation_matrix_from_axis_and_angle(np.array([0, 0, 1]), phi),
               rotation_matrix_from_axis_and_angle(np.array([0, 1, 0]), theta))

    # Plot the cylinder surface
   
    delta = np.linspace(-np.pi, np.pi, 20)
    z = np.linspace(-10, 10, 20)

    Delta, Z = np.meshgrid(delta, z)
    X = r_fit * np.cos(Delta)
    Y = r_fit * np.sin(Delta)

    for i in range(len(X)):
        for j in range(len(X[i])):
            p = np.dot(M, np.array([X[i][j], Y[i][j], Z[i][j]])) + C_fit

            X[i][j] = p[0]
            Y[i][j] = p[1]
            Z[i][j] = p[2]

    ax.plot_surface(X, Y, Z, alpha=0.2)

    # Plot the center and direction

    ax.quiver(C_fit[0], C_fit[1], C_fit[2], 
            r_fit * w_fit[0], r_fit * w_fit[1], r_fit * w_fit[2], color='red')


    plt.show()
324341
private void fitParameters(Map<Long, Double> metricData) {
        mean = getMetricMean(metricData);
        variance = getMetricVariance(metricData);
    }
1209321
def fit(self, X, y, **fit_params):
        
        # pylint: disable=useless-super-delegation
        # this is actually a pylint bug:
        # https://github.com/PyCQA/pylint/issues/1085
        return super().fit(X, y, **fit_params)
1329668
def fit_all(xy,uv,mode='rscale',center=None,verbose=True):
    
    if mode not in ['general', 'shift', 'rscale']:
        mode = 'rscale'
    if not isinstance(xy,np.ndarray):
        # cast input list as numpy ndarray for fitting
        xy = np.array(xy)
    if not isinstance(uv,np.ndarray):
        # cast input list as numpy ndarray for fitting
        uv = np.array(uv)

    if mode == 'shift':
        logstr = 'Performing "shift" fit'
        if verbose:
            print(logstr)
        else:
            log.info(logstr)
        result = fit_shifts(xy, uv)

    elif mode == 'general':
        logstr = 'Performing "general" fit'
        if verbose:
            print(logstr)
        else:
            log.info(logstr)
        result = fit_general(xy, uv)

    else:
        logstr = 'Performing "rscale" fit'
        if verbose:
            print(logstr)
        else:
            log.info(logstr)
        result = geomap_rscale(xy, uv, center=center)

    return result
343545
def report_fit(self):
        
        if not self.fitted:
            print('Model not yet fit.')
            return

        print('R-Squared: {0:.3f}'.format(self.model_fit.rsquared))
        print('Adj. R-Squared: {0:.3f}'.format(self.model_fit.rsquared_adj))
        print('')

        tbl = PrettyTable(
            ['Component', ])
        tbl = PrettyTable()

        tbl.add_column('Component', self.fit_parameters.index.values)
        for col in ('Coefficient', 'Std. Error', 'T-Score'):
            tbl.add_column(col, self.fit_parameters[col].values)

        tbl.align['Component'] = 'l'
        tbl.float_format = '.3'

        print(tbl)
206066
def manage_fits(list_of_frame):
    """"""

    import astropy.io.fits as fits
    import numina.types.dataframe as df

    refs = []
    for frame in list_of_frame:
        if isinstance(frame, str):
            ref = fits.open(frame)
            refs.append(ref)
        elif isinstance(frame, fits.HDUList):
            refs.append(frame)
        elif isinstance(frame, df.DataFrame):
            ref = frame.open()
            refs.append(ref)
        else:
            refs.append(frame)
    try:
        yield refs
    finally:
        # release
        for obj in refs:
            obj.close()
1056799
def fitness_vs(self, v):
        """"""
        base = self._base
        if base._classifier:
            if base._multiple_outputs:
                v.fitness_vs = v._error
                # if base._fitness_function == 'macro-F1':
                #     v.fitness_vs = v._error
                # elif base._fitness_function == 'BER':
                #     v.fitness_vs = v._error
                # elif base._fitness_function == 'macro-Precision':
                #     v.fitness_vs = v._error
                # elif base._fitness_function == 'accDotMacroF1':
                #     v.fitness_vs = v._error
                # elif base._fitness_function == 'macro-RecallF1':
                #     v.fitness_vs = v._error
                # elif base._fitness_function == 'F1':
                #     v.fitness_vs = v._error
                # else:
                #     v.fitness_vs = - v._error.dot(base._mask_vs) / base._mask_vs.sum()
            else:
                v.fitness_vs = -((base.y - v.hy.sign()).sign().fabs() *
                                 base._mask_vs).sum()
        else:
            mask = base._mask
            y = base.y
            hy = v.hy
            if not isinstance(mask, list):
                mask = [mask]
                y = [y]
                hy = [hy]
            fit = []
            for _mask, _y, _hy in zip(mask, y, hy):
                m = (_mask + -1).fabs()
                x = _y * m
                y = _hy * m
                a = (x - y).sq().sum()
                b = (x + -x.sum() / x.size()).sq().sum()
                fit.append(-a / b)
            v.fitness_vs = np.mean(fit)
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()
742312
def proper(self,x):
        """"""
        x[x < 0] = self.max_fit
        x[np.isnan(x)] = self.max_fit
        x[np.isinf(x)] = self.max_fit
        return x
11801
def fit(self, X, y=None):
        
        return self.partial_fit(np.concatenate(X, axis=0))