exponenta event banner

bagOfNgrams

Модель мешка n-граммов

Описание

Модель мешка n-граммов записывает количество раз, которое каждый n-грамм появляется в каждом документе коллекции. N-грамм - это совокупность n последовательных слов.

bagOfNgrams не разбивает текст на слова. Сведения о создании массива маркированных документов см. в разделе tokenizedDocument.

Создание

Описание

bag = bagOfNgrams создает пустую модель мешка n-grams.

пример

bag = bagOfNgrams(documents) создает модель bag-of-n-grams и подсчитывает биграммы (пары слов) в documents.

пример

bag = bagOfNgrams(___,'NgramLengths',lengths) подсчитывает n-граммов указанных длин, используя любой из предыдущих синтаксисов.

пример

bag = bagOfNgrams(uniqueNgrams,counts) создает модель мешка n-грамм, используя n-грамм в uniqueNgrams и соответствующие счетчики частоты в counts. Если uniqueNgrams содержит <missing> значения, затем соответствующие значения в counts игнорируются.

Входные аргументы

развернуть все

Исходные документы, указанные как tokenizedDocument массив, строковый массив слов или массив ячеек символьных векторов. Если documents не является tokenizedDocument массив, то это должен быть вектор строки, представляющий один документ, где каждый элемент является словом. Чтобы указать несколько документов, используйте tokenizedDocument массив.

Уникальный n-граммовый список, указанный как NumNgramsоколо-maxN строковый массив или массив ячеек символьных векторов, где NumNgrams - количество уникальных n-граммов, и maxN - длина наибольшего n-грамма.

Значение uniqueNgrams(i,j) является jпятое слово iН-грамм. Если количество слов в in-грамм меньше maxN, то остальные записи iтретий ряд uniqueNgrams пусты.

Если uniqueNgrams содержит <missing>, то функция игнорирует соответствующие значения в counts.

Каждый n-грамм должен иметь по крайней мере одно слово.

Пример: ["An" ""; "An" "example"; "example" ""]

Типы данных: string | cell

Число частот n-граммов, соответствующих строкам uniqueNgrams, указанный как матрица неотрицательных целых чисел. Стоимость counts(i,j) соответствует числу n-граммов uniqueNgrams(j,:) отображается в i-ом документе.

counts должно иметь столько столбцов, сколько uniqueNgrams имеет строки.

Длины n-граммов, определенные как положительное целое число или вектор положительных целых чисел.

Свойства

развернуть все

Число N граммов в документе, указанное как разреженная матрица.

Уникальный n-грамм в модели, указанный как строковый массив. Ngrams(i,j) является jпятое слово iН-грамм. Если количество столбцов Ngrams больше числа слов в n-грамме, остальные записи пусты.

Длины n-граммов, определенные как положительное целое число или вектор положительных целых чисел.

Уникальные слова в модели, указанные как строковый вектор.

Типы данных: string

Число n-граммов, указанное как неотрицательное целое число.

Количество видимых документов, указанных как неотрицательное целое число.

Функции объекта

encodeКодировать документы как матрицу числа слов или n-граммов
tfidfМатрица Term Frequency-Inverse Document Frequency (tf-idf)
topkngramsНаиболее часто n-грамм
addDocumentДобавление документов в модель «мешок слов» или «мешок n-грамм»
removeDocumentУдалить документы из модели мешка слов или мешка n граммов
removeEmptyDocumentsУдаление пустых документов из маркированного массива документов, модели мешка слов или модели мешка n грамм
removeNgramsУдалить n-грамм из модели мешков n-грамм
removeInfrequentNgramsУдаление редко встречающихся n-грамм из модели мешков n-грамм
joinОбъединение нескольких моделей мешков слов или мешков n граммов
wordcloudСоздание таблицы облака слов из текста, модели мешка слов, модели мешка n граммов или модели LDA

Примеры

свернуть все

Загрузите данные примера. Файл sonnetsPreprocessed.txt содержит предварительно обработанные версии сонетов Шекспира. Файл содержит один сонет на строку со словами, разделенными пробелом. Извлечь текст из sonnetsPreprocessed.txtразделите текст на документы с новыми символами, а затем пометьте документы.

filename = "sonnetsPreprocessed.txt";
str = extractFileText(filename);
textData = split(str,newline);
documents = tokenizedDocument(textData);
documents(1:10)
ans = 
  10x1 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

Создайте модель мешка n-grams.

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

          Counts: [154x8799 double]
      Vocabulary: [1x3092 string]
          Ngrams: [8799x2 string]
    NgramLengths: 2
       NumNgrams: 8799
    NumDocuments: 154

Визуализация модели с помощью облака слов.

figure 
wordcloud(bag);

Figure contains an object of type wordcloud.

Загрузите данные примера. Файл sonnetsPreprocessed.txt содержит предварительно обработанные версии сонетов Шекспира. Файл содержит один сонет на строку со словами, разделенными пробелом. Извлечь текст из sonnetsPreprocessed.txtразделите текст на документы с новыми символами, а затем пометьте документы.

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

Создайте модель мешка n-grams. Для подсчета n-граммов длины 2 и 3 (биграмы и триграммы) укажите '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

Просмотрите 10 наиболее распространенных n-граммов длины 2 (биграмм).

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     

Просмотрите 10 наиболее распространенных n-граммов длиной 3 (триграммы).

 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-граммов, используя строковый массив уникальных n-граммов и матрицу счетчиков.

Загрузите пример n-граммов и счетчиков из sonnetsBigramCounts.mat. Этот файл содержит строковый массив uniqueNgrams, которая содержит уникальные n-граммы и матрицу counts, который содержит n-граммовые счетчики частоты.

load sonnetsBigramCounts.mat

Просмотр первых нескольких n-граммов в uniqueNgrams.

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"    

Создайте модель мешка n-grams.

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

          Counts: [154x8799 double]
      Vocabulary: [1x3092 string]
          Ngrams: [8799x2 string]
    NgramLengths: 2
       NumNgrams: 8799
    NumDocuments: 154

Представлен в R2018a