NMF 적용
두 가지 다른 목적 함수, Frobenius 노름과 일반화된 Kullback-Leibler 발산을 사용하여 NMF 를 적용합니다. 후자는 확률적 잠재 의미 지수와 동등합니다.
from sklearn.decomposition import NMF
n_components = 10
n_top_words = 20
init = "nndsvda"
## NMF 모델 적합
print(
"tf-idf 특징, n_samples=%d 및 n_features=%d를 사용하여 NMF 모델 (Frobenius 노름) 을 맞추는 중..." % (n_samples, n_features)
)
nmf = NMF(
n_components=n_components,
random_state=1,
init=init,
beta_loss="frobenius",
alpha_W=0.00005,
alpha_H=0.00005,
l1_ratio=1,
).fit(tfidf)
## NMF 모델의 상위 단어 플롯
def plot_top_words(model, feature_names, n_top_words, title):
fig, axes = plt.subplots(2, 5, figsize=(30, 15), sharex=True)
axes = axes.flatten()
for topic_idx, topic in enumerate(model.components_):
top_features_ind = topic.argsort()[: -n_top_words - 1 : -1]
top_features = [feature_names[i] for i in top_features_ind]
weights = topic[top_features_ind]
ax = axes[topic_idx]
ax.barh(top_features, weights, height=0.7)
ax.set_title(f"Topic {topic_idx +1}", fontdict={"fontsize": 30})
ax.invert_yaxis()
ax.tick_params(axis="both", which="major", labelsize=20)
for i in "top right left".split():
ax.spines[i].set_visible(False)
fig.suptitle(title, fontsize=40)
plt.subplots_adjust(top=0.90, bottom=0.05, wspace=0.90, hspace=0.3)
plt.show()
tfidf_feature_names = tfidf_vectorizer.get_feature_names_out()
plot_top_words(
nmf, tfidf_feature_names, n_top_words, "NMF 모델 (Frobenius 노름) 의 주제"
)
## 일반화된 Kullback-Leibler 발산을 사용하여 NMF 모델 적합
print(
"\n" * 2,
"tf-idf 특징, n_samples=%d 및 n_features=%d를 사용하여 NMF 모델 (일반화된 Kullback-Leibler 발산) 을 맞추는 중..."
% (n_samples, n_features),
)
nmf = NMF(
n_components=n_components,
random_state=1,
init=init,
beta_loss="kullback-leibler",
solver="mu",
max_iter=1000,
alpha_W=0.00005,
alpha_H=0.00005,
l1_ratio=0.5,
).fit(tfidf)
## 일반화된 Kullback-Leibler 발산을 사용한 NMF 모델의 상위 단어 플롯
tfidf_feature_names = tfidf_vectorizer.get_feature_names_out()
plot_top_words(
nmf,
tfidf_feature_names,
n_top_words,
"NMF 모델 (일반화된 Kullback-Leibler 발산) 의 주제",
)
## MiniBatchNMF 모델 적합
from sklearn.decomposition import MiniBatchNMF
batch_size = 128
print(
"\n" * 2,
"tf-idf 특징, n_samples=%d 및 n_features=%d, batch_size=%d를 사용하여 MiniBatchNMF 모델 (Frobenius 노름) 을 맞추는 중..."
% (n_samples, n_features, batch_size),
)
## ... (나머지 코드 생략)