コード例 #1
0
def rebuild(patch, dic, lambd):
    return skl
    D = np.asarray([x.getdata() for x in dic]).transpose()
    X = img.getdata()
    alpha = optim.lasso_seq(D, X, lambd)
    X_ = D.dot(alpha)
    nimg = Image.new(img.mode, img.size)
    nimg.putdata(X_)
    nimg.save("restored.png")
コード例 #2
0
def learn_dic(patches, dic_size, T=1000, lambd=0.1, batch_size=100):
    """
    Learns sparse coding dictionary using the online algorithm exposed in
        "J. Mairal, F. Bach, J. Ponce, and G. Sapiro. Online dictionary learning for sparse coding.
        In Proceedings of the International Conference on Machine Learning (ICML), 2009."
    :param patches: array of patches patches[i, j] represents the jth pixel of the ith patch
    :param dic_size: size of dictionary
    :param T: number of iterations
    :param lambd: Lasso regularization parameter
    :param batch_size: size of batches processed during each iteration
    :return: learned dictionary
    """

    # Extract patch size
    patch_size = patches.shape[1]

    # Initialize A and B at 0
    A = np.zeros((dic_size, dic_size))
    B = np.zeros((patch_size, dic_size))

    # Initialize D at random
    D = np.random.rand(patch_size, dic_size)

    for t in range(T):
        # Extract batch as array of column-vectors
        batch_indices = np.random.choice(range(len(patches)), size=batch_size)
        x = patches[batch_indices].T

        # Compute sparse coding of x using lars lasso
        alpha = optim.lasso_seq(D, x, lambd)

        # Update A and B
        A += alpha.dot(alpha.T) / batch_size
        B += x.dot(alpha.T) / batch_size

        # Update D
        D = update_dic(D, A, B)

        # Print percentage
        print("\rDictionary learning: {0}".format(int((float(t + 1) / T) * 100)), "%", end="", flush=True)

    return D