###やりたいこと
指定したディレクトリ内にある全てのテキストファイル(.txtファイル)をLDAモデルに投入し、分類するためのプログラムを実装したいと思っています。
実装中のコードを以下に記します。
python3
1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3 4import time 5import os 6import glob 7import MeCab 8from gensim import corpora, models 9 10#ディレクトリ指定 11input_dir = input('select directory:') 12 13t0 = time.time() 14 15txt_list = glob.glob(input_dir + os.sep + '*.txt') 16 17texts = '' 18for file in txt_list: 19 with open(file, 'r', encoding='utf-8') as f: 20 texts += f.read() 21 22f.close() 23 24#文字列を改行位置で区切って分割する(形態素解析) 25m = MeCab.Tagger ("-Ochasen") 26chunks = m.parse(texts).splitlines() 27 28#絞り結果を格納 29sels = [] 30 31#絞り込み 32for chunk in chunks: 33 #chunk:形態素解析結果(1行の文字列) 34 #タブ(\t)で区切り、文字列リストを作成 35 cols = chunk.split('\t') 36 if len(cols) >= 4: 37 #parts[0]:品詞の種類 38 parts = cols[3].split('-') 39 #指定した品詞で始まっている場合 → true 40 if parts[0].startswith('名詞') or parts[0].startswith('動詞'): 41 #要素(形態素)を追加 42 #sels:要素(形態素)のみの行列 43 sels.append(chunk[0]) 44 45#辞書作成 46dictionary = corpora.Dictionary([sels]) 47 48""" 49#単語の出現回数が1以下を除く 50dictionary.filter_extremes(no_below = 1) 51""" 52 53#[辞書の単語数]次元のベクトルに変換(コーパス作成) 54corpus = [dictionary.doc2bow(sels) for sel in sels] 55 56t1 = time.time() 57 58#LDAモデルに投入 59lda = models.LdaModel(corpus = corpus, 60 id2word = dictionary, 61 #トピック数 62 num_topics = 20) 63 64t2 = time.time() 65 66print(lda) 67 68#各トピックにおける各トークンの出現確率を係数で表示 69for topic in lda.show_topics(-1): 70 print(topic) 71 72""" 73#文書の推定トピック番号 , 推定の確信度を表示 74for topics_per_document in lda[corpus]: 75 print(topics_per_document) 76""" 77 78corpus_time = t1 - t0 79print('コーパス生成時間:%f秒'%corpus_time) 80 81lda_time = t2 -t1 82print('LDAモデル生成時間:%f秒'%lda_time) 83 84total_time = t2 - t0 85print('合計時間:%f秒'%total_time)
現在、
形態素解析 ⇒ 品詞の絞り込み(名詞、動詞のみ) ⇒
辞書作成 ⇒ コーパス生成 ⇒ LDAモデルに投入
といった流れでLDAモデルを作成するプログラムを実装しているのですが、
精度を上げるために「ひらがな1文字」の形態素を排除したいと思っています。
どの段階(辞書作成前?コーパス生成前?)で排除するのが良いのか、
それぞれの場合でどのような方法で排除するのか教えていただきたいです。
どちらか片方だけでも非常にありがたいです。
また、精度を上げるためにデータの加工について他に工夫する方法があるのであれば、
それも教えていただきたいです。
あなたの回答
tips
プレビュー