Esempio n. 1
0
File: als.py Progetto: hhhhzy/lkpy
def _train_matrix_cd(mat: CSR, this: np.ndarray, other: np.ndarray,
                     reg: float):
    """
    One half of an explicit ALS training round using coordinate descent.

    Args:
        mat: the :math:`m \\times n` matrix of ratings
        this: the :math:`m \\times k` matrix to train
        other: the :math:`n \\times k` matrix of sample features
        reg: the regularization term
    """
    nr = mat.nrows
    nf = other.shape[1]
    assert mat.ncols == other.shape[0]
    assert mat.nrows == this.shape[0]
    assert this.shape[1] == nf

    frob = 0.0

    for i in prange(nr):
        cols = mat.row_cs(i)
        if len(cols) == 0:
            continue

        vals = mat.row_vs(i)

        w = this[i, :].copy()
        _rr_solve(other, cols, vals, w, reg * len(cols), 2)
        delta = this[i, :] - w
        frob += np.dot(delta, delta)
        this[i, :] = w

    return np.sqrt(frob)
Esempio n. 2
0
def test_unit_norm(csr: CSR):
    # assume(spm.nnz >= 10)
    backup = csr.copy()

    m2 = csr.normalize_rows('unit')
    assert len(m2) == csr.nrows
    assert m2.dtype == csr.values.dtype

    for i in range(csr.nrows):
        vs = csr.row_vs(i)
        bvs = backup.row_vs(i)
        if len(vs) > 0:
            assert m2[i] == approx(np.linalg.norm(bvs))
            if m2[i] > 0:
                assert np.linalg.norm(vs) == approx(1.0)
                assert vs * m2[i] == approx(backup.row_vs(i))
            else:
                assert all(np.isnan(vs))
        else:
            assert m2[i] == 0.0