В этом примере показано, как использовать модель темы LDA для анализа текстовых данных.
Модель LDA (Latent Dirichlet Allocation) - это модель темы, которая обнаруживает основные темы в коллекции документов и выводит вероятности слов в темах.
Загрузите данные примера. Файл factoryReports.csv содержит заводские отчеты, включая текстовое описание и категориальные метки для каждого события.
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
Извлеките текстовые данные из поля 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."
Создайте функцию, которая маркирует и предварительно обрабатывает текстовые данные, чтобы их можно было использовать для анализа. Функция preprocessText, перечисленное в конце примера, выполняет следующие шаги в порядке:
Маркировка текста с помощью tokenizedDocument.
Лемматизировать слова с помощью normalizeWords.
Стереть пунктуацию с помощью erasePunctuation.
Удалите список стоп-слов (например, «and», «of» и «the»), используя removeStopWords.
Удаление слов, содержащих не более 2 символов removeShortWords.
Удаление слов с 15 или более символами с помощью removeLongWords.
Использовать функцию предварительной обработки preprocessText для подготовки текстовых данных.
documents = preprocessText(textData); documents(1:5)
ans =
5×1 tokenizedDocument:
6 tokens: items occasionally get stuck scanner spool
7 tokens: loud rattle bang sound come assembler piston
4 tokens: cut power start plant
3 tokens: fry capacitor assembler
3 tokens: mixer trip fuse
Создайте модель пакета слов из маркированных документов.
bag = bagOfWords(documents)
bag =
bagOfWords with properties:
Counts: [480×351 double]
Vocabulary: [1×351 string]
NumWords: 351
NumDocuments: 480
Удалите слова из модели сумки слов, которые не появлялись более двух раз. Удалите все документы, не содержащие слов, из модели сумки слов.
bag = removeInfrequentWords(bag,2); bag = removeEmptyDocuments(bag)
bag =
bagOfWords with properties:
Counts: [480×162 double]
Vocabulary: [1×162 string]
NumWords: 162
NumDocuments: 480
Поместите модель LDA с 7 темами. Пример выбора количества разделов см. в разделе Выбор количества разделов для модели LDA. Для подавления подробных выходных данных установите 'Verbose' в 0.
numTopics = 7;
mdl = fitlda(bag,numTopics,'Verbose',0);Если имеется большой набор данных, то стохастический аппроксимационный вариационный решатель Байеса обычно лучше подходит, так как он может соответствовать хорошей модели за меньшее количество проходов данных. Решатель по умолчанию для fitlda (свернутая выборка Гиббса) может быть более точной при стоимости, занимающей больше времени. Чтобы использовать стохастический аппроксимационный вариационный Байес, установите 'Solver' опция для 'savb'. Пример сравнения решателей LDA см. в разделе Сравнение решателей LDA.
Для просмотра слов с наибольшей вероятностью в каждом разделе можно использовать облака слов. Визуализируйте первые четыре раздела, используя облака слов.
figure; for topicIdx = 1:4 subplot(2,2,topicIdx) wordcloud(mdl,topicIdx); title("Topic " + topicIdx) end

Использовать transform преобразование документов в векторы вероятностей темы.
newDocument = tokenizedDocument("Coolant is pooling underneath sorter."); topicMixture = transform(mdl,newDocument); figure bar(topicMixture) xlabel("Topic Index") ylabel("Probability") title("Document Topic Probabilities")

Визуализация смесей по нескольким темам с помощью сгруппированных гистограмм. Визуализация тематических смесей первых 5 входных документов.
figure topicMixtures = transform(mdl,documents(1:5)); barh(topicMixtures(1:5,:),'stacked') xlim([0 1]) title("Topic Mixtures") xlabel("Topic Probability") ylabel("Document") legend("Topic " + string(1:numTopics),'Location','northeastoutside')

Функция preprocessText, выполняет следующие шаги в порядке:
Маркировка текста с помощью tokenizedDocument.
Лемматизировать слова с помощью normalizeWords.
Стереть пунктуацию с помощью erasePunctuation.
Удалите список стоп-слов (например, «and», «of» и «the»), используя removeStopWords.
Удаление слов, содержащих не более 2 символов removeShortWords.
Удаление слов с 15 или более символами с помощью 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
addPartOfSpeechDetails | bagOfWords | fitlda | ldaModel | removeEmptyDocuments | removeInfrequentWords | removeStopWords | tokenizedDocument | transform | wordcloud