wdm0006/sklearn-extensions · elm.py
python logo
def fit(self, X, y):
        """
        Fit the model using X, y as training data.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape [n_samples, n_features]
            Training vectors, where n_samples is the number of samples
            and n_features is the number of features.

        y : array-like of shape [n_samples, n_outputs]
            Target values (class labels in classification, real numbers in
            regression)

        Returns
        -------
        self : object

            Returns an instance of self.
        """
        rhl = self._create_random_layer()
        self._genelm_regressor = GenELMRegressor(hidden_layer=rhl,
                                                 regressor=self.regressor)
        self._genelm_regressor.fit(X, y)
        return self
Similar code snippets
1.
mattjj/pyslds · util.py
Match rating: 58.89% · See similar code snippets
python logo
def regression_logprior(regression):
    if isinstance(regression, DiagonalRegression):
        return diag_regression_logprior(regression)
    elif isinstance(regression, Regression):
        return dense_regression_logprior(regression)
2.
bsolomon1124/pyfinance · general.py
Match rating: 55.0% · See similar code snippets
python logo
def variance_inflation_factor(regressors, hasconst=False):
    """Calculate variance inflation factor (VIF) for each all `regressors`.

    A wrapper/modification of statsmodels:
    statsmodels.stats.outliers_influence.variance_inflation_factor

    One recommendation is that if VIF is greater than 5, then the explanatory
    variable `x` is highly collinear with the other explanatory
    variables, and the parameter estimates will have large standard errors
    because of this. [source: StatsModels]

    Parameters
    ----------
    regressors: DataFrame
        DataFrame containing the entire set of regressors
    hasconst : bool, default False
        If False, a column vector will be added to `regressors` for use in
        OLS

    Example
    -------
    # Generate some data
    from datetime import date
    from pandas_datareader.data import DataReader as dr

    syms = {'TWEXBMTH' : 'usd',
            'T10Y2YM' : 'term_spread',
            'PCOPPUSDM' : 'copper'
           }
    start = date(2000, 1, 1)
    data = (dr(syms.keys(), 'fred', start)
            .pct_change()
            .dropna())
    data = data.rename(columns = syms)

    print(variance_inflation_factor(data))
    usd            1.31609
    term_spread    1.03793
    copper         1.37055
    dtype: float64
    """

    if not hasconst:
        regressors = add_constant(regressors, prepend=False)
    k = regressors.shape[1]

    def vif_sub(x, regressors):
        x_i = regressors.iloc[:, x]
        mask = np.arange(k) != x
        x_not_i = regressors.iloc[:, mask]
        rsq = linear_model.OLS(x_i, x_not_i, missing="drop").fit().rsquared_adj
        vif = 1.0 / (1.0 - rsq)
        return vif

    vifs = pd.Series(np.arange(k), index=regressors.columns)
    vifs = vifs.apply(vif_sub, args=(regressors,))

    # Find the constant column (probably called 'const', but not necessarily
    # and drop it. `is_nonzero_const` borrowed from statsmodels.add_constant
    is_nonzero_const = np.ptp(regressors.values, axis=0) == 0
    is_nonzero_const &= np.all(regressors != 0.0, axis=0)
    vifs.drop(vifs.index[is_nonzero_const], inplace=True)
    return vifs
3.
tmoerman/arboreto · core.py
Match rating: 53.3% · See similar code snippets
python logo
def to_feature_importances(regressor_type,
                           regressor_kwargs,
                           trained_regressor):
    """
    Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing
    by the number of trees in the regression ensemble by multiplying again by the number of trees used.

    This enables prioritizing links that were inferred in a regression where lots of

    :param regressor_type: string. Case insensitive.
    :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor.
    :param trained_regressor: the trained model from which to extract the feature importances.
    :return: the feature importances inferred from the trained model.
    """

    if is_oob_heuristic_supported(regressor_type, regressor_kwargs):
        n_estimators = len(trained_regressor.estimators_)

        denormalized_importances = trained_regressor.feature_importances_ * n_estimators

        return denormalized_importances
    else:
        return trained_regressor.feature_importances_
4.
tknapen/FIRDeconvolution · FIRDeconvolution.py
Match rating: 51.01% · See similar code snippets
python logo
def add_continuous_regressors_to_design_matrix(self, regressors):
        """add_continuous_regressors_to_design_matrix appends continuously sampled regressors to the existing design matrix. One uses this addition to the design matrix when one expects the data to contain nuisance factors that aren't tied to the moments of specific events. For instance, in fMRI analysis this allows us to add cardiac / respiratory regressors, as well as tissue and head motion timecourses to the designmatrix.
        
            :param regressors: the signal to be appended to the design matrix.
            :type regressors: numpy array, with shape equal to (nr_regressors, self.resampled_signal.shape[-1])
        """
        previous_design_matrix_shape = self.design_matrix.shape
        if len(regressors.shape) == 1:
            regressors = regressors[np.newaxis, :]
        if regressors.shape[1] != self.resampled_signal.shape[1]:
            self.logger.warning('additional regressor shape %s does not conform to designmatrix shape %s' % (regressors.shape, self.resampled_signal.shape))
        # and, an vstack append
        self.design_matrix = np.vstack((self.design_matrix, regressors))
        self.logger.debug('added %s continuous regressors to %s design_matrix, shape now %s' % (str(regressors.shape), str(previous_design_matrix_shape), str(self.design_matrix.shape)))
5.
Qiskit/qiskit-terra · matplotlib.py
Match rating: 49.46% · See similar code snippets
python logo
def _draw_regs(self):
        # quantum register
        for ii, reg in enumerate(self._qreg):
            if len(self._qreg) > 1:
                label = '${}_{{{}}}$'.format(reg.reg.name, reg.index)
            else:
                label = '${}$'.format(reg.reg.name)

            pos = -ii
            self._qreg_dict[ii] = {
                'y': pos,
                'label': label,
                'index': reg.index,
                'group': reg.reg
            }
            self._cond['n_lines'] += 1
        # classical register
        if self._creg:
            n_creg = self._creg.copy()
            n_creg.pop(0)
            idx = 0
            y_off = -len(self._qreg)
            for ii, (reg, nreg) in enumerate(itertools.zip_longest(
                    self._creg, n_creg)):
                pos = y_off - idx
                if self._style.bundle:
                    label = '${}$'.format(reg.reg.name)
                    self._creg_dict[ii] = {
                        'y': pos,
                        'label': label,
                        'index': reg.index,
                        'group': reg.reg
                    }
                    if not (not nreg or reg.reg != nreg.reg):
                        continue
                else:
                    label = '${}_{{{}}}$'.format(reg.reg.name, reg.index)
                    self._creg_dict[ii] = {
                        'y': pos,
                        'label': label,
                        'index': reg.index,
                        'group': reg.reg
                    }

                self._cond['n_lines'] += 1
                idx += 1
6.
kata198/indexedredis · compressed.py
Match rating: 48.61% · See similar code snippets
python logo
def __init__(self, name='', compressMode=COMPRESS_MODE_ZLIB, defaultValue=irNull):
		'''
			__init__ - Create this object

			@param name <str> - Field name
			@param compressMode <str>, default "zlib". Determines the compression module to use
			  for this field. See COMPRESS_MODE_* variables in this module.

			  Supported values as of 5.0.0 are:

			     "zlib" / "gz" / "gzip" - zlib compression

			     "bz2"  / "bzip2"       - bzip2 compression

			     "lzma" / "xz"          - LZMA compression.
			       NOTE: This is provided in python3 by default, but in python2 you will need an external module.
			        IndexedRedis will automatically detect if "backports.lzma" or "lzmaffi" are installed, and use them
				if the core "lzma" module is not available.
			
			@param defaultValue - The default value for this field

			An IRCompressedField is indexable, and forces the index to be hashed.
		'''
		self.valueType = None
		self.defaultValue = defaultValue

		if compressMode == COMPRESS_MODE_ZLIB or compressMode in _COMPRESS_MODE_ALIASES_ZLIB:
			self.compressMode = COMPRESS_MODE_ZLIB
			self.header = b'x\xda'
			self.extraCompressArgs = (9, )
		elif compressMode == COMPRESS_MODE_BZ2 or compressMode in _COMPRESS_MODE_ALIASES_BZ2:
			self.compressMode = COMPRESS_MODE_BZ2
			self.header = b'BZh9'
			self.extraCompressArgs = (9, )
		elif compressMode == COMPRESS_MODE_LZMA or compressMode in _COMPRESS_MODE_ALIASES_LZMA:
			self.compressMode = COMPRESS_MODE_LZMA
			self.header = b'\xfd7zXZ'
			self.extraCompressArgs = tuple()
			self.getCompressMod() # Die early if LZMA compression is not available
		else:
			raise ValueError('Invalid compressMode, "%s", for field "%s". Should be one of the IndexedRedis.fields.compressed.COMPRESS_MODE_* constants.' %(str(compressMode), name))
7.
Diviyan-Kalainathan/CausalDiscoveryToolbox · estimator.py
Match rating: 47.02% · See similar code snippets
python logo
def get_pipeline(features, regressor=None, params=None):
    steps = [
        ("extract_features", FeatureMapper(features)),
        ("regressor", regressor(**params)),
        ]
    return Pipeline(steps)
8.
django-leonardo/django-leonardo · compress_patch.py
Match rating: 46.94% · See similar code snippets
python logo
def compress_monkey_patch():
    """patch all compress

    we need access to variables from widget scss

    for example we have::

        /themes/bootswatch/cyborg/_variables

    but only if is cyborg active for this reasone we need
    dynamically append import to every scss file

    """
    from compressor.templatetags import compress as compress_tags
    from compressor import base as compress_base

    compress_base.Compressor.filter_input = filter_input
    compress_base.Compressor.output = output
    compress_base.Compressor.hunks = hunks
    compress_base.Compressor.precompile = precompile

    compress_tags.CompressorMixin.render_compressed = render_compressed

    from django_pyscss import compressor as pyscss_compressor

    pyscss_compressor.DjangoScssFilter.input = input
9.
aliyun/aliyun-odps-python-sdk · stream.py
Match rating: 46.94% · See similar code snippets
python logo
def write(self, data):
        if self._compressor:
            compressed_data = self._compressor.compress(data)
            if compressed_data:
                self._output.write(compressed_data)
            else:
                pass  # buffering
        else:
            self._output.write(data)
10.
msmbuilder/msmbuilder · regularspatial.py
Match rating: 46.52% · See similar code snippets
python logo
def fit_predict(self, X, y=None):
        return self.fit(X, y=y).predict(X)