Обработка естественного языка

Обработка естественного языка (NLP) — это область искусственного интеллекта, которая помогает компьютерам понимать человеческий язык. НЛП позволяет машинам извлекать смысл из человеческого языка, чтобы мы могли получать ценную информацию из онлайн-общения.

В 1950 году, когда Алан Тьюринг опубликовал свою статью под названием Вычислительные машины и интеллект, с этого момента начался интерес к обработке естественного языка (НЛП). Отсюда возник мощный процесс/тест, названный Тестом Тьюринга. Тьюринг в основном утверждал, что компьютер можно считать разумным, если он может вести разговор с человеком так, чтобы человек не осознавал, что разговаривает с машиной.

НЛТК

NLTK – это самый популярный пакет Python для обработки естественного языка. Он предоставляет алгоритмы для импорта, очистки и предварительной обработки текстовых данных на человеческом языке, а затем применяет алгоритмы компьютерной лингвистики, такие как настроения. анализ.

Данные

Набор данных был представлен Бо Пангом и Лилиан Ли. Этот набор данных распространяется вместе с NLTK с разрешения авторов. Сегодня скачаю данные прямо из библиотеки NLTK.

Этот набор данных содержит 1000 положительных и 1000 отрицательных обработанных отзывов в виде текстовых файлов.

  • 1000 текстовых файлов с положительными отзывами
  • 1000 текстовых файлов с негативными отзывами

Итак, приступим к решению,

Выполнение

Сначала мы импортируем пакет NLTK и

Он также включает в себя множество простых в использовании наборов данных в пакете nltk.corpus, мы можем загрузить, например, пакет movie_reviews с помощью функции nltk.download:

код для того же будет

аналогичным образом, если вы хотите увидеть весь доступный набор данных для загрузки, вы можете просто написать

nltk.download()

Это перечислит все наборы данных, доступные с NLTK.

Как только данные будут загружены, мы можем импортировать их из nltk.corpus

Проверка набора данных обзоров фильмов

Метод fileids, предоставляемый всеми наборами данных в nltk.corpus, дает доступ к списку всех доступных файлов.

В частности, в наборе данных movie_reviews у нас есть 2000 текстовых файлов, каждый из которых представляет собой обзор фильма, и они уже разделены на папку neg для отрицательных отзывов и папку pos для положительных отзывов:

fileids также может фильтровать доступные файлы на основе их категории, которая является названием подпапок, в которых они расположены. Поэтому мы можем иметь списки положительных и отрицательных отзывов отдельно.

Одну из рецензий мы можем осмотреть методом raw из movie_reviews, каждый файл разбит на предложения, кураторы этого датасета также убрали из каждой рецензии любое прямое упоминание о рейтинге фильма.

вывод:

films adapted from comic books have had plenty of success , whether they're about superheroes ( batman , superman , spawn ) , or geared toward kids ( casper ) or the arthouse crowd ( ghost world ) , but there's never really been a comic book like from hell before . 
for starters , it was created by alan moore ( and eddie campbell ) , who brought the medium to a whole new level in the mid '80s with a 12-part series called the watchmen . 
to say moore and campbell thoroughly researched the subject of jack the ripper would be like saying michael jackson is starting to look a little odd . 
the book ( or " graphic novel , " if you will ) is over 500 pages long and includes nearly 30 more that consist of nothing but footnotes . 
in other words , don't dismiss this film because of its source . 
if you can get past the whole comic book thing , you might find another stumbling block in from hell's directors , albert and allen hughes . 
getting the hughes brothers to direct this seems almost as ludicrous as casting carrot top in , well , anything , but riddle me this : who better to direct a film that's set in the ghetto and features really violent street crime than the mad geniuses behind menace ii society ? 
the ghetto in question is , of course , whitechapel in 1888 london's east end . 
it's a filthy , sooty place where the whores ( called " unfortunates " ) are starting to get a little nervous about this mysterious psychopath who has been carving through their profession with surgical precision . 
when the first stiff turns up , copper peter godley ( robbie coltrane , the world is not enough ) calls in inspector frederick abberline ( johnny depp , blow ) to crack the case . 
abberline , a widower , has prophetic dreams he unsuccessfully tries to quell with copious amounts of absinthe and opium . 
upon arriving in whitechapel , he befriends an unfortunate named mary kelly ( heather graham , say it isn't so ) and proceeds to investigate the horribly gruesome crimes that even the police surgeon can't stomach . 
i don't think anyone needs to be briefed on jack the ripper , so i won't go into the particulars here , other than to say moore and campbell have a unique and interesting theory about both the identity of the killer and the reasons he chooses to slay . 
in the comic , they don't bother cloaking the identity of the ripper , but screenwriters terry hayes ( vertical limit ) and rafael yglesias ( les mis ? rables ) do a good job of keeping him hidden from viewers until the very end . 
it's funny to watch the locals blindly point the finger of blame at jews and indians because , after all , an englishman could never be capable of committing such ghastly acts . 
and from hell's ending had me whistling the stonecutters song from the simpsons for days ( " who holds back the electric car/who made steve guttenberg a star ? " ) . 
don't worry - it'll all make sense when you see it . 
now onto from hell's appearance : it's certainly dark and bleak enough , and it's surprising to see how much more it looks like a tim burton film than planet of the apes did ( at times , it seems like sleepy hollow 2 ) . 
the print i saw wasn't completely finished ( both color and music had not been finalized , so no comments about marilyn manson ) , but cinematographer peter deming ( don't say a word ) ably captures the dreariness of victorian-era london and helped make the flashy killing scenes remind me of the crazy flashbacks in twin peaks , even though the violence in the film pales in comparison to that in the black-and-white comic . 
oscar winner martin childs' ( shakespeare in love ) production design turns the original prague surroundings into one creepy place . 
even the acting in from hell is solid , with the dreamy depp turning in a typically strong performance and deftly handling a british accent . 
ians holm ( joe gould's secret ) and richardson ( 102 dalmatians ) log in great supporting roles , but the big surprise here is graham . 
i cringed the first time she opened her mouth , imagining her attempt at an irish accent , but it actually wasn't half bad . 
the film , however , is all good . 
2 : 00 - r for strong violence/gore , sexuality , language and drug content

Tokenize Text in Words

The first thing, we have to do is generally to split the text into words, this process might appear simple but it is very tedious to handle all corner cases, see for example all the issues with punctuation we have to solve if we just start with a split on whitespace:

Output:

['Why',
 'then,',
 'O',
 'brawling',
 'love!',
 'O',
 'loving',
 'hate!',
 'O',
 'any',
 'thing,',
 'of',
 'nothing',
 'first',
 'create!',
 'O',
 'heavy',
 'lightness,',
 'serious',
 'vanity,',
 'Misshapen',
 'chaos',
 'of',
 'well-seeming',
 'forms,',
 'Feather',
 'of',
 'lead,',
 'bright',
 'smoke,',
 'cold',
 'fire,',
 'sick',
 'health,',
 'Still-waking',
 'sleep,',
 'that',
 'is',
 'not',
 'what',
 'it',
 'is!',
 'This',
 'love',
 'feel',
 'I,',
 'that',
 'feel',
 'no',
 'love',
 'in',
 'this.']

movie_reviews корпус уже имеет прямой доступ к токенизированному тексту с помощью метода words:

Построить модель мешка слов

Простейшая модель анализа текста состоит в том, чтобы думать о тексте как о неупорядоченном наборе слов (наборе слов). Как правило, это позволяет сделать вывод из текста о категории, теме или настроении.

Из модели мешка слов мы можем создавать функции, которые будут использоваться классификатором. Здесь мы предполагаем, что каждое слово является функцией, которая может быть либо True, либо False.
Мы реализуем это в Python как словарь, где для каждого слова в предложении, которое мы связываем, если слово отсутствует, это будет то же самое, что присваивать False.

вывод:

{'Why': True,
 'then': True,
 ',': True,
 'O': True,
 'brawling': True,
 'love': True,
 '!': True,
 'loving': True,
 'hate': True,
 'any': True,
 'thing': True,
 'of': True,
 'nothing': True,
 'first': True,
 'create': True,
 'heavy': True,
 'lightness': True,
 'serious': True,
 'vanity': True,
 'Misshapen': True,
 'chaos': True,
 'well-seeming': True,
 'forms': True,
 'Feather': True,
 'lead': True,
 'bright': True,
 'smoke': True,
 'cold': True,
 'fire': True,
 'sick': True,
 'health': True,
 'Still-waking': True,
 'sleep': True,
 'that': True,
 'is': True,
 'not': True,
 'what': True,
 'it': True,
 'This': True,
 'feel': True,
 'I': True,
 'no': True,
 'in': True,
 'this': True,
 '.': True}

Вывод:

{'Why': True,
 'then': True,
 ',': True,
 'O': True,
 'brawling': True,
 'love': True,
 '!': True,
 'loving': True,
 'hate': True,
 'any': True,
 'thing': True,
 'of': True,
 'nothing': True,
 'first': True,
 'create': True,
 'heavy': True,
 'lightness': True,
 'serious': True,
 'vanity': True,
 'Misshapen': True,
 'chaos': True,
 'well-seeming': True,
 'forms': True,
 'Feather': True,
 'lead': True,
 'bright': True,
 'smoke': True,
 'cold': True,
 'fire': True,
 'sick': True,
 'health': True,
 'Still-waking': True,
 'sleep': True,
 'that': True,
 'is': True,
 'not': True,
 'what': True,
 'it': True,
 'This': True,
 'feel': True,
 'I': True,
 'no': True,
 'in': True,
 'this': True,
 '.': True}

Это то, что мы хотели, но мы замечаем, что и знаки препинания, такие как «!» и слова, бесполезные для целей классификации, такие как «из» или «что», также включены.
Эти слова называются «стоп-словами», и nltk имеет удобный корпус, который мы можем скачать:

Используя список Python string.punctuation и английские стоп-слова, мы можем создавать лучшие функции, отфильтровывая те слова, которые не помогут в классификации:

Вывод:

{'Why': 1,
 'O': 1,
 'brawling': 1,
 'love': 1,
 'loving': 1,
 'hate': 1,
 'thing': 1,
 'nothing': 1,
 'first': 1,
 'create': 1,
 'heavy': 1,
 'lightness': 1,
 'serious': 1,
 'vanity': 1,
 'Misshapen': 1,
 'chaos': 1,
 'well-seeming': 1,
 'forms': 1,
 'Feather': 1,
 'lead': 1,
 'bright': 1,
 'smoke': 1,
 'cold': 1,
 'fire': 1,
 'sick': 1,
 'health': 1,
 'Still-waking': 1,
 'sleep': 1,
 'This': 1,
 'feel': 1,
 'I': 1}

График частот слов

Перед началом анализа обычно изучают набор данных, в этом разделе мы найдем наиболее распространенные слова и построим график их частотности.

Используя функцию .words() без аргументов, мы можем извлечь слова из всего набора данных и убедиться, что их около 1,6 миллиона.

Теперь в этом наборе данных у нас также есть много нежелательных данных/слов, нам нужно их отфильтровать. Это также сделает наш набор данных небольшим.

Вывод:

['plot',
 'two',
 'teen',
 'couples',
 'go',
 'church',
 'party',
 'drink',
 'drive',
 'get',
 'accident',
 'one',
 'guys',
 'dies',
 'girlfriend',
 'continues',
 'see',
 'life',
 'nightmares',
 'deal']

Теперь у нас есть пакет с названием collection counter, который можно использовать для подсчета частоты слов, представленных в нашем списке.

Вывод:

[('film', 9517),
 ('one', 5852),
 ('movie', 5771),
 ('like', 3690),
 ('even', 2565),
 ('good', 2411),
 ('time', 2411),
 ('story', 2169),
 ('would', 2109),
 ('much', 2049)]

Он также имеет функцию mosty_common() для выбранных наиболее часто используемых слов в нашем списке.

Визуализируйте данные

Теперь мы собираемся использовать библиотеку matplotlib для визуализации данных.

Мы можем отсортировать количество слов и отобразить их значения на логарифмических осях, чтобы проверить форму распределения. Эта визуализация особенно полезна при сравнении двух или более наборов данных: более плоское распределение указывает на большой словарный запас, а пикообразное распределение — на ограниченный словарный запас, часто из-за сфокусированной темы или специализированного языка.

Другим связанным графиком является гистограмма sorted_word_counts, которая показывает, сколько слов имеет значение в определенном диапазоне.

теперь у нас есть представление о наборе данных, и мы должны создать модель ML для классификации настроений.

Создание модели машинного обучения

Теперь последний шаг — создать модель машинного обучения и обучить ее только что созданным функциям.

для дальнейшей реализации можно скачать отсюда: оценочный обзор фильма с НЛТК

Оставайтесь с нами, приятного обучения :-)

Следите за MachineX Intelligence, чтобы узнать больше: