Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

text_lab2

.pdf
Скачиваний:
33
Добавлен:
05.07.2022
Размер:
366.82 Кб
Скачать

Отчет по лабораторной работе № 2

по дисциплине «Основы анализа текстовых данных»

на тему: «Предварительная обработка текстовых данных»

Цель работы:

Получить практические навыки обработки текстовых данных в среде Jupiter Notebook (Эта лабораторная выполнялась в среде Google Colab). Научиться проводить предварительную обработку текстовых данных и выявлять параметры обработки, позволяющие добиться наилучшей точности классификации.

1. Импортирование необходимых для работы библиотек и модулей.

from sklearn.datasets import fetch_20newsgroups

from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.pipeline import Pipeline

from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import classification_report from sklearn.metrics import accuracy_score

2.Загрузка обучающей и экзаменационной выборки в соответствии с вариантом (классы

7, 14, 20).

categories = ['misc.forsale', 'sci.med', 'talk.religion.misc'] remove = ('headers', 'footers', 'quotes')

twenty_train = fetch_20newsgroups(subset='train', shuffle=True, random_state=42, categories = categories, remove = remove )

twenty_test = fetch_20newsgroups(subset='test', shuffle=True, random_state=42, categories = categories, remove = remove )

3. Вывод на экран по одному документу каждого класса.

print (twenty_train.target_names[twenty_train.target[1]]) sci.med

Вывод документа класса sci.med:

print (twenty_train.data[1]) Dear Netters,

I am not sure whether this is the right place to post my query, but I thought there may be some bilingual physicians in this newsgroup that could help. Please, excuse me for overloading the bandwidth.

I am trying to build a resource allocation program for managing a surgical operating unit in a hospital. The user interface is in English, however the terms of medical specialties I was given are in French :-( I have no medical dictionary handy, mine is a technical university :-((

I need to get the translation into English (when there is one) of the

following words. They refer to medical categories of operating rooms (theaters). I admit they may not be universally "used".

1- sceptique

2- orl

3- brulure/brule'

4- ne'onatal

5- pre'natal

6- pre'mature'

7- neurochirurgie (neuro-surgery??)

8- chirurgie ge'ne'rale

9- chirurgie plastique

10urologie (urology??)

Thank you for you help.

Cheers,

---------

Berthe Y. Choueiry

choueiry@lia.di.epfl.ch

LIA-DI, Ecole Polytechnique Federale de Lausanne, Ecublens CH-1015 Lausanne, Switzerland

Voice: +41-21-693.52.77 and +41-21-693.66.78 Fax: +41-21-693.52.25

print (twenty_train.target_names[twenty_train.target[2]]) talk.religion.misc

Вывод документа класса talk.religion.misc:

print (twenty_train.data[2])

Almost one third of the world's population claim to be Christian. But any similarity between their beliefs and lifestyle to the first century model is purely coincidental. At Luke 18:8 it states, "...nevertheless, when the son of man returns, will he really find the faith on the earth?"

print (twenty_train.target_names[twenty_train.target[4]]) misc.forsale

Вывод документа класса misc.forsale:

print (twenty_train.data[4])

The package is called Sun and Sand, it includes:

--5 days/ 4 nights(2+2) accommodations in Orlando and Daytona beach; --hotels are selected from major hotel chains and family resorts; --two adults and up to three children;

--fully transferable;

--expires at 09/93, $20 for extention of one more year;

--it needs a 45 days advance reservation (esp. for peak season), the reservation department will offer a coupon book which may give you saving up to $150.

2

--price: I bought it for $199, which is a good deal for peak seasons. For now, I will not turn down any reasonable offers. must sell.

It doesn't include transportation. And you have to pay $3/day for hotel tax.

4.Применение стемминга, запись обработанных выборок (тестовой и обучающей) в новые переменные.

import nltk

from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenize from tqdm import tqdm

ps = PorterStemmer() # стеммер с алгоритмом стемминга Porterstemmer def stemming(text: str) -> str:

# функция разделения документов каждого класса на слова и выделения основы каждого слова

words = []

for word in word_tokenize(text): # цикл по разделению документов каждого класса на слова

words.append(ps.stem(word.lower()))

return ' '.join(words) # список с основами каждого слова

def stemming_dataset(dataset: list) -> list: # функция применения стемминга resulting_list = []

for example in tqdm(dataset):#цикл по созданию индикатора применения стемминга (см. результат выполнения ячейки ниже)

resulting_list.append(stemming(example))

return resulting_list#список с основами каждого слова документов каждого класса

#создаем снова обучающую и тестовую выборки, чтобы потом применить к ним стемминг:

stem_train = fetch_20newsgroups(subset='train', shuffle=True, random_state=42, cate gories = categories, remove = remove )

stem_test = fetch_20newsgroups(subset='test', shuffle=True, random_state=42, catego ries = categories, remove = remove )

nltk.download('punkt')

#Реализуем стемминг:

stem_train['data_stem'] = stemming_dataset(stem_train['data'])#запись обработанной обучающей выборки в новую переменную

stem_test['data_stem'] = stemming_dataset(stem_test['data'])#запись обработанной те стовой выборки в новую переменную

#Удаляем лишний раздел переменных: del stem_train['data']

del stem_test['data']

5. Векторизация выборки.

3

a.Векторизация обучающей и тестовой выборки простым подсчетом слов

(CountVectorizer) и значеним max_features = 10000

vect = CountVectorizer(max_features = 10000)

vect.fit(twenty_train.data)

train_data = vect.transform(twenty_train.data) test_data = vect.transform(twenty_test.data)

b.Вывод первых 20 наиболее частотных слов всей выборки и каждого класса поотдельности.

import numpy as np

Вывод для всей выборки (Count):

x = list(zip(vect.get_feature_names(), np.ravel(train_data.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('the', 11301), ('of', 6613), ('to', 6208), ('and', 5710), ('in', 3962), ('is', 3857), ('that', 3485), ('it', 2943), ('for', 2894), ('you', 2402), ('this', 1766), ('are', 1753), ('with', 1736), ('not', 1711), ('have', 1632), ('be', 1555), ('or', 1504), ('as', 1433), ('on', 1314), ('but', 1143)]

transform_num_to_name_class = {i: twenty_train['target_names'][i] for i in range(len(twenty_train['target_names']))}

for i in range(3):

twenty_train[transform_num_to_name_class[i]] = [twenty_train['data'][j] for j in range(len(twenty_train['data'])) if twenty_train['target'][j] == i]

Вывод для класса 0 (Count):

train_data01 = vect.transform(twenty_train[transform_num_to_name_class[0]]) x = list(zip(vect.get_feature_names(), np.ravel(train_data01.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('the', 1488), ('for', 1157), ('and', 1081), ('to', 967), ('of', 755), ('in', 645), ('00', 617), ('it', 513), ('is', 510), ('you', 477), ('with', 452), ('or', 430), ('have', 378), ('are', 308), ('all', 294), ('if', 283), ('new', 278), ('this', 274), ('that', 249), ('sale', 247)]

Вывод для класса 1(Count):

train_data02 = vect.transform(twenty_train[transform_num_to_name_class[1]]) x = list(zip(vect.get_feature_names(), np.ravel(train_data02.sum(axis=0))))

def SortbyTF(inputStr):

4

return inputStr[1] x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('the', 5174), ('of', 3283), ('to', 2879), ('and', 2643), ('in', 1971), ('is', 1899), ('that', 1526), ('it', 1467), ('for', 1086), ('you', 863), ('this', 852), ('are', 812), ('be', 787), ('with', 776), ('not', 730), ('have', 700), ('or', 648), ('on', 635), ('as', 624), ('but', 530)]

Вывод для класса 2 (Count):

train_data03 = vect.transform(twenty_train[transform_num_to_name_class[2]]) x = list(zip(vect.get_feature_names(), np.ravel(train_data03.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('the', 4639), ('of', 2575), ('to', 2362), ('and', 1986), ('that', 1710), ('is', 1448), ('in', 1346), ('you', 1062), ('it', 963), ('not', 785), ('for', 651), ('as', 642), ('this', 640), ('are', 633), ('be', 573), ('have', 554), ('with', 508), ('was', 486), ('he', 470), ('they', 445)]

c. Применение процедуры отсечения стоп-слов и повтор пункта b.

vect = CountVectorizer(max_features = 10000, stop_words = 'english') vect.fit(twenty_train.data)

train_data04 = vect.transform(twenty_train.data) test_data04 = vect.transform(twenty_test.data)

Вывод для всей выборки при отсечении стоп-слов (Count):

x = list(zip(vect.get_feature_names(), np.ravel(train_data04.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('00', 640), ('people', 517), ('new', 504), ('edu', 502), ('don', 467), ('like', 461), ('good', 420), ('just', 417), ('know', 394), ('10', 358), ('use', 356), ('god', 338), ('time', 336), ('think', 328), ('does', 313), ('20', 285), ('used', 275), ('50', 261), ('com', 259), ('jesus', 258)]

Вывод для класса 0 при отсечении стоп-слов (Count):

train_data05 = vect.transform(twenty_train[transform_num_to_name_class[0]]) x = list(zip(vect.get_feature_names(), np.ravel(train_data05.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

5

[('00', 617), ('new', 278), ('sale', 247), ('50', 228), ('10', 214), ('dos', 201), ('offer', 195), ('shipping', 180), ('20', 168), ('price', 164), ('25', 155), ('15', 153), ('condition', 151), ('good', 146), ('used', 130), ('like', 129), ('edu', 128), ('asking', 121), ('mail', 121), ('interested', 120)]

Вывод для класса 1 при отсечении стоп-слов (Count):

train_data06 = vect.transform(twenty_train[transform_num_to_name_class[1]]) x = list(zip(vect.get_feature_names(), np.ravel(train_data06.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('edu', 354), ('don', 230), ('people', 221), ('health', 217), ('use', 216), ('medical', 206), ('like', 201), ('know', 191), ('com', 190), ('time', 180), ('just', 174), ('patients', 163), ('new', 162), ('think', 153), ('disease', 146), ('good', 143), ('msg', 143), ('food', 142), ('years', 139), ('doctor', 133)]

Вывод для класса 2 при отсечении стоп-слов (Count):

train_data07 = vect.transform(twenty_train[transform_num_to_name_class[2]]) x = list(zip(vect.get_feature_names(), np.ravel(train_data07.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('god', 329), ('people', 267), ('jesus', 256), ('don', 162), ('bible', 160), ('just', 159), ('christian', 151), ('think', 151), ('know', 149), ('say', 149), ('does', 147), ('did', 132), ('good', 131), ('like', 131), ('life', 118), ('way', 118), ('believe', 117), ('said', 103), ('point', 101), ('time', 99)]

d.Реализация пунктов a-c для обучающей и тестовой выборки, для которых проведена процедура стемминга.

vect = CountVectorizer(max_features = 10000) vect.fit(stem_train.data_stem)

train_data_stem = vect.transform(stem_train.data_stem) test_data_stem = vect.transform(stem_test.data_stem)

Вывод для всей выборки при стемминге (Count):

x = list(zip(vect.get_feature_names(), np.ravel(train_data_stem.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('the', 11297), ('of', 6613), ('to', 6208), ('and', 5712), ('in', 3964), ('is', 3922), ('that', 3488), ('it', 3111), ('for', 2894), ('you', 2401), ('are', 1785), ('not', 1780), ('have', 1773), ('thi', 1766), ('be', 1763), ('with', 1737), ('or', 1504), ('as', 1430), ('do', 1385), ('on', 1320)]

6

stem_transform_num_to_name_class = {i: stem_train['target_names'][i] for i in range (len(stem_train['target_names']))}

for i in range(3):

stem_train[transform_num_to_name_class[i]] = [stem_train['data_stem'][j] for j in range(len(stem_train['data_stem'])) if stem_train['target'][j] == i]

Вывод для класса 0 при стемминге (Count):

train_data_stem01 = vect.transform(stem_train[stem_transform_num_to_name_class[0]]) x = list(zip(vect.get_feature_names(), np.ravel(train_data_stem01.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('the', 1485), ('for', 1157), ('and', 1081), ('to', 967), ('of', 755), ('in', 647), ('00', 617), ('it', 532), ('is', 516), ('you', 477), ('with', 453), ('or', 430), ('have', 385), ('do', 318), ('are', 310), ('all', 292), ('if', 283), ('new', 278), ('thi', 273), ('will', 253)]

Вывод для класса 1 при стемминге (Count):

train_data_stem02 = vect.transform(stem_train[stem_transform_num_to_name_class[1]]) x = list(zip(vect.get_feature_names(), np.ravel(train_data_stem02.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('the', 5173), ('of', 3283), ('to', 2879), ('and', 2644), ('in', 1971), ('is', 1936), ('it', 1539), ('that', 1527), ('for', 1086), ('be', 865), ('you', 863), ('thi', 850), ('are', 828), ('have', 785), ('with', 776), ('not', 749), ('or', 648), ('on', 637), ('as', 624), ('do', 551)]

Вывод для класса 2 при стемминге (Count):

train_data_stem03 = vect.transform(stem_train[stem_transform_num_to_name_class[2]]) x = list(zip(vect.get_feature_names(), np.ravel(train_data_stem03.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('the', 4639), ('of', 2575), ('to', 2362), ('and', 1987), ('that', 1711), ('is', 1470), ('in', 1346), ('you', 1061), ('it', 1040), ('not', 829), ('be', 695), ('for', 651), ('are', 647), ('thi', 643), ('as', 639), ('have', 603), ('do', 516), ('with', 508), ('wa', 492), ('he', 470)]

vect = CountVectorizer(max_features = 10000, stop_words = 'english') vect.fit(stem_train.data_stem)

train_data_stem04 = vect.transform(stem_train.data_stem) test_data_stem04 = vect.transform(stem_test.data_stem)

7

Вывод для всей выборки при отсечении стоп-слов и стемминге (Count):

x = list(zip(vect.get_feature_names(), np.ravel(train_data_stem04.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('thi', 1766), ('wa', 1068), ('use', 808), ('ha', 730), ('00', 640), ('ani', 535), ('like', 518), ('peopl', 518), ('new', 506), ('edu', 502), ('hi', 497), ('know', 438), ('doe', 436), ('good', 430), ('just', 417), ('time', 414), ('onli', 413), ('say', 400), ('think', 391), ('make', 381)]

Вывод для класса 0 при отсечении стоп-слов и стемминге (Count):

train_data_stem05 = vect.transform(stem_train[stem_transform_num_to_name_class[0]]) x = list(zip(vect.get_feature_names(), np.ravel(train_data_stem05.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('00', 617), ('new', 278), ('thi', 273), ('sale', 252), ('offer', 249), ('use', 246), ('includ', 239), ('50', 228), ('10', 214), ('price', 201), ('ship', 189), ('20', 169), ('pleas', 167), ('sell', 167), ('game', 160), ('25', 155), ('condit', 154), ('15', 153), ('good', 149), ('ha', 149)]

Вывод для класса 1 при отсечении стоп-слов и стемминге (Count):

train_data_stem06 = vect.transform(stem_train[stem_transform_num_to_name_class[1]]) x = list(zip(vect.get_feature_names(), np.ravel(train_data_stem06.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('thi', 850), ('wa', 477), ('use', 407), ('ha', 362), ('edu', 354), ('ani', 283), ('medic', 231), ('like', 229), ('patient', 223), ('time', 222), ('peopl', 221), ('health', 217), ('know', 211), ('year', 211), ('diseas', 208), ('food', 193), ('com', 191), ('caus', 188), ('doe', 183), ('think', 183)]

Вывод для класса 2 при отсечении стоп-слов и стемминге (Count):

train_data_stem07 = vect.transform(stem_train[stem_transform_num_to_name_class[2]]) x = list(zip(vect.get_feature_names(), np.ravel(train_data_stem07.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('thi', 643), ('wa', 492), ('god', 337), ('hi', 312), ('christian', 284), ('peopl', 268), ('jesu', 255), ('say', 249), ('ha', 219), ('doe', 195), ('think',

8

181), ('did', 180), ('know', 170), ('believ', 165), ('moral', 161), ('bibl', 159), ('just', 159), ('like', 158), ('use', 155), ('onli', 150)]

e.Векторизация выборок с помощью TfidfTransformer (с использованием TF и TF-IDF взвешиваний) и повтор пунктов b-d.

from sklearn.feature_extraction.text import TfidfTransformer

Использование TF-IDF взвешивания:

tfidf = TfidfTransformer(use_idf = True).fit(train_data) train_data_tfidf = tfidf.transform(train_data)

Вывод для всей выборки (TF-IDF):

x = list(zip(vect.get_feature_names(), np.ravel(train_data_tfidf.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('tone', 158.7095535302558), ('trip', 100.59334482026873), ('noon', 96.82672169042559), ('adjust', 86.39016862609914), ('ima', 78.0737463854439), ('impact', 71.51597224999692), ('tomographi', 69.39495091529038), ('harass', 67.86182033825528), ('epistl', 62.588326880465274), ('youth', 60.005846885521684), ('trade', 41.37365799621488), ('agreement', 40.00414095201544), ('forest', 39.4882262676624), ('word', 38.8104458820901), ('naturalist', 38.444939640920175), ('armageddon', 37.677253780707396), ('obviou', 37.30203300467406), ('aladdin', 32.73502619945886), ('grin', 32.43874285684031), ('nth', 31.670689631446457)]

Вывод для класса 0 (TF-IDF):

train_data_tfidf01 = tfidf.transform(train_data01)

x = list(zip(vect.get_feature_names(), np.ravel(train_data_tfidf01.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('epistl', 36.605426645044616), ('tone', 32.400606264074796), ('adjust', 25.53963375142146), ('trip', 24.02535491965117), ('harass', 18.19576015792747), ('shaw', 17.722469996962033), ('00', 17.62608520876973), ('impact', 17.4431606216812), ('noon', 16.992969198018002), ('obviou', 16.68612710009828), ('youth', 16.4437339055982), ('word', 15.135759587241065), ('forest', 14.88848644443091), ('nordenberg', 14.713813622103075), ('ima', 14.325829808132072), ('motorcycl', 13.642053174048948), ('soar', 13.551280029395848), ('macintosh', 12.278788600110328), ('pollut', 11.636978495985442), ('grin', 11.573783276041448)]

Вывод для класса 1 (TF-IDF):

train_data_tfidf02 = tfidf.transform(train_data02)

x = list(zip(vect.get_feature_names(), np.ravel(train_data_tfidf02.sum(axis=0))))

def SortbyTF(inputStr):

9

return inputStr[1] x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('tone', 73.58068299929461), ('noon', 48.03148056168368), ('trip', 46.79173100922471), ('ima', 41.46032113433584), ('impact', 38.47051656473345), ('adjust', 37.31579653456829), ('tomographi', 33.066100610459664), ('harass', 31.763795826845207), ('youth', 21.692899120653582), ('trade', 19.347314874576753), ('armageddon', 18.925936665861673), ('agreement', 17.652862115516175), ('naturalist', 17.329719776068593), ('epistl', 16.82742524226526), ('miner', 15.975835588609662), ('aladdin', 15.38535077532892), ('forest', 15.154875347278635), ('word', 15.04721960675219), ('nth', 14.901971823201228), ('bet', 14.21039119588495)]

Вывод для класса 2 (TF-IDF):

train_data_tfidf03 = tfidf.transform(train_data03)

x = list(zip(vect.get_feature_names(), np.ravel(train_data_tfidf03.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('tone', 52.72826426688628), ('noon', 31.80227193072372), ('trip', 29.776258891392686), ('tomographi', 28.470192204599897), ('adjust', 23.534738340109442), ('ima', 22.28759544297607), ('youth', 21.86921385926989), ('harass', 17.90226435348267), ('impact', 15.602295063582332), ('naturalist', 14.292580751685762), ('formul', 13.045903076397373), ('fauci', 12.374787054742459), ('armageddon', 12.318567409219128), ('trade', 11.759985995661191), ('agreement', 11.758006542146852), ('aladdin', 11.642717455339573), ('toxin', 10.700586355386111), ('wealth', 10.66803890445866), ('forest', 9.4448644759529), ('bet', 9.321105631843507)]

Вывод для всей выборки при отсечении стоп-слов (TF-IDF):

train_data_tfidf04 = tfidf.transform(train_data04)

x = list(zip(vect.get_feature_names(), np.ravel(train_data_tfidf04.sum(axis=0))))

def SortbyTF(inputStr): return inputStr[1]

x.sort(key=SortbyTF, reverse = True) print (x[:20])

[('kuhn', 45.74036279295919), ('jhu', 42.31591963759787), ('invalid', 42.058405250991456), ('netcom', 40.72444517237231), ('pip', 39.656340384480814), ('difficulti', 36.435145204308476), ('sincer', 35.03307135183398), ('definit', 33.89451077238455), ('olympu', 28.90189824646167), ('firmli', 28.679271778192103), ('threw', 28.50858235756172), ('deem', 28.384304255533706), ('uucp', 25.056648628896507), ('thank', 24.27660015955998), ('lizard', 24.22002358641167), ('hystaspes_', 24.182650738929855), ('financi', 23.851962167726953), ('uu', 22.15224437887963), ('chb', 19.85158611082459), ('somat', 19.820183746409704)]

Вывод для класса 0 при отсечении стоп-слов (TF-IDF):

train_data_tfidf05 = tfidf.transform(train_data05)

10

Соседние файлы в предмете Основы анализа текстовых данных