|
| 1 | +# Author: Olivier Grisel <[email protected]> |
| 2 | +# Lars Buitinck |
| 3 | +# Chyi-Kwei Yau <[email protected]> |
| 4 | +# License: BSD 3 clause |
| 5 | + |
| 6 | +from time import time |
| 7 | +import shutil |
| 8 | +import matplotlib.pyplot as plt |
| 9 | +import pdb |
| 10 | +import os |
| 11 | +import numpy as np |
| 12 | + |
| 13 | +from sklearn.datasets import fetch_20newsgroups |
| 14 | +from sklearn.decomposition import LatentDirichletAllocation |
| 15 | +from sklearn.feature_extraction.text import CountVectorizer |
| 16 | +import jieba |
| 17 | +import jieba.posseg as jp |
| 18 | +import json |
| 19 | +import re |
| 20 | +from multiprocessing import Process, cpu_count |
| 21 | +# https://blog.csdn.net/xyisv/article/details/104482818 |
| 22 | +import pickle as pkl |
| 23 | + |
| 24 | +n_features = 2048 |
| 25 | +n_components = 100 |
| 26 | +n_top_words = 100 |
| 27 | +batch_size = 128 |
| 28 | + |
| 29 | +def files(): |
| 30 | + basedir = '/home/data/khj/workspace/huixiangdou/lda/preprocess' |
| 31 | + |
| 32 | + docs = [] |
| 33 | + for root, _, files in os.walk(basedir): |
| 34 | + for file in files: |
| 35 | + if file.endswith('.jpg') or file.endswith('.png') or file.endswith('.jpeg'): |
| 36 | + pdb.set_trace() |
| 37 | + else: |
| 38 | + docs.append((file, os.path.join(root, file))) |
| 39 | + return docs |
| 40 | + |
| 41 | +def filecontents(dirname:str): |
| 42 | + filepaths = files() |
| 43 | + for _, filepath in filepaths: |
| 44 | + with open(filepath) as f: |
| 45 | + content = f.read() |
| 46 | + if len(content) > 0: |
| 47 | + yield content |
| 48 | + |
| 49 | +def load_namemap(): |
| 50 | + namemap = dict() |
| 51 | + with open('name_map.txt') as f: |
| 52 | + for line in f: |
| 53 | + parts = line.split('\t') |
| 54 | + namemap[parts[0].strip()] = parts[1].strip() |
| 55 | + return namemap |
| 56 | + |
| 57 | +# reference step https://blog.csdn.net/xyisv/article/details/104482818 |
| 58 | +def plot_top_words(model, feature_names, n_top_words, title): |
| 59 | + fig, axes = plt.subplots(2, 5, figsize=(30, 15), sharex=True) |
| 60 | + axes = axes.flatten() |
| 61 | + for topic_idx, topic in enumerate(model.components_): |
| 62 | + top_features_ind = topic.argsort()[-n_top_words:] |
| 63 | + top_features = feature_names[top_features_ind] |
| 64 | + weights = topic[top_features_ind] |
| 65 | + |
| 66 | + ax = axes[topic_idx] |
| 67 | + ax.barh(top_features, weights, height=0.7) |
| 68 | + ax.set_title(f"Topic {topic_idx +1}", fontdict={"fontsize": 30}) |
| 69 | + ax.tick_params(axis="both", which="major", labelsize=20) |
| 70 | + for i in "top right left".split(): |
| 71 | + ax.spines[i].set_visible(False) |
| 72 | + fig.suptitle(title, fontsize=40) |
| 73 | + |
| 74 | + plt.subplots_adjust(top=0.90, bottom=0.05, wspace=0.90, hspace=0.3) |
| 75 | + plt.savefig('topic_centers.jpg') |
| 76 | + |
| 77 | +def build_topic(dirname: str='preprocess'): |
| 78 | + namemap = load_namemap() |
| 79 | + pdb.set_trace() |
| 80 | + |
| 81 | + tf_vectorizer = CountVectorizer( |
| 82 | + max_df=0.95, min_df=2, max_features=n_features, stop_words="english" |
| 83 | + ) |
| 84 | + |
| 85 | + t0 = time() |
| 86 | + tf = tf_vectorizer.fit_transform(filecontents(dirname)) |
| 87 | + print("BoW in %0.3fs." % (time() - t0)) |
| 88 | + |
| 89 | + lda = LatentDirichletAllocation( |
| 90 | + n_components=n_components, |
| 91 | + max_iter=5, |
| 92 | + learning_method="online", |
| 93 | + learning_offset=50.0, |
| 94 | + random_state=0, |
| 95 | + ) |
| 96 | + t0 = time() |
| 97 | + doc_types = lda.fit_transform(tf) |
| 98 | + |
| 99 | + pdb.set_trace() |
| 100 | + print("lda train in %0.3fs." % (time() - t0)) |
| 101 | + # transform(raw_documents)[source] |
| 102 | + feature_names = tf_vectorizer.get_feature_names_out() |
| 103 | + |
| 104 | + models = {'CountVectorizer': tf_vectorizer, 'LatentDirichletAllocation': lda} |
| 105 | + with open('lda_models.pkl', 'wb') as model_file: |
| 106 | + pkl.dump(models, model_file) |
| 107 | + |
| 108 | + top_features_list = [] |
| 109 | + for _, topic in enumerate(lda.components_): |
| 110 | + top_features_ind = topic.argsort()[-n_top_words:] |
| 111 | + top_features = feature_names[top_features_ind] |
| 112 | + weights = topic[top_features_ind] |
| 113 | + top_features_list.append(top_features.tolist()) |
| 114 | + |
| 115 | + with open(os.path.join('cluster', 'desc.json'), 'w') as f: |
| 116 | + json_str = json.dumps(top_features_list, ensure_ascii=False) |
| 117 | + f.write(json_str) |
| 118 | + |
| 119 | + filepaths = files() |
| 120 | + |
| 121 | + pdb.set_trace() |
| 122 | + for file_id, doc_score in enumerate(doc_types): |
| 123 | + basename, input_filepath = filepaths[file_id] |
| 124 | + hashname = basename.split('.')[0] |
| 125 | + source_filepath = namemap[hashname] |
| 126 | + indices_np = np.where(doc_score > 0.1)[0] |
| 127 | + for topic_id in indices_np: |
| 128 | + target_dir = os.path.join('cluster', str(topic_id)) |
| 129 | + if not os.path.exists(target_dir): |
| 130 | + os.makedirs(target_dir) |
| 131 | + shutil.copy(source_filepath, target_dir) |
| 132 | + |
| 133 | +if __name__ == '__main__': |
| 134 | + build_topic() |
0 commit comments