محاسبه آمار عبارات یکتا در پایتون — راهنمای کاربردی

۱۱۷ بازدید
آخرین به‌روزرسانی: ۲۱ تیر ۱۴۰۲
زمان مطالعه: ۸ دقیقه
محاسبه آمار عبارات یکتا

در این مطلب، با مبحث محاسبه آمار عبارات یکتا در «زبان برنامه‌نویسی پایتون» (Python Programming language) آشنا خواهید شد. یکی از کاربردهای مهم محاسبه آمار عبارات یکتا و تحلیل آن‌ها، در «پردازش زبان طبیعی» (Natural Language Processing) است. همچنین، از محاسبه آمار عبارات یکتا به شکل گسترده‌ای برای «متن‌کاوی» (Text Mining) یا «تحلیل کیفی متن» (Text Analysis) استفاده می‌شود.

یکی از مهم‌ترین «مدل‌های زبانی» (Language Models) برای شناسایی و محاسبه آمار عبارات یکتا در داده‌های متنی، مدل زبانی N-gram است. به بیان ساده، مدل‌های N-gram، مجموعه‌ای از N کلمه «هم‌اتفاق یا باهم‌گذاری شده» (Co-Occurring) در یک «پنجره محتوایی» (Context Window) هستند که یک عبارت مشخص در داده‌های متنی را نمایش می‌دهند.

پس از شناسایی یک عبارت N-gram در داده‌های متنی، پنجره محتوایی، یک کلمه رو به جلو در متن حرکت می‌کند و از این طریق، فرایند محاسبه آمار عبارات یکتا یا همان عبارات یکتای N-gram در داده‌های متنی انجام می‌شود.

مدل‌های «دو کلمه‌ای» (2Gram)، «سه کلمه‌ای» (3Gram)، «چهار کلمه‌ای» (4Gram) و «پنج کلمه‌ای» (5Gram)، مهم‌ترین مدل‌های شناسایی و محاسبه آمار عبارات یکتا در داده‌های متنی محسوب می‌شوند.

محاسبه آمار عبارات یکتا

نحوه محاسبه آمار عبارات یکتا با استفاده از مدل‌های N-Gram

در این بخش، ابتدا توضیح مختصری در مورد عبارات N-gram در زبان‌های طبیعی داده می‌شود. سپس، مدل‌های N-gram به طور مختصر تعریف می‌شوند. در نهایت، کدهای لازم برای پیاده‌سازی مدل‌های N-gram و محاسبه آمار عبارات یکتا نمایش داده می‌شوند.

اهمیت ترتیب کلمات در پردازش زبان طبیعی

ترتیب استفاده کلمات در زبان‌های طبیعی بسیار مهم است و به هیچ عنوان تصادفی نیست. به عنوان نمونه، شما در زبان فارسی از عبارت سیب قرمز و آب‌دار استفاده می‌کنید و نه عبارت قرمز آب‌دار سیب.

روابط میان کلمات در داده‌های متنی، غالبا بسیار پیچیده است. این پیچیدگی به حدی است که یک حوزه کاملا متمایز در «زبان‌شناسی» (Linguistics) به نام «نحو زبان» (Language Syntax) به آن اختصاص داده شده است. با این حال، دانشمندان این حوزه روش‌های ساده ولی هوشمندانه‌ای برای شناسایی و تحلیل برخی از روابط موجود میان کلمات ابداع کرده‌اند.

محققان حوزه زبان‌شناسی بیان می‌کنند که برای شناسایی روابط میان کلمات و استخراج اطلاعات از آن‌ها، می‌توان از هم‌اتفاقی کلمات در زمینه‌های محتوایی متفاوت استفاده کرد. به عبارت دیگر، این موضوع که در یک داده متنی، معمولا چه کلماتی در کنار هم ظاهر می‌شوند، اطلاعات زیادی در مورد زمینه محتوایی آن داده متنی در اختیار قرار می‌دهد.

تعریف مدل‌های N-gram

ایده اصلی مدل‌های N-gram این است که N کلمه (دو کلمه، سه کلمه و چهار کلمه و سایر موارد) ظاهر شده در کنار هم (کلمات هم‌اتفاق)، شناسایی و تحلیل شوند. در یک مجموعه بزرگ از داده‌های متنی، ممکن است عباراتی نظیر سیب قرمز یا قرمز آب‌دار به دفعات در داده‌های متنی مشاهده شوند؛ با این حال، احتمال مشاهده عباراتی نظیر قرمز سیب یا آب‌دار سیب در داده‌های متنی بسیار پایین است.

چنین مواردی، زمانی برای سیستم‌های پردازش متن مفید هستند که مدل‌های پردازش زبان طبیعی بخواهد مشخص کند که یک از عبارات فوق در یک زبان طبیعی معتبر است تا توسط سیستم «بازشناسی خودکار گفتار» (Automatic Speech Recognition) مورد استفاده قرار بگیرد.

بنابراین به مدل‌های شناسایی کلمات هم‌اتفاق، مدل‌های N-gram گفته می‌شود. در این مدل‌ها، N مشخص کننده طول عبارات هم‌اتفاق در داده‌های متنی است. مدل‌های دو کلمه‌ای (2Gram)، سه کلمه‌ای (3Gram)، چهار کلمه‌ای (4Gram) و پنج کلمه‌ای (5Gram)، مهم‌ترین مدل‌های N-gram محسوب می‌شوند.

محاسبه آمار عبارات یکتا

کدهای محاسبه آمار عبارات یکتا در زبان پایتون

از کدهای زیر برای شناسایی متناوب‌ترین عبارات دو کلمه‌ای (2Gram)، سه کلمه‌ای (3Gram)، چهار کلمه‌ای (4Gram) و پنج کلمه‌ای (5Gram) در داده‌های متنی، تعداد تناوب آن‌ها در داده‌های متنی و نمایش آن‌ها در خروجی استفاده می‌شود.

داده متنی زیر بخشی از مجموعه داده‌‌ای است که برای شناسایی متناوب‌ترین مدل‌های N-gram استفاده شده است.

	A critical history of virtual worlds invention

	The job of recounting the specific histories of various virtual 
worlds developments has already been done, in Japan by Katsura 
Hattori's _What's Virtual Reality?_ and in the U.S. by Howard 
Rheingold's _Virtual Reality,_ Myron Krueger's _Artificial Reality 
II,_ and other books to be published this year.  I want to emphasize 
the individualistic character of the invention that has taken place so 
far, which may explain why our technology is less than we would 
have it be.

	Clearly, many inventors were inspired by science fiction 
stories, in which people traveled through space and time, either 
physically "teleporting" their bodies or sending their thoughts 
around via telepathy.  Vannevar Bush was perhaps the first modern 
computer scientist to conceive of knowledge as a medium through 
which one might travel by machine.  His "Memex" was a fantasy 
computer that would put all knowledge at the disposal of its user in 
multimedia form,   Now Vannevar Bush's dream of universal access 
to knowledge has become international.

	In the U.S., in the 1960s, Ivan Sutherland started experiment-
ing with stereoscopic images created by a computer, to build a "data 
field."  Around the same time, Myron Krueger, another American, was 
using video cameras and other techniques to reverse the flow, put-
ting the user "into" the computer terminal and merging him or her 
with the images on the screen.  And, in the next decade, Thomas 
Furness began directing the "Super Cockpit" project for the U.S. Air 
Force, a completely pilot-attuned ensemble (complete with virtual 
world projectors) that the pilot would wear.  While these eminences 
knew of each other, their work did not coalesce but continued in dis-
tinctly different directions:  Sutherland, toward flat-screen simula-
tors; Krueger, deeper into art and media environments; and Furness, 
toward continuing to refine data-presentation and manipulation.
	
	The popularization of virtual worlds occurred with the simpli-
fication of a stereoscopic, head-mounted data display with position-
sensors by NASA; and the subsequent commercialization of a similar 
display complete with world-design software, the "Eyephones" and 
"Body Electric/Swivel 3D" by VPL Research, in Redwood City, Cali-
fornia.  With the appearance of these systems, and later the 3D 
sound unit, the Convolvatron, marketed by Crystal River Engineering, 
virtual worlds took off in the press and popular imagination.  Auto-
desk, of Sausalito, California, announced its work on Cyberspace, a 
3D CAD program.  Cyberspace begat Sense8, also of Sausalito, a 
small firm working on a Sun workstation platform rather than the 
traditional, more powerful Silicon Graphics computers that had been 
the tradition until then.  For awhile it looked as if the Mattel Power-
glove, a derivative of VPL's Dataglove developed by A.G.E., in New 
York, might take virtual worlds into the exploding Nintendo game 
market, but this did not occur.

	However, although work in virtual worlds was going on in many 
places by the 1990s, almost all of this activity was completely 
independent and uncoordinated.  Developments and inventions would 
usually become known within the virtual worlds community only 
after their introduction at one of the computer professional conven-
tions or trade shows, and even so inventors liked to hold onto secret 
code or hardware tricks to keep their pint-sized corporate empires 
intact.  This tradition of individuality and secrecy is only slowly 
being eroded by professional and social communications.  Unfortu-
nately, it is no longer the legacy of small firms; today, many larger 
firms practice the same self-serving tactics, to the disadvantage of 
our field.

کدهای زبان برنامه‌نویسی پایتون برای شناسایی متناوب‌ترین مدل‌های N-gram:

"""Print most frequent N-grams in given file.
Usage: python ngrams.py filename
Problem description: Build a tool which receives a corpus of text,
analyses it and reports the top 10 most frequent bigrams, trigrams,
four-grams (i.e. most frequently occurring two, three and four word
consecutive combinations).
NOTES
=====
I'm using collections.Counter indexed by n-gram tuple to count the
frequencies of n-grams, but I could almost as easily have used a
plain old dict (hash table). In that case I'd use the idiom
"dct.get(key, 0) + 1" to increment the count, and heapq.nlargest(10)
or sorted() on the frequency descending instead of the
counter.most_common() call.
In terms of performance, it's O(N * M) where N is the number of words
in the text, and M is the number of lengths of n-grams you're
counting. In this case we're counting digrams, trigrams, and
four-grams, so M is 3 and the running time is O(N * 3) = O(N), in
other words, linear time. There are various micro-optimizations to be
had, but as you have to read all the words in the text, you can't
get much better than O(N) for this problem.
On my laptop, it runs on the text of the King James Bible (4.5MB,
824k words) in about 3.9 seconds. Full text here:
https://www.gutenberg.org/ebooks/10.txt.utf-8
I haven't done the "extra" challenge to aggregate similar bigrams.
However, what I would do to start with is, after calling
count_ngrams(), use difflib.SequenceMatcher to determine the
similarity ratio between the various n-grams in an N^2 fashion. This
would be quite slow, but a reasonable start for smaller texts.
This code took me about an hour to write and test. It works on Python
2.7 as well as Python 3.x.
"""

import collections
import re
import sys
import time


def tokenize(string):
    """Convert string to lowercase and split into words (ignoring
    punctuation), returning list of words.
    """
    return re.findall(r'\w+', string.lower())


def count_ngrams(lines, min_length=2, max_length=4):
    """Iterate through given lines iterator (file object or list of
    lines) and return n-gram frequencies. The return value is a dict
    mapping the length of the n-gram to a collections.Counter
    object of n-gram tuple and number of times that n-gram occurred.
    Returned dict includes n-grams of length min_length to max_length.
    """
    lengths = range(min_length, max_length + 1)
    ngrams = {length: collections.Counter() for length in lengths}
    queue = collections.deque(maxlen=max_length)

    # Helper function to add n-grams at start of current queue to dict
    def add_queue():
        current = tuple(queue)
        for length in lengths:
            if len(current) >= length:
                ngrams[length][current[:length]] += 1

    # Loop through all lines and words and add n-grams to dict
    for line in lines:
        for word in tokenize(line):
            queue.append(word)
            if len(queue) >= max_length:
                add_queue()

    # Make sure we get the n-grams at the tail end of the queue
    while len(queue) > min_length:
        queue.popleft()
        add_queue()

    return ngrams


def print_most_frequent(ngrams, num=50):
    """Print num most common n-grams of each length in n-grams dict."""
    for n in sorted(ngrams):
        print('----- {} most common {}-grams -----'.format(num, n))
        for gram, count in ngrams[n].most_common(num):
            print('{0}: {1}'.format(' '.join(gram), count))
        print('')


if __name__ == '__main__':

    start_time = time.time()
    with open('C:/Users/m.jaderyan/Desktop/Text.txt') as f:
        ngrams = count_ngrams(f)
    print_most_frequent(ngrams)
    elapsed_time = time.time() - start_time
    print('Took {:.03f} seconds'.format(elapsed_time))

خروجی:

----- 15 most common 2-grams -----
virtual worlds: 21
in the: 17
at the: 9
university of: 9
of the: 8
the virtual: 8
the university: 8
the world: 7
the computer: 7
virtual world: 7
and the: 6
on the: 5
of virtual: 4
it is: 4
in three: 4

----- 15 most common 3-grams -----
the university of: 8
the virtual worlds: 4
of virtual worlds: 3
the virtuality paradigm: 3
the virtual world: 3
the physical world: 3
at the university: 3
the u s: 3
research is taking: 3
is taking place: 3
virtual worlds technology: 2
of this technology: 2
around the world: 2
the world and: 2
within the computer: 2

----- 15 most common 4-grams -----
at the university of: 3
research is taking place: 3
in the fields of: 2
the virtual world can: 2
the university of north: 2
university of north carolina: 2
in three or more: 2
three or more dimensions: 2
in the u s: 2
is taking place in: 2
the virtual worlds consortium: 2
in japan and north: 2
japan and north america: 2
virtual worlds technology promises: 1
worlds technology promises to: 1

----- 15 most common 5-grams -----
the university of north carolina: 2
in three or more dimensions: 2
research is taking place in: 2
in japan and north america: 2
virtual worlds technology promises to: 1
worlds technology promises to greatly: 1
technology promises to greatly expand: 1
promises to greatly expand both: 1
to greatly expand both the: 1
greatly expand both the numbers: 1
expand both the numbers of: 1
both the numbers of persons: 1
the numbers of persons who: 1
numbers of persons who use: 1
of persons who use computers: 1

اگر نوشته بالا برای شما مفید بوده است، آموزش‌های زیر نیز به شما پیشنهاد می‌شوند:

^^

بر اساس رای ۱ نفر
آیا این مطلب برای شما مفید بود؟
شما قبلا رای داده‌اید!
اگر بازخوردی درباره این مطلب دارید یا پرسشی دارید که بدون پاسخ مانده است، آن را از طریق بخش نظرات مطرح کنید.
منابع:
Kaggle

نظر شما چیست؟

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *