def optimize_NxN(x, y, fit_offset=False, perc=None):
if perc is not None:<EOL><INDENT>if not fit_offset and isinstance(perc, (list, tuple)): perc = perc[<NUM_LIT:1>]<EOL>weights = get_weight(x, y, perc).astype(bool)<EOL>if issparse(weights): weights = weights.A<EOL><DEDENT>else:<EOL><INDENT>weights = None<EOL><DEDENT>x, y = x.astype(np.float64), y.astype(np.float64)<EOL>n_vars = x.shape[<NUM_LIT:1>]<EOL>offset, gamma = np.zeros(n_vars), np.zeros(n_vars)<EOL>for i in range(n_vars):<EOL><INDENT>xi = x[:, i] if weights is None else x[:, i][weights[:, i]]<EOL>yi = y[:, i] if weights is None else y[:, i][weights[:, i]]<EOL>if fit_offset:<EOL><INDENT>offset[i], gamma[i] = minimize(lambda m: np.sum((-yi + xi * m[<NUM_LIT:1>] + m[<NUM_LIT:0>])**<NUM_LIT:2>), method="<STR_LIT>",<EOL>x0=(<NUM_LIT:0>, <NUM_LIT:0.1>), bounds=[(<NUM_LIT:0>, None), (None, None)]).x<EOL><DEDENT>else:<EOL><INDENT>gamma[i] = minimize(lambda m: np.sum((-yi + xi * m) ** <NUM_LIT:2>), x0=<NUM_LIT:0.1>, method="<STR_LIT>").x<EOL><DEDENT><DEDENT>offset[np.isnan(offset)], gamma[np.isnan(gamma)] = <NUM_LIT:0>, <NUM_LIT:0><EOL>return offset, gamma<EOL>
Just to compare with closed-form solution