Compute correlation of two numeric array

    Parameters
    ----------
    how : {'sample', 'pop'}, default 'sample'

    Returns
    -------
    corr : double scalar
492946
def correlation(left, right, where=None, how='sample'):
    
    expr = ops.Correlation(left, right, how, where).to_expr()
    return expr
1334172
def _correlate(self):
        
        a = self.algorithm(**self.algorithm_params)
        self.correlation_result = a.run()
293923
def covariance_mtx_to_superop(self, mtx):
        
        M = self.flat()
        return qt.Qobj(
            np.dot(np.dot(M.conj().T, mtx), M),
            dims=[[self.dims] * 2] * 2
        )
75433
def cor(y_true, y_pred):
    
    y_true, y_pred = _mask_nan(y_true, y_pred)
    return np.corrcoef(y_true, y_pred)[0, 1]
734187
private function computeCovariance()
    {
        $factorCallable = $this->coVarianceFactor;
        $this->factor = $factorCallable();

        // Cache covariance and inverse covariance of the data
        if (null === $this->_dataInvCov) {
            // original used the numpy.cov function.
            $this->_dataCovariance = pow(Statistics::stdev($this->dataset, true), 2);

            //$this->_dataInvCov = 1/ linalg.inv($this->_dataCovariance)
            $this->_dataInvCov = 1 / $this->_dataCovariance;
        }

        $this->covariance = $this->_dataCovariance * pow($this->factor, 2);
        $this->invCov = $this->_dataInvCov / pow($this->factor, 2);
        $this->normFactor = sqrt(2 * M_PI * $this->covariance) * count($this->dataset);
    }
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
1125383
public static double pearsonCorrelation(double[] x, double[] y) {
		double result;
		double sum_sq_x = 0, sum_sq_y = 0;
    double mean_x = x[0], mean_y = y[0];
		double sum_coproduct = 0;
		for(int i=2; i<x.length+1;++i) {
			double w = (i - 1)*1.0/i;
			double delta_x = x[i-1] - mean_x;
			double delta_y = y[i-1] - mean_y;
			sum_sq_x += delta_x * delta_x*w;
			sum_sq_y += delta_y * delta_y*w;
			sum_coproduct += delta_x * delta_y*w;
			mean_x += delta_x / i;
			mean_y += delta_y / i;
		}
		double pop_sd_x = Math.sqrt(sum_sq_x/x.length);
		double pop_sd_y = Math.sqrt(sum_sq_y/y.length);
		double cov_x_y = sum_coproduct / x.length;
    double denom = pop_sd_x*pop_sd_y;
    if(denom == 0.0)
      return 0.0;
    result = cov_x_y/denom;
		return result;
	}
121980
public static double computeCorrelation(final List<Double> list1, final List<Double> list2)
    {
        final double[] doubleArray1 = new double[list1.size()];
        final double[] doubleArray2 = new double[list2.size()];

        int off1 = 0;
        for (final double item : list1) {
            doubleArray1[off1] = item;
            off1++;
        }

        int off2 = 0;
        for (final double item : list2) {
            doubleArray2[off2] = item;
            off2++;
        }

        final double correlation = computeCorrelation(doubleArray1, doubleArray2);

        return correlation;
    }
686251
double cosine(SparseVector vec1, SparseVector vec2)
    {
        double norm1 = vec1.norm();
        double norm2 = vec2.norm();
        double result = 0.0f;
        if (norm1 == 0 && norm2 == 0)
        {
            return result;
        }
        else
        {
            double prod = inner_product(vec1, vec2);
            result = prod / (norm1 * norm2);
            return Double.isNaN(result) ? 0.0f : result;
        }
    }
611029
def decompose_covariance(c):
    

    # make it a kickass copy of the original
    c = _n.array(c)

    # first get the error vector
    e = []
    for n in range(0, len(c[0])): e.append(_n.sqrt(c[n][n]))

    # now cycle through the matrix, dividing by e[1]*e[2]
    for n in range(0, len(c[0])):
        for m in range(0, len(c[0])):
            c[n][m] = c[n][m] / (e[n]*e[m])

    return [_n.array(e), _n.array(c)]
710357
def corrArray(self, inputArray):
        
        outputArray = numpy.vstack([numpy.nan_to_num(currSpline(inputArray))
                                    for currSpline in self.splines
                                    ]).mean(axis=0)
        return outputArray
1004986
def _pairwise_corr(self, columns=None, covar=None, tail='two-sided',
                   method='pearson', padjust='none', export_filename=None):
    """"""
    stats = pairwise_corr(data=self, columns=columns, covar=covar,
                          tail=tail, method=method, padjust=padjust,
                          export_filename=export_filename)
    return stats
242446
def _scalar2array(d):
    """"""
    da = {}
    for k, v in d.items():
        if '_' not in k:
            da[k] = v
        else:
            name = ''.join(k.split('_')[:-1])
            ind = k.split('_')[-1]
            dim = len(ind)
            if name not in da:
                shape = tuple(3 for i in range(dim))
                da[name] = np.empty(shape, dtype=complex)
                da[name][:] = np.nan
            da[name][tuple(int(i) - 1 for i in ind)] = v
    return da
870485
public static double Correlation(double[] p, double[] q) {

        double x = 0;
        double y = 0;

        for (int i = 0; i < p.length; i++) {
            x += -p[i];
            y += -q[i];
        }

        x /= p.length;
        y /= q.length;

        double num = 0;
        double den1 = 0;
        double den2 = 0;
        for (int i = 0; i < p.length; i++) {
            num += (p[i] + x) * (q[i] + y);

            den1 += Math.abs(Math.pow(p[i] + x, 2));
            den2 += Math.abs(Math.pow(q[i] + x, 2));
        }

        return 1 - (num / (Math.sqrt(den1) * Math.sqrt(den2)));

    }
377347
def get_R_corr2(x_avg, y_avg, x_segment, y_segment): #
    
    xd = x_segment - x_avg # detrend x_segment
    yd = y_segment - y_avg # detrend y_segment
    if sum(xd**2) * sum(yd**2) == 0: # prevent divide by zero error
        return float('nan')
    rcorr = old_div(sum((xd * yd))**2, (sum(xd**2) * sum(yd**2)))
    return rcorr
1269821
def S(self):
        
        if self.c is None:
            raise RuntimeError('Cross-spectral density requires noise '
                               'covariance matrix c.')
        H = self.H()
        # TODO: can we do that more efficiently?
        S = np.empty(H.shape, dtype=H.dtype)
        for f in range(H.shape[2]):
            S[:, :, f] = H[:, :, f].dot(self.c).dot(H[:, :, f].conj().T)
        return S
1348799
def layer_covariance(layer1, layer2=None):
    """"""
    layer2 = layer2 or layer1
    act1, act2 = layer1.activations, layer2.activations
    num_datapoints = act1.shape[0]  # cast to avoid numpy type promotion during division
    return np.matmul(act1.T, act2) / float(num_datapoints)