example_20newsgroups.py 4.61 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Copyright 2021 Yifei Ma
# Modified from scikit-learn example "plot_topics_extraction_with_nmf_lda.py"
# with the following original authors with BSD 3-Clause:
# * Olivier Grisel <olivier.grisel@ensta.org>
# * Lars Buitinck
# * Chyi-Kwei Yau <chyikwei.yau@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import warnings
21
from time import time
22

23
import matplotlib.pyplot as plt
24
25
26
import numpy as np
import scipy.sparse as ss
import torch
27
from lda_model import LatentDirichletAllocation as LDAModel
28
from sklearn.datasets import fetch_20newsgroups
29
30
from sklearn.decomposition import NMF, LatentDirichletAllocation
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
31

32
33
import dgl
from dgl import function as fn
34
35
36
37
38

n_samples = 2000
n_features = 1000
n_components = 10
n_top_words = 20
39
40
device = "cuda"

41
42
43
44
45

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_):
46
        top_features_ind = topic.argsort()[: -n_top_words - 1 : -1]
47
48
49
50
51
        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)
52
        ax.set_title(f"Topic {topic_idx +1}", fontdict={"fontsize": 30})
53
        ax.invert_yaxis()
54
55
        ax.tick_params(axis="both", which="major", labelsize=20)
        for i in "top right left".split():
56
57
58
59
60
61
            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()

62

63
64
65
66
67
68
69
# Load the 20 newsgroups dataset and vectorize it. We use a few heuristics
# to filter out useless terms early on: the posts are stripped of headers,
# footers and quoted replies, and common English words, words occurring in
# only one document or in at least 95% of the documents are removed.

print("Loading dataset...")
t0 = time()
70
71
72
73
74
75
data, _ = fetch_20newsgroups(
    shuffle=True,
    random_state=1,
    remove=("headers", "footers", "quotes"),
    return_X_y=True,
)
76
data_samples = data[:n_samples]
77
data_test = data[n_samples : 2 * n_samples]
78
79
80
81
print("done in %0.3fs." % (time() - t0))

# Use tf (raw term count) features for LDA.
print("Extracting tf features for LDA...")
82
83
84
tf_vectorizer = CountVectorizer(
    max_df=0.95, min_df=2, max_features=n_features, stop_words="english"
)
85
86
87
88
89
90
t0 = time()
tf_vectorizer.fit(data)
tf = tf_vectorizer.transform(data_samples)
tt = tf_vectorizer.transform(data_test)

tf_feature_names = tf_vectorizer.get_feature_names()
91
92
93
94
95
96
97
98
99
100
tf_uv = [
    (u, v)
    for u, v, e in zip(tf.tocoo().row, tf.tocoo().col, tf.tocoo().data)
    for _ in range(e)
]
tt_uv = [
    (u, v)
    for u, v, e in zip(tt.tocoo().row, tt.tocoo().col, tt.tocoo().data)
    for _ in range(e)
]
101
102
103
104
105
print("done in %0.3fs." % (time() - t0))
print()

print("Preparing dgl graphs...")
t0 = time()
106
107
G = dgl.heterograph({("doc", "topic", "word"): tf_uv}, device=device)
Gt = dgl.heterograph({("doc", "topic", "word"): tt_uv}, device=device)
108
109
110
111
112
print("done in %0.3fs." % (time() - t0))
print()

print("Training dgl-lda model...")
t0 = time()
113
model = LDAModel(G.num_nodes("word"), n_components)
114
115
116
117
118
119
120
model.fit(G)
print("done in %0.3fs." % (time() - t0))
print()

print(f"dgl-lda training perplexity {model.perplexity(G):.3f}")
print(f"dgl-lda testing perplexity {model.perplexity(Gt):.3f}")

yifeim's avatar
yifeim committed
121
word_nphi = np.vstack([nphi.tolist() for nphi in model.word_data.nphi])
122
plot_top_words(
123
124
125
126
127
    type("dummy", (object,), {"components_": word_nphi}),
    tf_feature_names,
    n_top_words,
    "Topics in LDA model",
)
128
129
130

print("Training scikit-learn model...")

131
132
133
134
135
136
137
138
139
140
141
142
143
print(
    "\n" * 2,
    "Fitting LDA models with tf features, "
    "n_samples=%d and n_features=%d..." % (n_samples, n_features),
)
lda = LatentDirichletAllocation(
    n_components=n_components,
    max_iter=5,
    learning_method="online",
    learning_offset=50.0,
    random_state=0,
    verbose=1,
)
144
145
146
147
148
149
150
t0 = time()
lda.fit(tf)
print("done in %0.3fs." % (time() - t0))
print()

print(f"scikit-learn training perplexity {lda.perplexity(tf):.3f}")
print(f"scikit-learn testing perplexity {lda.perplexity(tt):.3f}")