bagOfNgrams

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

Описание

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

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

Создание

Синтаксис

bag = bagOfNgrams
bag = bagOfNgrams(documents)
bag = bagOfNgrams(___,'NgramLengths',lengths)
bag = bagOfNgrams(uniqueNgrams,counts)

Описание

bag = bagOfNgrams создает пустой мешок n модели граммов.

пример

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

пример

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

пример

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

Входные параметры

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

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

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

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

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

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

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

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

Подсчет частот N-грамм, соответствующих строкам uniqueNgrams, заданного как матрица неотрицательных целых чисел. Значение counts(i,j) соответствует числу раз n-грамма uniqueNgrams(j,:), появляется в i th документ.

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

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

Свойства

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

N-грамма рассчитывает на документ, заданный как разреженная матрица.

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

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

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

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

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

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

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

encodeЗакодируйте документы как матрицу количеств n-граммы или слова
tfidfНазовите Обратную Частотой Частоту Документа (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 модели граммов.

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);

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

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

Создайте мешок n модели граммов. Чтобы считать 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 array
    "fairest"      "creatures"
    "creatures"    "desire"   
    "desire"       "increase" 
    "increase"     "thereby"  
    "thereby"      "beautys"  
    "beautys"      "rose"     
    "rose"         "might"    
    "might"        "never"    
    "never"        "die"      
    "die"          "riper"    

Создайте мешок n модели граммов.

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

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

Введенный в R2018a

Для просмотра документации необходимо авторизоваться на сайте