MCPcopy Create free account
hub / github.com/ddbourgin/numpy-ml / fit

Method fit

numpy_ml/factorization/factors.py:100–139  ·  view source on GitHub ↗

Factor a data matrix into two low rank factors via ALS. Parameters ---------- X : numpy array of shape `(N, M)` The data matrix to factor. W : numpy array of shape `(N, K)` or None An initial value for the `W` factor matrix. If None,

(self, X, W=None, H=None, n_initializations=10, verbose=False)

Source from the content-addressed store, hash-verified

98 return X @ A @ T1
99
100 def fit(self, X, W=None, H=None, n_initializations=10, verbose=False):
101 """
102 Factor a data matrix into two low rank factors via ALS.
103
104 Parameters
105 ----------
106 X : numpy array of shape `(N, M)`
107 The data matrix to factor.
108 W : numpy array of shape `(N, K)` or None
109 An initial value for the `W` factor matrix. If None, initialize `W`
110 randomly. Default is None.
111 H : numpy array of shape `(K, M)` or None
112 An initial value for the `H` factor matrix. If None, initialize `H`
113 randomly. Default is None.
114 n_initializations : int
115 Number of re-initializations of the algorithm to perform before
116 taking the answer with the lowest reconstruction error. This value
117 is ignored and set to 1 if both `W` and `H` are not None. Default
118 is 10.
119 verbose : bool
120 Whether to print the loss at each iteration. Default is False.
121 """
122 if W is not None and H is not None:
123 n_initializations = 1
124
125 best_loss = np.inf
126 for f in range(n_initializations):
127 if verbose:
128 print("\nINITIALIZATION {}".format(f + 1))
129
130 new_W, new_H, loss = self._fit(X, W, H, verbose)
131
132 if loss <= best_loss:
133 best_loss = loss
134 best_W, best_H = deepcopy(new_W), deepcopy(new_H)
135
136 self.W, self.H = best_W, best_H
137
138 if verbose:
139 print("\nFINAL LOSS: {}".format(best_loss))
140
141 def _fit(self, X, W, H, verbose):
142 self._init_factor_matrices(X, W, H)

Callers 1

_init_factor_matricesMethod · 0.95

Calls 1

_fitMethod · 0.95

Tested by

no test coverage detected