Main Content

이 번역 페이지는 최신 내용을 담고 있지 않습니다. 최신 내용을 영문으로 보려면 여기를 클릭하십시오.

bagOfNgrams

Bag-of-n-grams 모델

설명

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형 배열 또는 문자형 벡터로 구성된 셀형 배열로 지정됩니다. documentstokenizedDocument 배열이 아닌 경우 이는 단일 문서를 나타내고 각 요소가 단어인 행 벡터여야 합니다. 문서를 여러 개 지정하려면 tokenizedDocument 배열을 사용하십시오.

고유한 n-gram 목록으로, NumNgramsxmaxN string형 배열 또는 문자형 벡터로 구성된 셀형 배열로 지정됩니다. 여기서 NumNgrams는 고유한 n-gram의 개수이고, maxN은 가장 큰 n-gram의 길이입니다.

uniqueNgrams(i,j)의 값은 i번째 n-gram 중 j번째 단어입니다. i번째 n-gram의 단어 수가 maxN보다 작은 경우 uniqueNgramsi번째 행의 나머지 요소는 비어 있습니다.

uniqueNgrams<missing>이 있는 경우 함수는 counts의 해당 값은 무시됩니다.

각 n-gram에는 최소 하나 이상의 단어가 있어야 합니다.

예: ["An" ""; "An" "example"; "example" ""]

데이터형: string | cell

uniqueNgrams의 행에 해당하는 n-gram의 빈도 수로, 음이 아닌 정수로 구성된 행렬로 지정됩니다. 값 counts(i,j)는 i번째 문서에서 n-gram uniqueNgrams(j,:)이 나오는 횟수에 해당합니다.

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이 나오는 횟수로, 음이 아닌 정수로 지정됩니다.

문서가 나오는 횟수로, 음이 아닌 정수로 지정됩니다.

객체 함수

encode문서를 단어 개수 또는 n-gram 개수로 구성된 행렬로 인코딩
tfidfTF-IDF(단어 빈도-역 문서 빈도) 행렬
topkngrams빈도가 가장 높은 n-gram
addDocumentbag-of-words 모델 또는 bag-of-n-grams 모델에 문서 추가
removeDocumentbag-of-words 모델 또는 bag-of-n-grams 모델에서 문서 제거
removeEmptyDocuments토큰화된 문서 배열, bag-of-words 모델 또는 bag-of-n-grams 모델에서 빈 문서 제거
removeNgramsbag-of-n-grams 모델에서 n-gram 제거
removeInfrequentNgramsbag-of-n-grams 모델에서 낮은 빈도로 나오는 n-gram 제거
joinCombine multiple bag-of-words or bag-of-n-grams models
wordcloud텍스트, bag-of-words 모델, bag-of-n-grams 모델 또는 LDA 모델에서 워드 클라우드 차트 만들기

예제

모두 축소

예제 데이터를 불러옵니다. 파일 sonnetsPreprocessed.txt에는 셰익스피어 소네트의 전처리된 버전이 들어 있습니다. 파일에는 한 줄에 하나씩 소네트가 들어 있으며 단어가 공백으로 구분되어 있습니다. 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);

예제 데이터를 불러옵니다. 파일 sonnetsPreprocessed.txt에는 셰익스피어 소네트의 전처리된 버전이 들어 있습니다. 파일에는 한 줄에 하나씩 소네트가 들어 있으며 단어가 공백으로 구분되어 있습니다. sonnetsPreprocessed.txt에서 텍스트를 추출하고, 추출한 텍스트를 새 줄 문자에서 문서로 분할한 후 그 문서를 토큰화합니다.

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

bag-of-n-grams 모델을 만듭니다. 길이가 2(바이그램)인 n-gram과 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에 개발됨