1
1
from mola .matrix import Matrix
2
- from mola .utils import identity , ones , zeros , randoms , covmat , diag
2
+ from mola .utils import identity , ones , zeros , randoms , diag
3
3
from copy import deepcopy
4
4
5
5
def linear_least_squares (H : Matrix , z : Matrix , W = None ):
@@ -23,35 +23,40 @@ def linear_least_squares(H: Matrix, z: Matrix, W=None):
23
23
th_tuple = (th .get (0 ,0 ), th .get (1 ,0 ))
24
24
return th_tuple
25
25
26
- def irls (H : Matrix , z : Matrix , threshold = 1e-6 ):
26
+ def fit_irls (H : Matrix , z : Matrix , p : int = 2 , threshold : float = 1e-6 ):
27
27
"""
28
28
Return the iteratively reweighted least squares (IRLS) estimate of the parameters of a model defined by observation matrix H and dependent values z.
29
29
30
30
Arguments:
31
31
H -- Matrix: the observation matrix of the linear system of equations
32
32
z -- Matrix: the observed or dependent values depicting the right side of the linear system of equations
33
+ p -- float: norm exponential (default 2)
34
+ threshold -- float: the maximum difference between two consecutive estimate sets to break from iteration
33
35
"""
34
36
35
37
# estimate the parameters using ordinary least squares
36
38
th = ((H .get_transpose ())* H ).get_inverse () * H .get_transpose () * z
37
39
38
40
39
41
difference = float ('inf' )
42
+ delta = 1e-5
40
43
41
44
while difference > threshold :
42
45
46
+ th_previous = th
47
+
43
48
# calculate absolute values of residuals
44
- residuals = (H * th - z ).get_absolute_matrix ()
45
-
46
- # estimate sample variance-covariance matrix V using the OLS residuals
47
- #V = covmat(residuals)
49
+ residuals = ((H * th - z ).get_absolute_matrix ())** (p - 2 )
50
+
51
+ # formulate weighting matrix W as the diagonal of the residuals
48
52
W = diag (residuals )
49
53
print ("W: " , W )
50
54
51
55
# re-estimate the parameters using generalized least squares
52
56
th = ((H .get_transpose ())* W * H ).get_inverse () * H .get_transpose () * W * z
53
57
54
- difference = residuals .norm_Euclidean ()
58
+ difference = (th - th_previous ).norm_entrywise (p )
59
+ print ("diff: " , difference )
55
60
56
61
th_tuple = tuple (th .get_column (0 ))
57
62
return th_tuple
0 commit comments