def sweep_components(X, n_max=None, n_min=2): """ Sweeps over all values of n_components and returns a plot of losses vs n_components Parameters ---------- X : Tensor n_max : int Max n in search, default X.shape[0] n_min : int Min n in search, default 2 Returns ------- fig """ from constrainednmf.nmf.models import NMF mpl.rcParams.update({"font.size": fontsize, "lines.linewidth": linewidth}) if n_max is None: n_max = X.shape[0] losses = list() kl_losses = list() for n_components in range(n_min, n_max + 1): nmf = NMF(X.shape, n_components) nmf.fit(X, beta=2, tol=1e-8, max_iter=500) losses.append(nmf.loss(X, beta=2)) kl_losses.append(nmf.loss(X, beta=1)) fig = plt.figure( figsize=(one_column_width, one_column_width / 2), tight_layout=True ) # create a figure object ax = fig.add_subplot(1, 1, 1) axes = [ax, ax.twinx()] x = list(range(n_min, n_max + 1)) axes[0].plot(x, losses, color="C0", label="MSE Loss") axes[0].set_ylabel("MSE Loss", color="C0") axes[1].plot(x, kl_losses, color="C1", label="KL Loss") axes[1].set_ylabel("KL Loss", color="C1") axes[1].ticklabel_format(style='sci', scilimits=(-2, 2)) ax.set_xlabel("Number of components") return fig, axes
def constrained_nmf(X, components): input_H = [ torch.tensor(component[None, :], dtype=torch.float) for component in components ] nmf = NMF( X.shape, n_components=3, initial_components=input_H, fix_components=[True for _ in range(len(input_H))], ) n_iter = nmf.fit(torch.tensor(X), beta=2) return nmf
def constrained_nmf(X): ideal_weights = np.array( list(zip(*[(x, 1 - x) for x in np.linspace(0, 1, X.shape[0])]))) input_W = [ torch.tensor(w[None, :], dtype=torch.float) for w in ideal_weights.T ] nmf = NMF( X.shape, n_components=2, initial_weights=input_W, fix_weights=[True for _ in range(len(input_W))], ) n_iter = nmf.fit(torch.tensor(X), beta=2) return nmf
def partial_constrained_nmf(X, components, fix_components=(True for _ in range(3))): input_H = [ torch.tensor(component[None, :], dtype=torch.float) if fix_components[i] else torch.rand(1, X.shape[-1]) for i, component in enumerate(components) ] nmf = NMF( X.shape, n_components=3, initial_components=input_H, fix_components=fix_components, ) _ = nmf.fit(torch.tensor(X), beta=2) return nmf
def standard_nmf(X, n_components=4): nmf = NMF(X.shape, n_components) n_iter = nmf.fit(X, beta=2, tol=1e-8, max_iter=1000) return nmf
def standard_nmf(X): nmf = NMF(X.shape, n_components=2) n_iter = nmf.fit(torch.tensor(X), beta=2) return nmf
def standard_nmf(X): nmf = NMF(X.shape, 4) n_iter = nmf.fit(X, beta=2, tol=1e-8, max_iter=1000) return nmf