Ejemplo n.º 1
0
def test_run():
    # Data generated from W = [[1,2],[3,4]], H = [[4,3],[2,1]]
    R = [[8, 5], [20, 13]]
    M = [[1, 1], [1, 0]]
    K = 2

    U = numpy.array([[10, 9], [8, 7]], dtype='f')  #2x2
    V = numpy.array([[6, 4], [5, 3]], dtype='f')  #2x2

    nmf = NMF(R, M, K)

    # Check we get an Exception if W, H are undefined
    with pytest.raises(AssertionError) as error:
        nmf.run(0)
    assert str(
        error.value
    ) == "U and V have not been initialised - please run NMF.initialise() first."

    # Then check for 1 iteration whether the updates work - heck just the first entry of U
    nmf.U = U
    nmf.V = V
    nmf.run(1)

    U_00 = 10 * (6 * 8 / 96.0 + 5 * 5 / 77.0) / (5.0 + 6.0)  #0.74970484061
    assert abs(U_00 - nmf.U[0][0]) < 0.000001
Ejemplo n.º 2
0
# We now run the VB algorithm on each of the M's for each fraction.
all_performances = {metric: [] for metric in metrics}
average_performances = {metric: []
                        for metric in metrics}  # averaged over repeats
for (fraction, Ms, Ms_test) in zip(fractions_unknown, all_Ms, all_Ms_test):
    print "Trying fraction %s." % fraction

    # Run the algorithm <repeats> times and store all the performances
    for metric in metrics:
        all_performances[metric].append([])
    for (repeat, M, M_test) in zip(range(0, repeats), Ms, Ms_test):
        print "Repeat %s of fraction %s." % (repeat + 1, fraction)

        nmf = NMF(R, M, K)
        nmf.initialise(init_UV, expo_prior)
        nmf.run(iterations)

        # Measure the performances
        performances = nmf.predict(M_test)
        for metric in metrics:
            # Add this metric's performance to the list of <repeat> performances for this fraction
            all_performances[metric][-1].append(performances[metric])

    # Compute the average across attempts
    for metric in metrics:
        average_performances[metric].append(
            sum(all_performances[metric][-1]) / repeats)


print "repeats=%s \nfractions_unknown = %s \nall_performances = %s \naverage_performances = %s" % \
    (repeats,fractions_unknown,all_performances,average_performances)