@@ -51,7 +51,7 @@ def atleast_nd(x: Array, *, ndim: int, xp: ModuleType) -> Array:
51
51
52
52
def cov (m : Array , / , * , xp : ModuleType ) -> Array :
53
53
"""
54
- Estimate a covariance matrix, given data and weights .
54
+ Estimate a covariance matrix.
55
55
56
56
Covariance indicates the level to which two variables vary together.
57
57
If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
@@ -67,6 +67,8 @@ def cov(m: Array, /, *, xp: ModuleType) -> Array:
67
67
A 1-D or 2-D array containing multiple variables and observations.
68
68
Each row of `m` represents a variable, and each column a single
69
69
observation of all those variables.
70
+ xp : array_namespace
71
+ The standard-compatible namespace for `m`.
70
72
71
73
Returns
72
74
-------
@@ -75,37 +77,42 @@ def cov(m: Array, /, *, xp: ModuleType) -> Array:
75
77
76
78
Examples
77
79
--------
78
- >>> import numpy as np
80
+ >>> import array_api_strict as xp
81
+ >>> import array_api_extra as xpx
79
82
80
83
Consider two variables, :math:`x_0` and :math:`x_1`, which
81
84
correlate perfectly, but in opposite directions:
82
85
83
- >>> x = np.array ([[0, 2], [1, 1], [2, 0]]).T
86
+ >>> x = xp.asarray ([[0, 2], [1, 1], [2, 0]]).T
84
87
>>> x
85
- array ([[0, 1, 2],
86
- [2, 1, 0]])
88
+ Array ([[0, 1, 2],
89
+ [2, 1, 0]], dtype=array_api_strict.int64 )
87
90
88
91
Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
89
92
matrix shows this clearly:
90
93
91
- >>> np.cov(x)
92
- array([[ 1., -1.],
93
- [-1., 1.]])
94
+ >>> xpx.cov(x, xp=xp)
95
+ Array([[ 1., -1.],
96
+ [-1., 1.]], dtype=array_api_strict.float64)
97
+
94
98
95
99
Note that element :math:`C_{0,1}`, which shows the correlation between
96
100
:math:`x_0` and :math:`x_1`, is negative.
97
101
98
102
Further, note how `x` and `y` are combined:
99
103
100
- >>> x = [-2.1, -1, 4.3]
101
- >>> y = [3, 1.1, 0.12]
102
- >>> X = np.stack((x, y), axis=0)
103
- >>> np.cov(X)
104
- array([[11.71 , -4.286 ], # may vary
105
- [-4.286 , 2.144133]])
106
- >>> np.cov(x)
107
- array(11.71)
108
- >>> xp.cov(y)
104
+ >>> x = xp.asarray([-2.1, -1, 4.3])
105
+ >>> y = xp.asarray([3, 1.1, 0.12])
106
+ >>> X = xp.stack((x, y), axis=0)
107
+ >>> xpx.cov(X, xp=xp)
108
+ Array([[11.71 , -4.286 ],
109
+ [-4.286 , 2.14413333]], dtype=array_api_strict.float64)
110
+
111
+ >>> xpx.cov(x, xp=xp)
112
+ Array(11.71, dtype=array_api_strict.float64)
113
+
114
+ >>> xpx.cov(y, xp=xp)
115
+ Array(2.14413333, dtype=array_api_strict.float64)
109
116
110
117
"""
111
118
m = xp .asarray (m , copy = True )
0 commit comments