main content

analyze text data using topic models -凯发k8网页登录

this example shows how to use the latent dirichlet allocation (lda) topic model to analyze text data.

a latent dirichlet allocation (lda) model is a topic model which discovers underlying topics in a collection of documents and infers the word probabilities in topics.

load and extract text data

load the example data. the file factoryreports.csv contains factory reports, including a text description and categorical labels for each event.

data = readtable("factoryreports.csv",texttype="string");
head(data)
ans=8×5 table
                                 description                                       category          urgency          resolution         cost 
    _____________________________________________________________________    ____________________    ________    ____________________    _____
    "items are occasionally getting stuck in the scanner spools."            "mechanical failure"    "medium"    "readjust machine"         45
    "loud rattling and banging sounds are coming from assembler pistons."    "mechanical failure"    "medium"    "readjust machine"         35
    "there are cuts to the power when starting the plant."                   "electronic failure"    "high"      "full replacement"      16200
    "fried capacitors in the assembler."                                     "electronic failure"    "high"      "replace components"      352
    "mixer tripped the fuses."                                               "electronic failure"    "low"       "add to watch list"        55
    "burst pipe in the constructing agent is spraying coolant."              "leak"                  "high"      "replace components"      371
    "a fuse is blown in the mixer."                                          "electronic failure"    "low"       "replace components"      441
    "things continue to tumble off of the belt."                             "mechanical failure"    "low"       "readjust machine"         38

extract the text data from the field description.

textdata = data.description;
textdata(1:10)
ans = 10×1 string
    "items are occasionally getting stuck in the scanner spools."
    "loud rattling and banging sounds are coming from assembler pistons."
    "there are cuts to the power when starting the plant."
    "fried capacitors in the assembler."
    "mixer tripped the fuses."
    "burst pipe in the constructing agent is spraying coolant."
    "a fuse is blown in the mixer."
    "things continue to tumble off of the belt."
    "falling items from the conveyor belt."
    "the scanner reel is split, it will soon begin to curve."

prepare text data for analysis

create a function which tokenizes and preprocesses the text data so it can be used for analysis. the function preprocesstext, listed in the preprocessing function section of the example, performs the following steps in order:

  1. tokenize the text using tokenizeddocument.

  2. lemmatize the words using normalizewords.

  3. erase punctuation using erasepunctuation.

  4. remove a list of stop words (such as "and", "of", and "the") using removestopwords.

  5. remove words with 2 or fewer characters using removeshortwords.

  6. remove words with 15 or more characters using removelongwords.

prepare the text data for analysis using the preprocesstext function.

documents = preprocesstext(textdata);
documents(1:5)
ans = 
  5×1 tokenizeddocument:
    6 tokens: item occasionally get stuck scanner spool
    7 tokens: loud rattling bang sound come assembler piston
    4 tokens: cut power start plant
    3 tokens: fry capacitor assembler
    3 tokens: mixer trip fuse

create a bag-of-words model from the tokenized documents.

bag = bagofwords(documents)
bag = 
  bagofwords with properties:
          counts: [480×338 double]
      vocabulary: [1×338 string]
        numwords: 338
    numdocuments: 480

remove words from the bag-of-words model that have do not appear more than two times in total. remove any documents containing no words from the bag-of-words model.

bag = removeinfrequentwords(bag,2);
bag = removeemptydocuments(bag)
bag = 
  bagofwords with properties:
          counts: [480×158 double]
      vocabulary: [1×158 string]
        numwords: 158
    numdocuments: 480

fit lda model

fit an lda model with 7 topics. for an example showing how to choose the number of topics, see choose number of topics for lda model. to suppress verbose output, set the verbose option to 0. for reproducibility, use the rng function with the "default" option.

rng("default")
numtopics = 7;
mdl = fitlda(bag,numtopics,verbose=0);

if you have a large dataset, then the stochastic approximate variational bayes solver is usually better suited as it can fit a good model in fewer passes of the data. the default solver for fitlda (collapsed gibbs sampling) can be more accurate at the cost of taking longer to run. to use stochastic approximate variational bayes, set the solver option to "savb". for an example showing how to compare lda solvers, see compare lda solvers.

visualize topics using word clouds

you can use word clouds to view the words with the highest probabilities in each topic. visualize the topics using word clouds.

figure
t = tiledlayout("flow");
title(t,"lda topics")
for i = 1:numtopics
    nexttile
    wordcloud(mdl,i);
    title("topic "   i)
end

view mixtures of topics in documents

create an array of tokenized documents for a set of previously unseen documents using the same preprocessing function as the training data.

str = [
    "coolant is pooling underneath assembler."
    "sorter blows fuses at start up."
    "there are some very loud rattling sounds coming from the assembler."];
newdocuments = preprocesstext(str);

use the transform function to transform the documents into vectors of topic probabilities. note that for very short documents, the topic mixtures may not be a strong representation of the document content.

topicmixtures = transform(mdl,newdocuments);

plot the document topic probabilities of the first document in a bar chart. to label the topics, use the top three words of the corresponding topic.

for i = 1:numtopics
    top = topkwords(mdl,3,i);
    topwords(i) = join(top.word,", ");
end
figure
bar(topicmixtures(1,:))
xlabel("topic")
xticklabels(topwords);
ylabel("probability")
title("document topic probabilities")

visualize multiple topic mixtures using stacked bar charts. visualize the topic mixtures of the documents.

figure
barh(topicmixtures,"stacked")
xlim([0 1])
title("topic mixtures")
xlabel("topic probability")
ylabel("document")
legend(topwords, ...
    location="southoutside", ...
    numcolumns=2)

preprocessing function

the function preprocesstext, performs the following steps in order:

  1. tokenize the text using tokenizeddocument.

  2. lemmatize the words using normalizewords.

  3. erase punctuation using erasepunctuation.

  4. remove a list of stop words (such as "and", "of", and "the") using removestopwords.

  5. remove words with 2 or fewer characters using removeshortwords.

  6. remove words with 15 or more characters using removelongwords.

function documents = preprocesstext(textdata)
% tokenize the text.
documents = tokenizeddocument(textdata);
% lemmatize the words.
documents = addpartofspeechdetails(documents);
documents = normalizewords(documents,style="lemma");
% erase punctuation.
documents = erasepunctuation(documents);
% remove a list of stop words.
documents = removestopwords(documents);
% remove words with 2 or fewer characters, and words with 15 or greater
% characters.
documents = removeshortwords(documents,2);
documents = removelongwords(documents,15);
end

see also

| | | | | | | | |

related topics

网站地图