public Array <float> Fit(Array <float> X, bool center = true) { var m = X.Shape[0]; var n = X.Shape[1]; var k = Math.Min(m, n); this.means = NN.Mean(X, axis: 0); if (center) { X -= means; } var copy = (float[])X.Values.Clone(); var s = new float[k]; var u = NN.Zeros <float>(m, m); components_ = NN.Zeros <float>(n, n); var superb = new float[k - 1]; BlasNet.Lapack.gesvd('A', 'A', m, n, copy, n, s, u.Values, m, components_.Values, n, superb); var components = nComponents == 0 ? k : Math.Min(k, nComponents); SVDFlip(u, components); return(X); }
public static Array <Real> Cov(Array <Real> m, int ddof = 1, Array <Real> result = null) { // Estimate a covariance matrix, given data. // Covariance indicates the level to which two variables vary together. // If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`, // then the covariance matrix element :math:`C_{ij}` is the covariance of // :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance // of :math:`x_i`. // Parameters // ---------- // m : array_like // A 1-D or 2-D array containing multiple variables and observations. // Each row of `m` represents a variable, and each column a single // observation of all those variables. Also see `rowvar` below. // ddof : int, optional // .. versionadded:: 1.5 // If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is // the number of observations; this overrides the value implied by // ``bias``. The default value is ``None``. // Returns // ------- // out : ndarray // The covariance matrix of the variables. // See Also // -------- // corrcoef : Normalized covariance matrix // Examples // -------- // Consider two variables, :math:`x_0` and :math:`x_1`, which // correlate perfectly, but in opposite directions: // >>> x = np.array([[0, 2], [1, 1], [2, 0]]).T // >>> x // array([[0, 1, 2], // [2, 1, 0]]) // Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance // matrix shows this clearly: // >>> np.cov(x) // array([[ 1., -1.], // [-1., 1.]]) // Note that element :math:`C_{0,1}`, which shows the correlation between // :math:`x_0` and :math:`x_1`, is negative. // Further, note how `x` and `y` are combined: // >>> x = [-2.1, -1, 4.3] // >>> y = [3, 1.1, 0.12] // >>> X = np.vstack((x,y)) // >>> print np.cov(X) // [[ 11.71 -4.286 ] // [ -4.286 2.14413333]] // >>> print np.cov(x, y) // [[ 11.71 -4.286 ] // [ -4.286 2.14413333]] // >>> print np.cov(x) // 11.71 var fact = (Real)(m.Shape[1] - ddof); if (fact <= 0) { throw new ArgumentException("Degrees of freedom <= 0 for slice"); } var X = m - NN.Mean(m, axis: 1, keepdims: true); //result = X.T.Dot(X, result: result); result = X.Dot(X.T, result: result); result.Scale((Real)1.0 / fact, result: result); return(result); }