Main Content

bagOfNgrams

説明

bag-of-n-grams モデルは、各 n-gram がコレクションの各文書に出現する回数を記録します。n-gram は、連続する n 個の単語のコレクションです。

bagOfNgrams は、テキストを単語に分割しません。トークン化された文書の配列を作成するには、tokenizedDocument を参照してください。

作成

説明

bag = bagOfNgrams は、空の bag-of-n-grams モデルを作成します。

bag = bagOfNgrams(documents) は bag-of-n-grams モデルを作成し、documents 内のバイグラム (単語のペア) をカウントします。

bag = bagOfNgrams(___,'NgramLengths',lengths) は、前の構文のいずれかを使用して、指定された長さの n-gram をカウントします。

bag = bagOfNgrams(uniqueNgrams,counts) は、uniqueNgrams 内の n-gram と counts 内の対応する頻度カウントを使用して、bag-of-n-grams モデルを作成します。uniqueNgrams<missing> 値が含まれている場合、counts 内の対応する値が無視されます。

入力引数

すべて展開する

入力文書。tokenizedDocument 配列、単語の string 配列、または文字ベクトルの cell 配列として指定します。documents は、tokenizedDocument 配列でない場合、各要素が単語である単一の文書を表す行ベクトルでなければなりません。複数の文書を指定するには、tokenizedDocument 配列を使用します。

一意の n-gram のリスト。NumNgramsmaxN 列の string 配列または文字ベクトルの cell 配列として指定します。ここで、NumNgrams は一意の n-gram の数、maxN は最も大きな n-gram の長さです。

uniqueNgrams(i,j) の値は、i 番目の n-gram の j 番目の単語です。i 番目の n-gram の単語数が maxN 未満の場合、uniqueNgramsi 番目の行の残りのエントリは空になります。

uniqueNgrams<missing> が含まれている場合、関数は counts 内の対応する値を無視します。

各 n-gram には少なくとも 1 つの単語がなければなりません。

例: ["An" ""; "An" "example"; "example" ""]

データ型: string | cell

uniqueNgrams の行に対応する n-gram の頻度カウント。非負の整数の行列として指定します。値 counts(i,j) は、uniqueNgrams(j,:) の n-gram が i 番目の文書に出現する回数に対応します。

counts には、uniqueNgrams の行と同じ数の列がなければなりません。

n-gram の長さ。正の整数または正の整数のベクトルとして指定します。

プロパティ

すべて展開する

文書ごとの n-gram のカウント。スパース行列として指定します。

モデル内の一意の n-gram。string 配列として指定します。Ngrams(i,j) は、i 番目の n-gram の j 番目の単語です。Ngrams の列数が n-gram 内の単語数より多い場合、残りのエントリは空になります。

n-gram の長さ。正の整数または正の整数のベクトルとして指定します。

モデル内の一意の単語。string ベクトルとして指定します。

データ型: string

可視にする n-gram の数。非負の整数として指定します。

可視にする文書の数。非負の整数として指定します。

オブジェクト関数

encodeEncode documents as matrix of word or n-gram counts
tfidf単語頻度-逆文書頻度 (tf-idf) 行列
topkngramsMost frequent n-grams
addDocumentAdd documents to bag-of-words or bag-of-n-grams model
removeDocumentRemove documents from bag-of-words or bag-of-n-grams model
removeEmptyDocumentsRemove empty documents from tokenized document array, bag-of-words model, or bag-of-n-grams model
removeNgramsRemove n-grams from bag-of-n-grams model
removeInfrequentNgramsRemove infrequently seen n-grams from bag-of-n-grams model
joinCombine multiple bag-of-words or bag-of-n-grams models
wordcloudCreate word cloud chart from text, bag-of-words model, bag-of-n-grams model, or LDA model

すべて折りたたむ

サンプル データを読み込みます。ファイル sonnetsPreprocessed.txt には、シェイクスピアのソネット集の前処理されたバージョンが格納されています。ファイルには、1 行に 1 つのソネットが含まれ、単語がスペースで区切られています。sonnetsPreprocessed.txt からテキストを抽出し、テキストを改行文字で文書に分割した後、文書をトークン化します。

filename = "sonnetsPreprocessed.txt";
str = extractFileText(filename);
textData = split(str,newline);
documents = tokenizedDocument(textData);
documents(1:10)
ans = 
  10×1 tokenizedDocument:

    70 tokens: fairest creatures desire increase thereby beautys rose might never die riper time decease tender heir might bear memory thou contracted thine own bright eyes feedst thy lights flame selfsubstantial fuel making famine abundance lies thy self thy foe thy sweet self cruel thou art worlds fresh ornament herald gaudy spring thine own bud buriest thy content tender churl makst waste niggarding pity world else glutton eat worlds due grave thee
    71 tokens: forty winters shall besiege thy brow dig deep trenches thy beautys field thy youths proud livery gazed tatterd weed small worth held asked thy beauty lies treasure thy lusty days say thine own deep sunken eyes alleating shame thriftless praise praise deservd thy beautys thou couldst answer fair child mine shall sum count make old excuse proving beauty succession thine new made thou art old thy blood warm thou feelst cold
    65 tokens: look thy glass tell face thou viewest time face form another whose fresh repair thou renewest thou dost beguile world unbless mother fair whose uneard womb disdains tillage thy husbandry fond tomb selflove stop posterity thou art thy mothers glass thee calls back lovely april prime thou windows thine age shalt despite wrinkles thy golden time thou live rememberd die single thine image dies thee
    71 tokens: unthrifty loveliness why dost thou spend upon thy self thy beautys legacy natures bequest gives nothing doth lend frank lends free beauteous niggard why dost thou abuse bounteous largess thee give profitless usurer why dost thou great sum sums yet canst live traffic thy self alone thou thy self thy sweet self dost deceive nature calls thee gone acceptable audit canst thou leave thy unused beauty tombed thee lives th executor
    61 tokens: hours gentle work frame lovely gaze every eye doth dwell play tyrants same unfair fairly doth excel neverresting time leads summer hideous winter confounds sap checked frost lusty leaves quite gone beauty oersnowed bareness every summers distillation left liquid prisoner pent walls glass beautys effect beauty bereft nor nor remembrance flowers distilld though winter meet leese show substance still lives sweet
    68 tokens: let winters ragged hand deface thee thy summer ere thou distilld make sweet vial treasure thou place beautys treasure ere selfkilld forbidden usury happies pay willing loan thats thy self breed another thee ten times happier ten ten times thy self happier thou art ten thine ten times refigurd thee death thou shouldst depart leaving thee living posterity selfwilld thou art fair deaths conquest make worms thine heir
    64 tokens: lo orient gracious light lifts up burning head eye doth homage newappearing sight serving looks sacred majesty climbd steepup heavenly hill resembling strong youth middle age yet mortal looks adore beauty still attending golden pilgrimage highmost pitch weary car like feeble age reeleth day eyes fore duteous converted low tract look another way thou thyself outgoing thy noon unlookd diest unless thou get son
    70 tokens: music hear why hearst thou music sadly sweets sweets war joy delights joy why lovst thou thou receivst gladly else receivst pleasure thine annoy true concord welltuned sounds unions married offend thine ear sweetly chide thee confounds singleness parts thou shouldst bear mark string sweet husband another strikes mutual ordering resembling sire child happy mother pleasing note sing whose speechless song many seeming sings thee thou single wilt prove none
    70 tokens: fear wet widows eye thou consumst thy self single life ah thou issueless shalt hap die world wail thee like makeless wife world thy widow still weep thou form thee hast left behind every private widow well keep childrens eyes husbands shape mind look unthrift world doth spend shifts place still world enjoys beautys waste hath world end kept unused user destroys love toward others bosom sits murdrous shame commits
    69 tokens: shame deny thou bearst love thy self art unprovident grant thou wilt thou art belovd many thou none lovst evident thou art possessd murderous hate gainst thy self thou stickst conspire seeking beauteous roof ruinate repair thy chief desire o change thy thought change mind shall hate fairer lodgd gentle love thy presence gracious kind thyself least kindhearted prove make thee another self love beauty still live thine thee

bag-of-n-grams モデルを作成します。

bag = bagOfNgrams(documents)
bag = 
  bagOfNgrams with properties:

          Counts: [154×8799 double]
      Vocabulary: ["fairest"    "creatures"    "desire"    "increase"    "thereby"    "beautys"    "rose"    "might"    "never"    "die"    "riper"    "time"    "decease"    "tender"    "heir"    "bear"    "memory"    "thou"    "contracted"    …    ]
          Ngrams: [8799×2 string]
    NgramLengths: 2
       NumNgrams: 8799
    NumDocuments: 154

ワード クラウドを使用してモデルを可視化します。

figure 
wordcloud(bag);

Figure contains an object of type wordcloud.

サンプル データを読み込みます。ファイル sonnetsPreprocessed.txt には、シェイクスピアのソネット集の前処理されたバージョンが格納されています。ファイルには、1 行に 1 つのソネットが含まれ、単語がスペースで区切られています。sonnetsPreprocessed.txt からテキストを抽出し、テキストを改行文字で文書に分割した後、文書をトークン化します。

filename = "sonnetsPreprocessed.txt";
str = extractFileText(filename);
textData = split(str,newline);
documents = tokenizedDocument(textData);

bag-of-n-grams モデルを作成します。長さ 2 と長さ 3 の n-gram (バイグラムとトリグラム) をカウントするには、'NgramLengths' をベクトル [2 3] に指定します。

bag = bagOfNgrams(documents,'NgramLengths',[2 3])
bag = 
  bagOfNgrams with properties:

          Counts: [154×18022 double]
      Vocabulary: [1×3092 string]
          Ngrams: [18022×3 string]
    NgramLengths: [2 3]
       NumNgrams: 18022
    NumDocuments: 154

長さ 2 の最も一般的な n-gram (バイグラム) を 10 個表示します。

topkngrams(bag,10,'NGramLengths',2)
ans=10×3 table
             Ngram             Count    NgramLength
    _______________________    _____    ___________

    "thou"    "art"      ""     34           2     
    "mine"    "eye"      ""     15           2     
    "thy"     "self"     ""     14           2     
    "thou"    "dost"     ""     13           2     
    "mine"    "own"      ""     13           2     
    "thy"     "sweet"    ""     12           2     
    "thy"     "love"     ""     11           2     
    "dost"    "thou"     ""     10           2     
    "thou"    "wilt"     ""     10           2     
    "love"    "thee"     ""      9           2     

長さ 3 の最も一般的な n-gram (トリグラム) を 10 個表示します。

 topkngrams(bag,10,'NGramLengths',3)
ans=10×3 table
               Ngram                Count    NgramLength
    ____________________________    _____    ___________

    "thy"     "sweet"    "self"       4           3     
    "why"     "dost"     "thou"       4           3     
    "thy"     "self"     "thy"        3           3     
    "thou"    "thy"      "self"       3           3     
    "mine"    "eye"      "heart"      3           3     
    "thou"    "shalt"    "find"       3           3     
    "fair"    "kind"     "true"       3           3     
    "thou"    "art"      "fair"       2           3     
    "love"    "thy"      "self"       2           3     
    "thy"     "self"     "thou"       2           3     

一意の n-gram の string 配列およびカウントの行列を使用して、bag-of-n-grams モデルを作成します。

sonnetsBigramCounts.mat から、例の n-gram とカウントを読み込みます。このファイルには、一意の n-gram を格納する string 配列 uniqueNgrams と、n-gram の頻度カウントを格納する行列 counts が含まれています。

load sonnetsBigramCounts.mat

uniqueNgrams 内の最初のいくつかの n-gram を表示します。

uniqueNgrams(1:10,:)
ans = 10x2 string
    "fairest"      "creatures"
    "creatures"    "desire"   
    "desire"       "increase" 
    "increase"     "thereby"  
    "thereby"      "beautys"  
    "beautys"      "rose"     
    "rose"         "might"    
    "might"        "never"    
    "never"        "die"      
    "die"          "riper"    

bag-of-n-grams モデルを作成します。

bag = bagOfNgrams(uniqueNgrams,counts)
bag = 
  bagOfNgrams with properties:

          Counts: [154x8799 double]
      Vocabulary: ["fairest"    "creatures"    "desire"    "increase"    "thereby"    "beautys"    "rose"    "might"    "never"    "die"    "riper"    "time"    "decease"    "tender"    "heir"    "bear"    "memory"    "thou"    ...    ] (1x3092 string)
          Ngrams: [8799x2 string]
    NgramLengths: 2
       NumNgrams: 8799
    NumDocuments: 154

バージョン履歴

R2018a で導入