0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

特定の語彙からtf-idfベクトルを作成する

Posted at

はじめに

ストップワード抽出をした後、その語彙のみを用いてtf-idfのベクトル化を文書に対して行う際のコードを備忘録として残します。
形態素解析にはfugashi, tf-idfの作成ではsk-learnを利用しています。

実装

形態素解析

from fugashi import Tagger

def text_tokenizer_helper(tagger,text:str) -> list:
    ret = []
    for word in tagger(text):
        w = word.feature.lemma
        if w is None:
            w = str(word)
        
        ret.append(w)
    return ret

こちらのコードで形態素解析を行い、その基本形を返すようにします。この関数を使って文書の形態素解析を行いました。
例えば、文書集合があるときには以下のように扱うことができます.

texts = # 文が要素となっているリスト
tokenized_text = []
for s in texts:
    tokenized_sentence = text_tokenizer_helper(s)
    tokenized_text.append(tokenized_sentence)

tf-idfのベクトルの取得

ストップワードを取りいた後、tf-idfのベクトルを取得するために以下の関数を用います。
引数として対象とする文書(スペースで区切ったもの) と 使用する語彙のリストを渡します.

from sklearn.feature_extraction.text import TfidfVectorizer

def tf_idf_helper(corpus : list, vocabulary:list):
    vocabulary = {word: index for index, word in enumerate(global_word_list)}

    # TfidfVectorizer の初期化(独自の語彙を使用)
    vectorizer = TfidfVectorizer(vocabulary=vocabulary)

    X = vectorizer.fit_transform(corpus)
    return X.toarray()

このコードからTfidfVectorizer()にはvocabularyという引数に単語 : IDの辞書を渡すことで使用する語彙を決めることができるとわかりました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?