Main Content

분류를 위한 간단한 텍스트 모델 만들기

이 예제에서는 bag-of-words 모델을 사용하여 단어 빈도 수로 간단한 텍스트 분류기를 훈련시키는 방법을 보여줍니다.

단어 빈도 수를 예측 변수로 사용하는 간단한 분류 모델을 만들 수 있습니다. 이 예제에서는 텍스트 설명을 사용하여 공장 보고서의 범주를 예측하도록 간단한 분류 모델을 훈련시킵니다.

텍스트 데이터 불러오기 및 추출하기

예제 데이터를 불러옵니다. factoryReports.csv 파일에는 각 보고서에 대한 텍스트 설명과 범주 레이블이 포함된 공장 보고서가 들어 있습니다.

filename = "factoryReports.csv";
data = readtable(filename,'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

테이블의 Category 열에 있는 레이블을 categorical형으로 변환하고 히스토그램을 사용하여 데이터의 클래스 분포를 표시합니다.

data.Category = categorical(data.Category);
figure
histogram(data.Category)
xlabel("Class")
ylabel("Frequency")
title("Class Distribution")

데이터를 훈련 파티션 및 홀드아웃 테스트 세트로 분할합니다. 홀드아웃 백분율을 20%로 지정합니다.

cvp = cvpartition(data.Category,'Holdout',0.1);
dataTrain = data(cvp.training,:);
dataTest = data(cvp.test,:);

테이블에서 텍스트 데이터와 레이블을 추출합니다.

textDataTrain = dataTrain.Description;
textDataTest = dataTest.Description;
YTrain = dataTrain.Category;
YTest = dataTest.Category;

분석할 텍스트 데이터 준비하기

분석에 사용할 수 있도록 텍스트 데이터를 토큰화하고 전처리하는 함수를 만듭니다. 함수 preprocessText는 다음 단계를 순서대로 수행합니다.

  1. tokenizedDocument를 사용하여 텍스트를 토큰화합니다.

  2. removeStopWords를 사용하여 불용어 목록(예: "and", "of", "the")을 제거합니다.

  3. normalizeWords를 사용하여 단어의 표제어를 추출합니다.

  4. erasePunctuation을 사용하여 문장 부호를 지웁니다.

  5. removeShortWords를 사용하여 2자 이하로 이루어진 단어를 제거합니다.

  6. removeLongWords를 사용하여 15자 이상으로 이루어진 단어를 제거합니다.

예제 전처리 함수 preprocessText를 사용하여 텍스트 데이터를 준비합니다.

documents = preprocessText(textDataTrain);
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-of-words 모델을 만듭니다.

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

          Counts: [432×336 double]
      Vocabulary: [1×336 string]
        NumWords: 336
    NumDocuments: 432

총 2회 이하로 나타나는 단어를 bag-of-words 모델에서 제거합니다. bag-of-words 모델에서 단어를 포함하지 않는 모든 문서를 제거한 후 레이블에서 해당 요소를 제거합니다.

bag = removeInfrequentWords(bag,2);
[bag,idx] = removeEmptyDocuments(bag);
YTrain(idx) = [];
bag
bag = 
  bagOfWords with properties:

          Counts: [432×155 double]
      Vocabulary: [1×155 string]
        NumWords: 155
    NumDocuments: 432

지도 분류기 훈련시키기

bag-of-words 모델의 단어 빈도 수와 레이블을 사용하여 지도 분류 모델을 훈련시킵니다.

fitcecoc를 사용하여 다중 클래스 선형 분류 모델을 훈련시킵니다. bag-of-words 모델의 Counts 속성을 예측 변수로 지정하고 이벤트 유형 레이블을 응답 변수로 지정합니다. 학습기를 선형으로 지정합니다. 이러한 학습기는 희소 데이터 입력값을 지원합니다.

XTrain = bag.Counts;
mdl = fitcecoc(XTrain,YTrain,'Learners','linear')
mdl = 
  CompactClassificationECOC
      ResponseName: 'Y'
        ClassNames: [Electronic Failure    Leak    Mechanical Failure    Software Failure]
    ScoreTransform: 'none'
    BinaryLearners: {6×1 cell}
      CodingMatrix: [4×6 double]


  Properties, Methods

더 나은 피팅을 위해 선형 학습기의 여러 다른 파라미터를 지정해 볼 수 있습니다. 선형 분류 학습기 템플릿에 대한 자세한 내용은 templateLinear 항목을 참조하십시오.

분류기 테스트하기

훈련된 모델을 사용하여 테스트 데이터의 레이블을 예측하고 분류 정확도를 계산합니다. 분류 정확도는 모델이 정확하게 예측하는 레이블의 비율입니다.

훈련 데이터와 동일한 전처리 단계를 사용하여 테스트 데이터를 전처리합니다. 결과 테스트 문서를 bag-of-words 모델에 따라 단어 빈도 수로 구성된 행렬로 인코딩합니다.

documentsTest = preprocessText(textDataTest);
XTest = encode(bag,documentsTest);

훈련된 모델을 사용하여 테스트 데이터의 레이블을 예측하고 분류 정확도를 계산합니다.

YPred = predict(mdl,XTest);
acc = sum(YPred == YTest)/numel(YTest)
acc = 0.8542

새 데이터를 사용하여 예측하기

새 공장 보고서의 이벤트 유형을 분류합니다. 새 공장 보고서를 포함하는 string형 배열을 만듭니다.

str = [
    "Coolant is pooling underneath sorter."
    "Sorter blows fuses at start up."
    "There are some very loud rattling sounds coming from the assembler."];
documentsNew = preprocessText(str);
XNew = encode(bag,documentsNew);
labelsNew = predict(mdl,XNew)
labelsNew = 3×1 categorical
     Leak 
     Electronic Failure 
     Mechanical Failure 

예제 전처리 함수

함수 preprocessText는 다음 단계를 순서대로 수행합니다.

  1. tokenizedDocument를 사용하여 텍스트를 토큰화합니다.

  2. removeStopWords를 사용하여 불용어 목록(예: "and", "of", "the")을 제거합니다.

  3. normalizeWords를 사용하여 단어의 표제어를 추출합니다.

  4. erasePunctuation을 사용하여 문장 부호를 지웁니다.

  5. removeShortWords를 사용하여 2자 이하로 이루어진 단어를 제거합니다.

  6. removeLongWords를 사용하여 15자 이상으로 이루어진 단어를 제거합니다.

function documents = preprocessText(textData)

% Tokenize the text.
documents = tokenizedDocument(textData);

% Remove a list of stop words then lemmatize the words. To improve
% lemmatization, first use addPartOfSpeechDetails.
documents = addPartOfSpeechDetails(documents);
documents = removeStopWords(documents);
documents = normalizeWords(documents,'Style','lemma');

% Erase punctuation.
documents = erasePunctuation(documents);

% Remove words with 2 or fewer characters, and words with 15 or more
% characters.
documents = removeShortWords(documents,2);
documents = removeLongWords(documents,15);

end

참고 항목

| | | | | | | | |

관련 항목