Returns a pandas Series with eigenvalues of the correlation matrix.

    Args:
        df: pandas DataFrame with columns to run diagnostics on
546202
def eigenvalues(df):
    '''
    
    '''
    corr = np.corrcoef(df, rowvar=0)
    eigvals = np.linalg.eigvals(corr)
    return pd.Series(eigvals, df.columns, name='Eigenvalue')
660164
def get_ensemble_counts(d):
    
    _rows_cols = {"rows": 0, "cols": 0}
    try:

        if len(d) == 1:
            for var, data in d.items():
                # increment columns by one
                _rows_cols["cols"] += len(data["values"])
                # get row count by getting len of column (since it's only one list
                _rows_cols["rows"] = len(data["values"][0])
                break

        elif len(d) == 2:
            for var, data in d.items():
                # multiple columns in one. list of lists
                if isinstance(data["number"], list):
                    # add total amount of columns to the running total
                    _rows_cols["cols"] += len(data["values"])
                # single column. one list
                else:
                    # increment columns by one
                    _rows_cols["cols"] += 1
                    # get row count by getting len of column (since it's only one list
                    _rows_cols["rows"] = len(data["values"])

    except Exception as e:
        logger_misc.warn("get_ensemble_counts: {}".format(e))

    return _rows_cols
616290
def get_rows(self):
        
        possible_dataframes = ['F', 'FY', 'M', 'S',
                               'D_cba', 'D_pba',  'D_imp', 'D_exp',
                               'D_cba_reg', 'D_pba_reg',
                               'D_imp_reg', 'D_exp_reg',
                               'D_cba_cap', 'D_pba_cap',
                               'D_imp_cap', 'D_exp_cap', ]
        for df in possible_dataframes:
            if (df in self.__dict__) and (getattr(self, df) is not None):
                return getattr(self, df).index.get_values()
        else:
            logging.warn("No attributes available to get row names")
            return None
417222
def main(df):
  '''
  
  '''
  import numpy as np
  from ast import literal_eval as make_tuple

  test = {}
  test['row'] = df['mat'].index.tolist()
  test['col'] = df['mat'].columns.tolist()

  # if type( test_row ) is not str and type( test_row ) is not tuple:

  found_tuple = {}
  found_number = {}
  for inst_rc in ['row','col']:

    inst_name = test[inst_rc][0]

    found_tuple[inst_rc] = False
    found_number[inst_rc] = False

    if type(inst_name) != tuple:

      if type(inst_name) is int or type(inst_name) is float or type(inst_name) is np.int64:
        found_number[inst_rc] = True

      else:
        check_open = inst_name[0]
        check_comma = inst_name.find(',')
        check_close = inst_name[-1]

        if check_open == '(' and check_close == ')' and check_comma > 0 \
          and check_comma < len(inst_name):
          found_tuple[inst_rc] = True

  # convert to tuple if necessary
  #################################################
  if found_tuple['row']:
    row_names = df['mat'].index.tolist()
    row_names = [make_tuple(x) for x in row_names]
    df['mat'].index = row_names

  if found_tuple['col']:
    col_names = df['mat'].columns.tolist()
    col_names = [make_tuple(x) for x in col_names]
    df['mat'].columns = col_names

  # convert numbers to string if necessary
  #################################################
  if found_number['row']:
    row_names = df['mat'].index.tolist()
    row_names = [str(x) for x in row_names]
    df['mat'].index = row_names

  if found_number['col']:
    col_names = df['mat'].columns.tolist()
    col_names = [str(x) for x in col_names]
    df['mat'].columns = col_names

  return df
1319090
def noise_covariance(fit, dof=2, **kw):
    
    ev = fit.eigenvalues

    measurement_noise = ev[-1]/(fit.n-dof)
    return 4*ev*measurement_noise
279394
def term_group_freq_df(self, group_col):
        # type: (str) -> pd.DataFrame
        '''
        
        '''
        group_idx_store = IndexStore()
        X = self._X
        group_idx_to_cat_idx, row_group_cat \
            = self._get_group_docids_and_index_store(X, group_col, group_idx_store)
        newX = self._change_document_type_in_matrix(X, row_group_cat)
        newX = self._make_all_positive_data_ones(newX)
        category_row = newX.tocoo().row
        for group_idx, cat_idx in group_idx_to_cat_idx.items():
            category_row[category_row == group_idx] = cat_idx
        catX = self._change_document_type_in_matrix(newX, category_row)
        return self._term_freq_df_from_matrix(catX)
645563
def sample_correlations(self):
        
        C = np.corrcoef(self.X.T)
        corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C)
        return corr_matrix
1218500
def get_dfdx(self):
        
        if self._dfdx is True:
            if self.indep is None:
                zero = 0*self.be.Dummy()**0
                self._dfdx = self.be.Matrix(1, self.ny, [zero]*self.ny)
            else:
                self._dfdx = self.be.Matrix(1, self.ny, [expr.diff(self.indep) for expr in self.exprs])
        elif self._dfdx is False:
            return False
        return self._dfdx
652344
def as_df():
    """"""
    records = []
    for sym, ele in vars(_this).items():
        if sym not in ["Element", "Isotope"] and not sym.startswith("_"):
            for k, v in vars(ele).items():
                if k.startswith("_") and k[1].isdigit():
                    records.append({kk: vv for kk, vv in vars(v).items() if not kk.startswith("_")})
    return _DF.from_records(records)
139413
def condition_indices(df):
    '''
    
    '''
    eigvals = eigenvalues(df)
    cond_idx = np.sqrt(eigvals.max() / eigvals)
    return pd.Series(cond_idx, df.columns, name='Condition index')
79668
def column_correlations(self, X):
        """"""
        utils.validation.check_is_fitted(self, 's_')

        X_global = self._build_X_global(X)
        row_pc = self._row_coordinates_from_global(X_global)

        return pd.DataFrame({
            component: {
                feature: row_pc[component].corr(X_global[feature].to_dense())
                for feature in X_global.columns
            }
            for component in row_pc.columns
        })
1083765
def constraint_df(self):
        
        df = pd.DataFrame()
        for name,c in self.constraints.items():
            df[name] = c.ok
        for name,c in self.hidden_constraints.items():
            df[name] = c.ok
        return df
317791
public static double[] rowStdDevs(RealMatrix matrix) {
        double[] retval = new double[matrix.getRowDimension()];
        for (int i = 0; i < retval.length; i++) {
            retval[i] = new DescriptiveStatistics(matrix.getRow(i)).getStandardDeviation();
        }
        return retval;
    }
646293
def loadings(self):
        """"""
        loadings = self.v[:, : self.keep] * np.sqrt(self.eigenvalues)
        cols = ["PC%s" % i for i in range(1, self.keep + 1)]
        loadings = pd.DataFrame(
            loadings, columns=cols, index=self.feature_names
        )
        return loadings
1252443
def perform_pca(A):
    
    # First subtract the mean
    M = (A-numpy.mean(A.T, axis=1)).T
    # Get eigenvectors and values of covariance matrix
    return numpy.linalg.eig(numpy.cov(M))
569526
def corrgroups60(display=False):
    

    # set a constant seed
    old_seed = np.random.seed()
    np.random.seed(0)

    # generate dataset with known correlation
    N = 1000
    M = 60

    # set one coefficent from each group of 3 to 1
    beta = np.zeros(M)
    beta[0:30:3] = 1

    # build a correlation matrix with groups of 3 tightly correlated features
    C = np.eye(M)
    for i in range(0,30,3):
        C[i,i+1] = C[i+1,i] = 0.99
        C[i,i+2] = C[i+2,i] = 0.99
        C[i+1,i+2] = C[i+2,i+1] = 0.99
    f = lambda X: np.matmul(X, beta)

    # Make sure the sample correlation is a perfect match
    X_start = np.random.randn(N, M)
    X_centered = X_start - X_start.mean(0)
    Sigma = np.matmul(X_centered.T, X_centered) / X_centered.shape[0]
    W = np.linalg.cholesky(np.linalg.inv(Sigma)).T
    X_white = np.matmul(X_centered, W.T)
    assert np.linalg.norm(np.corrcoef(np.matmul(X_centered, W.T).T) - np.eye(M)) < 1e-6 # ensure this decorrelates the data

    # create the final data
    X_final = np.matmul(X_white, np.linalg.cholesky(C).T)
    X = X_final
    y = f(X) + np.random.randn(N) * 1e-2

    # restore the previous numpy random seed
    np.random.seed(old_seed)

    return pd.DataFrame(X), y
1065103
def pandas(self):
        
        names,prior,posterior = [],[],[]
        for iname,name in enumerate(self.posterior_parameter.row_names):
            names.append(name)
            posterior.append(np.sqrt(float(
                self.posterior_parameter[iname, iname]. x)))
            iprior = self.parcov.row_names.index(name)
            prior.append(np.sqrt(float(self.parcov[iprior, iprior].x)))
        for pred_name, pred_var in self.posterior_prediction.items():
            names.append(pred_name)
            posterior.append(np.sqrt(pred_var))
            prior.append(self.prior_prediction[pred_name])
        return pd.DataFrame({"posterior": posterior, "prior": prior},
                                index=names)