Zacznijmy od czegoś naprawdę prostego - tokenizacji to znaczy podziału tekstu na elementy składowe. Wykorzystamy tutaj pakiet nltk. Jednak, żeby w ogóle zacząć zabawę z tekstem musimy się pokusić o pobranie zdobycie jakiegos materiału - w naszym przypadku będzie to akapit z opowiadania Artura Conan Doyle’a pt. “Skanal w Bohemii”
Skorzystamy z biblioteki urllib i z dedykowanej funkcji . Generalnie już w tym momencie napotykamy pewne wątpliwości, m.in. w jaki sposób przedstawić używany tekst. W tym przypadku sensowne wydaje się wczytywanie linia po linii, bo taki jest oryginalny plik:
from urllib import request
url = "https://jsienkiewicz.pl/pliki/IDMI1/sh.txt"
response = request.urlopen(url)
lines = response.readlines()
lines
## [b'I had seen little of Holmes lately. My marriage had drifted us away\r\n', b'from each other. My own complete happiness, and the home-centred\r\n', b'interests which rise up around the man who first finds himself master\r\n', b'of his own establishment, were sufficient to absorb all my attention;\r\n', b'while Holmes, who loathed every form of society with his whole\r\n', b'Bohemian soul, remained in our lodgings in Baker Street, buried among\r\n', b'his old books, and alternating from week to week between cocaine and\r\n', b'ambition, the drowsiness of the drug, and the fierce energy of his\r\n', b'own keen nature. He was still, as ever, deeply attracted by the study\r\n', b'of crime, and occupied his immense faculties and extraordinary powers\r\n', b'of observation in following out those clues, and clearing up those\r\n', b'mysteries, which had been abandoned as hopeless by the official police.\r\n', b'From time to time I heard some vague account of his doings: of his\r\n', b'summons to Odessa in the case of the Trepoff murder, of his clearing\r\n', b'up of the singular tragedy of the Atkinson brothers at Trincomalee,\r\n', b'and finally of the mission which he had accomplished so delicately and\r\n', b'successfully for the reigning family of Holland. Beyond these signs of\r\n', b'his activity, however, which I merely shared with all the readers of\r\n', b'the daily press, I knew little of my former friend and companion.']
Nie da się ukryć, że pojawiają się znaczniki, takie jak \r \n, które nie są nam raczej do niczego potrzebne. Dzięki zmianie kodowania na utf-8 oraz uzyciu funkcji rstrip() otrzymamy dużo czytelniejszy tekst:
lines_corr = [x.decode("utf-8").rstrip() for x in lines]
lines_corr
## ['I had seen little of Holmes lately. My marriage had drifted us away', 'from each other. My own complete happiness, and the home-centred', 'interests which rise up around the man who first finds himself master', 'of his own establishment, were sufficient to absorb all my attention;', 'while Holmes, who loathed every form of society with his whole', 'Bohemian soul, remained in our lodgings in Baker Street, buried among', 'his old books, and alternating from week to week between cocaine and', 'ambition, the drowsiness of the drug, and the fierce energy of his', 'own keen nature. He was still, as ever, deeply attracted by the study', 'of crime, and occupied his immense faculties and extraordinary powers', 'of observation in following out those clues, and clearing up those', 'mysteries, which had been abandoned as hopeless by the official police.', 'From time to time I heard some vague account of his doings: of his', 'summons to Odessa in the case of the Trepoff murder, of his clearing', 'up of the singular tragedy of the Atkinson brothers at Trincomalee,', 'and finally of the mission which he had accomplished so delicately and', 'successfully for the reigning family of Holland. Beyond these signs of', 'his activity, however, which I merely shared with all the readers of', 'the daily press, I knew little of my former friend and companion.']
Oczywiście główne pytanie jest takie, czy faktycznie potrzebujemy zapisu linia po linii. Zamiast tego możemy od razu pokusić się o zwarty tekst:
response = request.urlopen(url)
raw_text = response.read().decode('utf8')
raw_text
## 'I had seen little of Holmes lately. My marriage had drifted us away\r\nfrom each other. My own complete happiness, and the home-centred\r\ninterests which rise up around the man who first finds himself master\r\nof his own establishment, were sufficient to absorb all my attention;\r\nwhile Holmes, who loathed every form of society with his whole\r\nBohemian soul, remained in our lodgings in Baker Street, buried among\r\nhis old books, and alternating from week to week between cocaine and\r\nambition, the drowsiness of the drug, and the fierce energy of his\r\nown keen nature. He was still, as ever, deeply attracted by the study\r\nof crime, and occupied his immense faculties and extraordinary powers\r\nof observation in following out those clues, and clearing up those\r\nmysteries, which had been abandoned as hopeless by the official police.\r\nFrom time to time I heard some vague account of his doings: of his\r\nsummons to Odessa in the case of the Trepoff murder, of his clearing\r\nup of the singular tragedy of the Atkinson brothers at Trincomalee,\r\nand finally of the mission which he had accomplished so delicately and\r\nsuccessfully for the reigning family of Holland. Beyond these signs of\r\nhis activity, however, which I merely shared with all the readers of\r\nthe daily press, I knew little of my former friend and companion.'
Użycie rstrip() nic nam nie da w tym przypadku, gdyż usuniemy tylko końcowe białe spacje. Nie będziemy sie tym za bardzo przejmować, bo tokenizator załatwi to za nas. Jeśli jednak, z jakiegos powodu, bardzo tego potrzebujemy, to możemy po protsu połączyć tekst otrzymany z rozbicia z linie:
' '.join(lines_corr)
## 'I had seen little of Holmes lately. My marriage had drifted us away from each other. My own complete happiness, and the home-centred interests which rise up around the man who first finds himself master of his own establishment, were sufficient to absorb all my attention; while Holmes, who loathed every form of society with his whole Bohemian soul, remained in our lodgings in Baker Street, buried among his old books, and alternating from week to week between cocaine and ambition, the drowsiness of the drug, and the fierce energy of his own keen nature. He was still, as ever, deeply attracted by the study of crime, and occupied his immense faculties and extraordinary powers of observation in following out those clues, and clearing up those mysteries, which had been abandoned as hopeless by the official police. From time to time I heard some vague account of his doings: of his summons to Odessa in the case of the Trepoff murder, of his clearing up of the singular tragedy of the Atkinson brothers at Trincomalee, and finally of the mission which he had accomplished so delicately and successfully for the reigning family of Holland. Beyond these signs of his activity, however, which I merely shared with all the readers of the daily press, I knew little of my former friend and companion.'
Skoro mamy już tekst, to wypada teraz dokonać tokenizacji. Jak wspomniano na wykładzie token to generalnie pewna cegiełka tekstu. W wielu przypadkach będziemy przyjmować, że jest to pojedyncze słowo, ale możemy za token uznać także znak, sylabę czy nawet zdanie. Ponizej wykorzystamy funkcję word_tokenize() z biblioteki nltk to rozdziału naszego tekstu na słowa…
import nltk
tokens_text = nltk.word_tokenize(raw_text)
print(tokens_text)
## ['I', 'had', 'seen', 'little', 'of', 'Holmes', 'lately', '.', 'My', 'marriage', 'had', 'drifted', 'us', 'away', 'from', 'each', 'other', '.', 'My', 'own', 'complete', 'happiness', ',', 'and', 'the', 'home-centred', 'interests', 'which', 'rise', 'up', 'around', 'the', 'man', 'who', 'first', 'finds', 'himself', 'master', 'of', 'his', 'own', 'establishment', ',', 'were', 'sufficient', 'to', 'absorb', 'all', 'my', 'attention', ';', 'while', 'Holmes', ',', 'who', 'loathed', 'every', 'form', 'of', 'society', 'with', 'his', 'whole', 'Bohemian', 'soul', ',', 'remained', 'in', 'our', 'lodgings', 'in', 'Baker', 'Street', ',', 'buried', 'among', 'his', 'old', 'books', ',', 'and', 'alternating', 'from', 'week', 'to', 'week', 'between', 'cocaine', 'and', 'ambition', ',', 'the', 'drowsiness', 'of', 'the', 'drug', ',', 'and', 'the', 'fierce', 'energy', 'of', 'his', 'own', 'keen', 'nature', '.', 'He', 'was', 'still', ',', 'as', 'ever', ',', 'deeply', 'attracted', 'by', 'the', 'study', 'of', 'crime', ',', 'and', 'occupied', 'his', 'immense', 'faculties', 'and', 'extraordinary', 'powers', 'of', 'observation', 'in', 'following', 'out', 'those', 'clues', ',', 'and', 'clearing', 'up', 'those', 'mysteries', ',', 'which', 'had', 'been', 'abandoned', 'as', 'hopeless', 'by', 'the', 'official', 'police', '.', 'From', 'time', 'to', 'time', 'I', 'heard', 'some', 'vague', 'account', 'of', 'his', 'doings', ':', 'of', 'his', 'summons', 'to', 'Odessa', 'in', 'the', 'case', 'of', 'the', 'Trepoff', 'murder', ',', 'of', 'his', 'clearing', 'up', 'of', 'the', 'singular', 'tragedy', 'of', 'the', 'Atkinson', 'brothers', 'at', 'Trincomalee', ',', 'and', 'finally', 'of', 'the', 'mission', 'which', 'he', 'had', 'accomplished', 'so', 'delicately', 'and', 'successfully', 'for', 'the', 'reigning', 'family', 'of', 'Holland', '.', 'Beyond', 'these', 'signs', 'of', 'his', 'activity', ',', 'however', ',', 'which', 'I', 'merely', 'shared', 'with', 'all', 'the', 'readers', 'of', 'the', 'daily', 'press', ',', 'I', 'knew', 'little', 'of', 'my', 'former', 'friend', 'and', 'companion', '.']
… jak widać - nie tylko. Także znaki interpunkcyjne są traktowane jako tokeny. Aby otrzymać rozsądny tekst, pwonniśmy rozważyć pozbycie się ich, jak również zmianę wszystkich liter na małe. Do tej ostatniej operacji wykorzystamy prostą wbudowaną domyślnie funkcję lower() operująca na łańcuchach, natomiast do tej pierwszej - bibliotekę string i zebrane w punctation znaki przestankowe.
import string
tokens_text = [word.lower() for word in tokens_text]
inwokacja = [word for word in tokens_text if word not in string.punctuation]
inwokacja
## ['i', 'had', 'seen', 'little', 'of', 'holmes', 'lately', 'my', 'marriage', 'had', 'drifted', 'us', 'away', 'from', 'each', 'other', 'my', 'own', 'complete', 'happiness', 'and', 'the', 'home-centred', 'interests', 'which', 'rise', 'up', 'around', 'the', 'man', 'who', 'first', 'finds', 'himself', 'master', 'of', 'his', 'own', 'establishment', 'were', 'sufficient', 'to', 'absorb', 'all', 'my', 'attention', 'while', 'holmes', 'who', 'loathed', 'every', 'form', 'of', 'society', 'with', 'his', 'whole', 'bohemian', 'soul', 'remained', 'in', 'our', 'lodgings', 'in', 'baker', 'street', 'buried', 'among', 'his', 'old', 'books', 'and', 'alternating', 'from', 'week', 'to', 'week', 'between', 'cocaine', 'and', 'ambition', 'the', 'drowsiness', 'of', 'the', 'drug', 'and', 'the', 'fierce', 'energy', 'of', 'his', 'own', 'keen', 'nature', 'he', 'was', 'still', 'as', 'ever', 'deeply', 'attracted', 'by', 'the', 'study', 'of', 'crime', 'and', 'occupied', 'his', 'immense', 'faculties', 'and', 'extraordinary', 'powers', 'of', 'observation', 'in', 'following', 'out', 'those', 'clues', 'and', 'clearing', 'up', 'those', 'mysteries', 'which', 'had', 'been', 'abandoned', 'as', 'hopeless', 'by', 'the', 'official', 'police', 'from', 'time', 'to', 'time', 'i', 'heard', 'some', 'vague', 'account', 'of', 'his', 'doings', 'of', 'his', 'summons', 'to', 'odessa', 'in', 'the', 'case', 'of', 'the', 'trepoff', 'murder', 'of', 'his', 'clearing', 'up', 'of', 'the', 'singular', 'tragedy', 'of', 'the', 'atkinson', 'brothers', 'at', 'trincomalee', 'and', 'finally', 'of', 'the', 'mission', 'which', 'he', 'had', 'accomplished', 'so', 'delicately', 'and', 'successfully', 'for', 'the', 'reigning', 'family', 'of', 'holland', 'beyond', 'these', 'signs', 'of', 'his', 'activity', 'however', 'which', 'i', 'merely', 'shared', 'with', 'all', 'the', 'readers', 'of', 'the', 'daily', 'press', 'i', 'knew', 'little', 'of', 'my', 'former', 'friend', 'and', 'companion']
Dodatkową rzeczą, którą można wykonac jest eliminacja tzw. “stopwords” czyli w wolnym tłumaczeniu “słów funkcyjnych” - generalnie sa to spójniki, przyimki , zaimki osobowe i dzierżawcze itd. Jak widać może to byc dość pokaźny zbiór słów. Posłużymy się tu wbudowanym zbiorem:
from nltk.corpus import stopwords
stopwords = set(stopwords.words('english'))
stopwords
## {'shan', 'such', 'that', 'same', 'should', "mustn't", "shouldn't", 'doing', "you'd", "she'd", 'all', 'before', 'wasn', 've', 'once', 'i', 'mightn', 'been', 'here', "that'll", 'aren', 'about', 'below', 'hers', 'no', "you're", 'between', 'needn', 'are', 'as', 'from', "she'll", 'my', 'didn', 'ourselves', 'then', 'to', "i've", 'on', 'this', "we've", 'during', 'because', 'theirs', 'these', 'where', 'them', "mightn't", 'until', 'yours', 'above', "shan't", 'so', "weren't", 'hadn', 'did', 'you', "doesn't", "they're", "they'd", 'other', 'weren', "it'd", 'just', 'for', 'll', 'there', 'we', 'couldn', 'by', 'under', "didn't", 'own', 'nor', 'what', 'isn', "she's", 'does', 'ma', 'any', 's', 'y', "needn't", 're', 'in', 'at', 'it', "we'd", 't', "he'll", 'up', "isn't", "it'll", 'their', "i'd", 'further', 'a', 'had', 'won', 'and', 'if', "couldn't", 'now', 'of', 'down', 'is', "don't", "we'll", 'have', 'haven', 'yourself', 'those', 'your', 'mustn', 'myself', 'm', "they've", 'very', 'over', 'he', 'ain', 'has', 'am', 'an', "wasn't", 'who', 'most', 'our', 'themselves', "i'll", 'after', 'having', 'd', 'shouldn', 'doesn', 'or', 'too', "you'll", 'yourselves', 'were', "wouldn't", 'again', 'she', 'her', 'they', "he'd", 'but', "aren't", 'itself', 'be', 'each', 'both', "it's", "they'll", 'why', 'when', 'the', 'can', 'wouldn', 'me', 'with', 'few', "hasn't", 'him', "should've", 'being', "he's", 'hasn', 'was', 'not', 'than', 'against', "hadn't", 'into', 'o', 'more', 'himself', 'while', 'through', "you've", 'some', "i'm", 'do', 'only', "haven't", 'out', 'its', 'off', 'how', 'ours', "we're", 'will', 'which', 'herself', 'whom', "won't", 'don', 'his'}
Teraz możemy de facto wykonać podobny kod jak w przypadku usuwania interpunkcji:
inwokacja_nsw = [word for word in inwokacja if word not in stopwords]
inwokacja_nsw
## ['seen', 'little', 'holmes', 'lately', 'marriage', 'drifted', 'us', 'away', 'complete', 'happiness', 'home-centred', 'interests', 'rise', 'around', 'man', 'first', 'finds', 'master', 'establishment', 'sufficient', 'absorb', 'attention', 'holmes', 'loathed', 'every', 'form', 'society', 'whole', 'bohemian', 'soul', 'remained', 'lodgings', 'baker', 'street', 'buried', 'among', 'old', 'books', 'alternating', 'week', 'week', 'cocaine', 'ambition', 'drowsiness', 'drug', 'fierce', 'energy', 'keen', 'nature', 'still', 'ever', 'deeply', 'attracted', 'study', 'crime', 'occupied', 'immense', 'faculties', 'extraordinary', 'powers', 'observation', 'following', 'clues', 'clearing', 'mysteries', 'abandoned', 'hopeless', 'official', 'police', 'time', 'time', 'heard', 'vague', 'account', 'doings', 'summons', 'odessa', 'case', 'trepoff', 'murder', 'clearing', 'singular', 'tragedy', 'atkinson', 'brothers', 'trincomalee', 'finally', 'mission', 'accomplished', 'delicately', 'successfully', 'reigning', 'family', 'holland', 'beyond', 'signs', 'activity', 'however', 'merely', 'shared', 'readers', 'daily', 'press', 'knew', 'little', 'former', 'friend', 'companion']
Jak widać, słowo “twą” jest na tyle archaiczne, że nie znalzało się w liście polskich słów funkcyjnych.
Choć na pewno jasny, poprzedni przykład charakteryzował się niewielką liczbą tokenów, które udało nam się wyekstrahować z tekstu. Nie musimy się uciekać do żadnych narzędzi, aby ocenić ile jest powtarzających się słów. Spróbujmy skorzystać z trochę bardziej pokaźnego pliku, pochodzącego z serwisu Project Gutenberg, w tym przypadku będzie to powieść Juliusza Verne’a W 80 dni dokoła świata. Dla ułatwienia napiszemy funkcję process_book(), która wykonuje wszytskie wcześniejsze operacje, a przyjmuje adres wskazujący na plik tekstowy z książką:
def process_book(url):
response = request.urlopen(url)
lines = response.readlines()
lines = [line.decode("utf8", "ignore").rstrip() for line in lines]
lines = ' '.join(lines)
words = nltk.word_tokenize(lines)
words = [w.lower() for w in words]
words = [w for w in words if w not in string.punctuation]
return(words)
Teraz możemy już spokojnie wywołać funkcję i wypisać pierwszych kilkadziesiąt słów:
verne_book = process_book("https://www.gutenberg.org/cache/epub/103/pg103.txt")
verne_book[0:100]
## ['the', 'project', 'gutenberg', 'ebook', 'of', 'around', 'the', 'world', 'in', 'eighty', 'days', 'this', 'ebook', 'is', 'for', 'the', 'use', 'of', 'anyone', 'anywhere', 'in', 'the', 'united', 'states', 'and', 'most', 'other', 'parts', 'of', 'the', 'world', 'at', 'no', 'cost', 'and', 'with', 'almost', 'no', 'restrictions', 'whatsoever', 'you', 'may', 'copy', 'it', 'give', 'it', 'away', 'or', 're-use', 'it', 'under', 'the', 'terms', 'of', 'the', 'project', 'gutenberg', 'license', 'included', 'with', 'this', 'ebook', 'or', 'online', 'at', 'www.gutenberg.org', 'if', 'you', 'are', 'not', 'located', 'in', 'the', 'united', 'states', 'you', 'will', 'have', 'to', 'check', 'the', 'laws', 'of', 'the', 'country', 'where', 'you', 'are', 'located', 'before', 'using', 'this', 'ebook', 'title', 'around', 'the', 'world', 'in', 'eighty', 'days']
Możemy też łatwo wyznaczyć liczbę słów (tokenów) \(M\) oraz liczbę typów \(V\) , czyli unikalnych tokenów, ich stosunek zwany type to token ratio (TTR, \(TTR = V/M\)) jak również stosunek ich logarytmów (czyli \(C=\log V/\log M\)), zwany indeksem Herdana:
import math
def get_stats(book):
M = len(book)
V = len(set(book))
TTR = V/M
C = math.log(V) / math.log(M)
print("M =", M, " V =", V, " TTR =", round(TTR, 3), " C =", round(C, 3))
get_stats(verne_book)
## M = 70365 V = 7614 TTR = 0.108 C = 0.801
Sprawdźmy teraz jak wyglądają te liczby, gdy usuniemy słowa funkcyjne
stopwords
## {'shan', 'such', 'that', 'same', 'should', "mustn't", "shouldn't", 'doing', "you'd", "she'd", 'all', 'before', 'wasn', 've', 'once', 'i', 'mightn', 'been', 'here', "that'll", 'aren', 'about', 'below', 'hers', 'no', "you're", 'between', 'needn', 'are', 'as', 'from', "she'll", 'my', 'didn', 'ourselves', 'then', 'to', "i've", 'on', 'this', "we've", 'during', 'because', 'theirs', 'these', 'where', 'them', "mightn't", 'until', 'yours', 'above', "shan't", 'so', "weren't", 'hadn', 'did', 'you', "doesn't", "they're", "they'd", 'other', 'weren', "it'd", 'just', 'for', 'll', 'there', 'we', 'couldn', 'by', 'under', "didn't", 'own', 'nor', 'what', 'isn', "she's", 'does', 'ma', 'any', 's', 'y', "needn't", 're', 'in', 'at', 'it', "we'd", 't', "he'll", 'up', "isn't", "it'll", 'their', "i'd", 'further', 'a', 'had', 'won', 'and', 'if', "couldn't", 'now', 'of', 'down', 'is', "don't", "we'll", 'have', 'haven', 'yourself', 'those', 'your', 'mustn', 'myself', 'm', "they've", 'very', 'over', 'he', 'ain', 'has', 'am', 'an', "wasn't", 'who', 'most', 'our', 'themselves', "i'll", 'after', 'having', 'd', 'shouldn', 'doesn', 'or', 'too', "you'll", 'yourselves', 'were', "wouldn't", 'again', 'she', 'her', 'they', "he'd", 'but', "aren't", 'itself', 'be', 'each', 'both', "it's", "they'll", 'why', 'when', 'the', 'can', 'wouldn', 'me', 'with', 'few', "hasn't", 'him', "should've", 'being', "he's", 'hasn', 'was', 'not', 'than', 'against', "hadn't", 'into', 'o', 'more', 'himself', 'while', 'through', "you've", 'some', "i'm", 'do', 'only', "haven't", 'out', 'its', 'off', 'how', 'ours', "we're", 'will', 'which', 'herself', 'whom', "won't", 'don', 'his'}
verne_book_wos = [w for w in verne_book if w not in stopwords]
get_stats(verne_book_wos)
## M = 37608 V = 7474 TTR = 0.199 C = 0.847
Jak widać pozbycie się słów funkcyjnych skróciło książkę prawie o połowę! Rzecz jasna, liczba uniklanych słów mogła zmaleć maksymalnie o tyle, ile jest słów funkcyjnych. Możemy jeszcze trochę ograniczyć nasz zbiór, jeśli odwołamy się do procedury stemowania, czyli sprowadzania różnych słów do tego samego rdzenia (np. “worker”, “workers”, “working”, “worked” można sprowadzić do rdzenia work). Zastosujemy tu tzw. stemmer Portera
from nltk.stem.porter import *
stemmer = PorterStemmer()
verne_book_stem = [stemmer.stem(word) for word in verne_book_wos]
get_stats(verne_book_stem)
## M = 37608 V = 5404 TTR = 0.144 C = 0.816
Oczywiście, całkowita liczba słów się w tym wypadku nie zmieniła (bo nic nie usuwaliśmy), natomiast liczba unikalnych słów zmiejszyła się o prawie 1/3.
Aby w miarę zgrabnie porównać poszczególne zbiory słów, skorzystamy ze funkcji FreqDist(), która po prostu zlicza występowanie słów:
f_verne_full = nltk.FreqDist(verne_book)
f_verne_full
## FreqDist({'the': 4907, 'and': 1976, 'of': 1934, 'to': 1757, 'a': 1377, '“': 1357, '”': 1356, 'in': 1116, 'was': 1006, 'he': 989, ...})
Przydatna okaże się metoda most_common(), za pomoca której możemy łatwo wypisać najpopularniejsze słowa. Ograniczmy się do 30 “topowych” i porównamy je za pomocą ramki danych z pakietu pandas
import pandas as pd
f_verne_wos = nltk.FreqDist(verne_book_wos)
f_verne_stem = nltk.FreqDist(verne_book_stem)
df_verne_full = pd.DataFrame(f_verne_full.most_common(30), columns = ["word", "N"])
df_verne_wos = pd.DataFrame(f_verne_wos.most_common(30), columns = ["word", "N"])
df_verne_stem = pd.DataFrame(f_verne_stem.most_common(30), columns = ["word", "N"])
df_all = pd.concat([df_verne_full, df_verne_wos, df_verne_stem], axis = 1)
df_all
## word N word N word N
## 0 the 4907 “ 1357 “ 1357
## 1 and 1976 ” 1356 ” 1356
## 2 of 1934 fogg 643 fogg 643
## 3 to 1757 ’ 477 ’ 477
## 4 a 1377 passepartout 422 passepartout 422
## 5 “ 1357 mr. 368 mr. 368
## 6 ” 1356 would 283 would 283
## 7 in 1116 phileas 256 fix 263
## 8 was 1006 fix 255 philea 256
## 9 he 989 said 194 said 194
## 10 his 858 — 192 — 192
## 11 at 659 one 171 one 172
## 12 fogg 643 could 140 day 162
## 13 it 589 aouda 136 hour 145
## 14 with 566 master 126 could 140
## 15 not 557 time 120 go 139
## 16 that 547 upon 120 time 138
## 17 on 538 train 117 train 137
## 18 which 518 two 101 aouda 136
## 19 had 513 sir 101 master 128
## 20 ’ 477 project 99 upon 120
## 21 as 451 hundred 98 pass 110
## 22 for 445 replied 93 steamer 106
## 23 passepartout 422 hours 89 repli 103
## 24 you 393 without 88 project 101
## 25 by 392 steamer 88 two 101
## 26 but 382 thousand 86 sir 101
## 27 i 368 made 86 seem 99
## 28 mr. 368 well 84 hundr 99
## 29 this 356 day 84 like 96
Wobraźmy sobie teraz sytuację, w której mamy do dyzpozycji nie jeden, lecz kilka dokumentów. Chcielibyśmy wykonać większość powyższych operacji automatycznie - to jedno. Po drugie, możemy też potrzebować innej reprezentacji tekstu niż ta, oparta tylko na zwykłych zliczeniach. W sukurs przychodzi nam tu znany już z zajęć LSED pakiet sklearn i funkcje CountVectorizer, TfidfTransformer i TfidfVectorizer.
Zaczynamy od stworzenia korpusu dokumentów. Pod tą nazwą, w szerszym znaczeniu, kryje się po prostu połączony w jakiś sposób zestaw tekstów. Dla uwagi ograniczymy sie na razie do czegoś bardzo małego:
corpus = [
"Once upon a time there was a king who wished to have a child.",
"Once upon a time, in a faraway land there lived a beautiful princess.",
"In the olden time, when wishing was having, there used to live a King."
]
corpus
## ['Once upon a time there was a king who wished to have a child.', 'Once upon a time, in a faraway land there lived a beautiful princess.', 'In the olden time, when wishing was having, there used to live a King.']
W tym momencie skorzystamy już z CountVectorizer(), który ma strukturę podobna do innych funkcji z pakietu sklearn, tzn. musimy najpierw stworzyc obiekt, a następnie użyć funkcji fot() i transform(0, względnie fit_transform(). Zdefiniwaliśmy też trochę inny wzorzec rozdziału na tokeny, bo domyślny pomijał słowa krótsze niż dwuliterowe.
from sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer(token_pattern=r"(?u)\b\w+\b")
words = vec.fit_transform(corpus)
df_words = pd.DataFrame(words.T.toarray(), vec.get_feature_names_out())
df_words
## 0 1 2
## a 3 3 1
## beautiful 0 1 0
## child 1 0 0
## faraway 0 1 0
## have 1 0 0
## having 0 0 1
## in 0 1 1
## king 1 0 1
## land 0 1 0
## live 0 0 1
## lived 0 1 0
## olden 0 0 1
## once 1 1 0
## princess 0 1 0
## the 0 0 1
## there 1 1 1
## time 1 1 1
## to 1 0 1
## upon 1 1 0
## used 0 0 1
## was 1 0 1
## when 0 0 1
## who 1 0 0
## wished 1 0 0
## wishing 0 0 1
Ramka danych, którą otrzymalismy to tzw. macierz termów-dokumentów (TDM matrix), często przedstawiana w odwrotnej wersji, tj. macierzy dokumentów-termów (DTM matrix), czasem nazywna również macierzą dokumentów-cech (document-feature matrix, DFM). Generalnie chodzi o przedstawienie korpusu dokuemntów w takiej formie, w której rzędami lub kolumnami są tokeny a kolumnami lub rzędami są dokumenty.
Wielkim plusem tego typu reprezentacji jest możliwość łatwego porównania dokumentów, np. za pomocą iloczynu skalarnego. W tym celu po prostu mnożymy macierz TDM przez jej transponowaną postać (dokładnie to na odwrót :-):
mat = df_words.T @ df_words
mat
## 0 1 2
## 0 20 13 8
## 1 13 19 6
## 2 8 6 14
Taką macierz łatwo możemy przedstawić w formie mapy ciepła za pomocą pakietu seaborn
import numpy as np
import seaborn as sns
mat = np.array(mat)
np.fill_diagonal(mat, 0)
sns.heatmap(mat)
Możemy też tworząc tokenizator zażądać usunięcia słów funkcyjnych:
vec = CountVectorizer(token_pattern=r"(?u)\b\w+\b", stop_words = "english")
words = vec.fit_transform(corpus)
df_words = pd.DataFrame(words.T.toarray(), vec.get_feature_names_out())
df_words
## 0 1 2
## beautiful 0 1 0
## child 1 0 0
## faraway 0 1 0
## having 0 0 1
## king 1 0 1
## land 0 1 0
## live 0 0 1
## lived 0 1 0
## olden 0 0 1
## princess 0 1 0
## time 1 1 1
## used 0 0 1
## wished 1 0 0
## wishing 0 0 1
Zastanówmy sie traz, jak w prosty sposób można uzyskać transformację TF-IDF (term frequency - inverse dokuent frequency), w którj każdemu słowu (tokenowi) w danym dokumencie przypisujemy wartość:
\[ (tf-idf)_{ij} = tf_{ij} \times idf_i = \frac{n_{ij}}{\sum_j n_{ij}} \log\left( \frac{M}{df_i}\right)\] gdzie \(n_{ij}\) to liczba wystąpień słowa \(i\) w dokumencie \(j\), natomiast \(df_i\) to liczba dokumentów (ze wszystkich dokumentów \(M\)), w których występuje słowo \(i\).
Bardzo łatwo jest stworzyć prosty kod do obliczenia tej transformacji:
import numpy as np
idf = np.log(df_words.shape[1] / df_words.apply(lambda x: sum(x>0), axis = 1))
df_words.mul(idf, axis = 0)
## 0 1 2
## beautiful 0.000000 1.098612 0.000000
## child 1.098612 0.000000 0.000000
## faraway 0.000000 1.098612 0.000000
## having 0.000000 0.000000 1.098612
## king 0.405465 0.000000 0.405465
## land 0.000000 1.098612 0.000000
## live 0.000000 0.000000 1.098612
## lived 0.000000 1.098612 0.000000
## olden 0.000000 0.000000 1.098612
## princess 0.000000 1.098612 0.000000
## time 0.000000 0.000000 0.000000
## used 0.000000 0.000000 1.098612
## wished 1.098612 0.000000 0.000000
## wishing 0.000000 0.000000 1.098612
Jak łatwo można zauważyć, wykorzystanie funkcji TfIdfVectorizer() z pakietu sklearn daje trochę inne wyniki:
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vec = TfidfVectorizer(token_pattern=r"(?u)\b\w+\b")
tfidf_words = tfidf_vec.fit_transform(corpus)
df_tfidf = pd.DataFrame(tfidf_words.T.toarray(), tfidf_vec.get_feature_names_out())
df_tfidf
## 0 1 2
## a 0.540935 0.544931 0.183495
## beautiful 0.000000 0.307550 0.000000
## child 0.305294 0.000000 0.000000
## faraway 0.000000 0.307550 0.000000
## have 0.305294 0.000000 0.000000
## having 0.000000 0.000000 0.310684
## in 0.000000 0.233899 0.236283
## king 0.232184 0.000000 0.236283
## land 0.000000 0.307550 0.000000
## live 0.000000 0.000000 0.310684
## lived 0.000000 0.307550 0.000000
## olden 0.000000 0.000000 0.310684
## once 0.232184 0.233899 0.000000
## princess 0.000000 0.307550 0.000000
## the 0.000000 0.000000 0.310684
## there 0.180312 0.181644 0.183495
## time 0.180312 0.181644 0.183495
## to 0.232184 0.000000 0.236283
## upon 0.232184 0.233899 0.000000
## used 0.000000 0.000000 0.310684
## was 0.232184 0.000000 0.236283
## when 0.000000 0.000000 0.310684
## who 0.305294 0.000000 0.000000
## wished 0.305294 0.000000 0.000000
## wishing 0.000000 0.000000 0.310684
Jest to związane z innym podejściem, stosowanym w tej funkcji. Po pierwsze faktyczny wzór na transformację wygląda następująco:
\[ (tf-idf)_{ij} = tf_{ij} \times idf_i = n_{ij} \left[1+\log\left( \frac{1+M}{1+df_i}\right)\right]\]
co zapobiega wartościom 0 dla słów, które występują we wszystkich dokumentach, a dodatkowo uwalnia nas od problemu, gdy jakieś słowo (z róznych powodów) nie występuje w żadnym dokumencie (co powodowało rozbieganie się wartosci logarytmu). Po drugie, tak otrzymane wartości są normowane zgodnie z normą L2, czyli
\[ \hat{v_i} = \frac{v_i}{\sqrt{v^2_1+v^2_2+...+v^2_n}}\] Jeśli się zastosujemy do tego “przepisu”, otrzymamy faktycznie identyczne wyniki
idf = np.log((1 + df_words.shape[1]) / (1 + df_words.apply(lambda x: sum(x>0), axis = 1))) + 1
x = df_words.mul(idf, axis = 0)
x = x / x.apply(lambda x: np.sqrt(sum(x**2)))
print(x.to_markdown())
| 0 | 1 | 2 | |
|---|---|---|---|
| beautiful | 0 | 0.432385 | 0 |
| child | 0.584483 | 0 | 0 |
| faraway | 0 | 0.432385 | 0 |
| having | 0 | 0 | 0.410747 |
| king | 0.444514 | 0 | 0.312384 |
| land | 0 | 0.432385 | 0 |
| live | 0 | 0 | 0.410747 |
| lived | 0 | 0.432385 | 0 |
| olden | 0 | 0 | 0.410747 |
| princess | 0 | 0.432385 | 0 |
| time | 0.345205 | 0.255374 | 0.242594 |
| used | 0 | 0 | 0.410747 |
| wished | 0.584483 | 0 | 0 |
| wishing | 0 | 0 | 0.410747 |
Pewnym bonusem, który znajdziemy w pakiecie nltk jest zestaw różnych korpusów. Jednym z nich jest zestawienie mów inauguracyjnych kolejnych prezydentów USA
from nltk.corpus import inaugural
import matplotlib.pyplot as plt
inaugural.fileids()
## ['1789-Washington.txt', '1793-Washington.txt', '1797-Adams.txt', '1801-Jefferson.txt', '1805-Jefferson.txt', '1809-Madison.txt', '1813-Madison.txt', '1817-Monroe.txt', '1821-Monroe.txt', '1825-Adams.txt', '1829-Jackson.txt', '1833-Jackson.txt', '1837-VanBuren.txt', '1841-Harrison.txt', '1845-Polk.txt', '1849-Taylor.txt', '1853-Pierce.txt', '1857-Buchanan.txt', '1861-Lincoln.txt', '1865-Lincoln.txt', '1869-Grant.txt', '1873-Grant.txt', '1877-Hayes.txt', '1881-Garfield.txt', '1885-Cleveland.txt', '1889-Harrison.txt', '1893-Cleveland.txt', '1897-McKinley.txt', '1901-McKinley.txt', '1905-Roosevelt.txt', '1909-Taft.txt', '1913-Wilson.txt', '1917-Wilson.txt', '1921-Harding.txt', '1925-Coolidge.txt', '1929-Hoover.txt', '1933-Roosevelt.txt', '1937-Roosevelt.txt', '1941-Roosevelt.txt', '1945-Roosevelt.txt', '1949-Truman.txt', '1953-Eisenhower.txt', '1957-Eisenhower.txt', '1961-Kennedy.txt', '1965-Johnson.txt', '1969-Nixon.txt', '1973-Nixon.txt', '1977-Carter.txt', '1981-Reagan.txt', '1985-Reagan.txt', '1989-Bush.txt', '1993-Clinton.txt', '1997-Clinton.txt', '2001-Bush.txt', '2005-Bush.txt', '2009-Obama.txt', '2013-Obama.txt', '2017-Trump.txt', '2021-Biden.txt', '2025-Trump.txt']
Tak krótka jest np. mowa Waszyngtona z początku drugiej kadnecji:
inaugural.raw(inaugural.fileids()[1])
## 'Fellow citizens, I am again called upon by the voice of my country to execute the functions of its Chief Magistrate. When the occasion proper for it shall arrive, I shall endeavor to express the high sense I entertain of this distinguished honor, and of the confidence which has been reposed in me by the people of united America.\n\nPrevious to the execution of any official act of the President the Constitution requires an oath of office. This oath I am now about to take, and in your presence: That if it shall be found during my administration of the Government I have in any instance violated willingly or knowingly the injunctions thereof, I may (besides incurring constitutional punishment) be subject to the upbraidings of all who are now witnesses of the present solemn ceremony.\n\n \n'
bardzo prostą, a zaraz niesłychanie popularną techniką przedstawiania i podsumowaywania dokumnetów sa chmury słów (wordclouds). W zasadzie jest to dokładnie to samo, to wykresy częstotliwościowe unigramów, dzięki innemu sposobowi prezentacji są one wyjatkowo atrakcyjne i przemawiające do odbiorcy.
from wordcloud import WordCloud
def clean_text(text):
words = nltk.word_tokenize(text)
words = [w.lower() for w in words]
words = [w for w in words if w not in string.punctuation]
words = [w for w in words if w not in stopwords]
return(words)
w = clean_text(inaugural.raw(inaugural.fileids()[0]))
wordcloud = WordCloud(background_color="white").generate(' '.join(w))
plt.imshow(wordcloud)
plt.axis("off");
Chmury można łatwo wykorzystać do porównywania tekstów:
speeches = {
'Washington 1789': inaugural.raw('1789-Washington.txt'),
'Lincoln 1861': inaugural.raw('1861-Lincoln.txt'),
'Kennedy 1961': inaugural.raw('1961-Kennedy.txt'),
'Obama 2009': inaugural.raw('2009-Obama.txt'),
}
cleaned = {name: clean_text(text) for name, text in speeches.items()}
fig, axes = plt.subplots(2, 2, figsize=(7, 5))
axes = axes.flatten()
for ax, (name, text) in zip(axes, cleaned.items()):
wc = WordCloud(
width=300, height=200,
background_color='white',
colormap='RdYlGn',
max_words=25
).generate(' '.join(text))
ax.imshow(wc,)
ax.set_title(name, fontsize=14, fontweight='bold')
ax.axis('off')
## <matplotlib.image.AxesImage object at 0x0000023B60F17290>
## Text(0.5, 1.0, 'Washington 1789')
## (np.float64(-0.5), np.float64(299.5), np.float64(199.5), np.float64(-0.5))
## <matplotlib.image.AxesImage object at 0x0000023B651EE5D0>
## Text(0.5, 1.0, 'Lincoln 1861')
## (np.float64(-0.5), np.float64(299.5), np.float64(199.5), np.float64(-0.5))
## <matplotlib.image.AxesImage object at 0x0000023B60E50A10>
## Text(0.5, 1.0, 'Kennedy 1961')
## (np.float64(-0.5), np.float64(299.5), np.float64(199.5), np.float64(-0.5))
## <matplotlib.image.AxesImage object at 0x0000023B651BFF10>
## Text(0.5, 1.0, 'Obama 2009')
## (np.float64(-0.5), np.float64(299.5), np.float64(199.5), np.float64(-0.5))
plt.suptitle('Inaugural Speech Word Clouds', fontsize=16, y=1.02)
plt.tight_layout()
plt.show();
Jednym z częstych zagadnień związanych z text mining jest budowa tzw. word embedding, czyli sposobu reprezentacji wyrazów w postaci liczbowej. W pewien sposób mówiliśmy już o tym, kiedy rozpatrywaliśmy model przestrzeni wektorowej - jest to jednak bardzo ograniczona reprezentacja.
Semantyka dystrybucyjna znalazła w ostatnich latach szerokie zastosowanie w rozwiązywaniu szeregu zadań związanych z przetwarzaniem języka naturalnego. U jej podstaw leży hipoteza, że słowa występujące w podobnych kontekstach w dużych zbiorach danych tekstowych mają podobne znaczenie. Znaczenia słów reprezentowane są przez wektory liczbowe.
Jednym z bardziej popularnych przykładów, należącym do tej grupy metod jest word2vec, stworzony przez Tomasa Mikolova z Google w 2013 roku. Podejście to może wykorzystywać dwie różne techniki: CBOW - Continuous Bag of Words oraz Skip-Gram. Teoretycznie metody są algorytmicznie identyczne, oprócz tego, że CBOW przewiduje kluczowe słowo na podstawie kontekstu np. ``cat sits on the mat’’, a Skip-Gram odwrotnie. Word2vec używa sieci neuronowej z pojedynczą warstwą jako podstawowej architektury, ale jako ogólny wskaźnik używane jest po prostu prawdopodobieństwo \(p(w_t | h)\) słowa \(w_t\) pod warunkiem historii (otoczenia) \(h\), które jest wyznaczane przy użyciu metody największej wiarygodności.
Zaczniemy od testowania działania modelu na bardzo małym przykładzie - oczywiście w tym przypadku nie ma mowy o tym, aby działał on odpowiednio, chodzi jedynie o szybki test, bez użycia większych mocy. Korzystamy z pakietu gensim oraz jego funkcji Word2Vec(). Nasz zestaw dokumentów, to zaledwie kilka zdań, do tego z powtarzającymi się słowami:
from gensim.models import Word2Vec
sentences = [["cat", "say", "meow"], ["dog", "say", "woof"],["kitten", "say", "meow"],["puppy", "say", "woof"]]
Warto też uruchomić opcję śledzenia postępu wykonywania funkcji
import logging
logging.basicConfig(format="%(levelname)s - %(asctime)s: %(message)s", datefmt= '%H:%M:%S', level=logging.INFO)
Uruchamiamy główną funkcję, ustalając wymiar zanurzeiowy na 10 - jest to dość niewielkie wartość, ale wakuratw ptym przypadku nie ma specjalnego znaczenia.
model = Word2Vec(sentences, min_count=1, vector_size=20)
Głównym obiektem jest wv, przechowujący zanurzenia (czyli embeddings), do których dostaniemy się za pomocą obiektu vectors
model.wv.vectors
## array([[-0.00268114, 0.00118216, 0.02551675, 0.04504637, -0.04651475,
## -0.03558404, 0.03229436, 0.04486494, -0.02507714, -0.01881686,
## 0.03690252, -0.00766736, -0.02268307, 0.03277026, -0.0243008 ,
## -0.00908009, 0.0143829 , 0.00495937, -0.04142607, -0.04724409],
## [ 0.03655883, 0.02535131, 0.03378846, 0.00381433, 0.03175445,
## -0.01702683, -0.00473201, 0.02884287, -0.03760819, -0.01968052,
## -0.03755791, -0.00465021, 0.04769059, -0.03659583, -0.01166884,
## -0.00968871, 0.04038718, -0.02965448, 0.00022581, -0.02376867],
## [-0.04801775, 0.02503647, -0.04379793, -0.02195913, -0.0001755 ,
## -0.00148091, -0.0383062 , 0.04807372, 0.02491029, 0.04616572,
## -0.04078959, 0.02247899, -0.02068538, 0.00412268, 0.0424931 ,
## -0.02231088, 0.0225875 , -0.0339348 , -0.01774244, 0.04699254],
## [-0.00788826, 0.00160686, -0.02070315, -0.03841344, -0.00754004,
## 0.01234897, -0.00444013, 0.02766831, -0.01371489, 0.01130033,
## 0.02727897, 0.04172977, -0.0072687 , -0.04604071, 0.02185276,
## 0.00285892, 0.03720954, -0.00406641, -0.01319207, -0.04376505],
## [-0.00428278, 0.01413282, 0.02700714, 0.03526328, -0.02851561,
## 0.0092941 , 0.03044432, -0.02399025, -0.0155363 , 0.03398815,
## 0.00815738, 0.00094959, 0.01736819, 0.00108889, 0.04809413,
## 0.02530302, -0.04458695, -0.0352078 , 0.00450728, 0.03196267],
## [-0.04309844, 0.01832869, 0.02594942, 0.02870969, 0.03733459,
## -0.03083838, 0.00552807, 0.03023641, -0.01420025, -0.03086761,
## -0.00205112, -0.04184474, -0.02800006, 0.03552269, 0.0167627 ,
## 0.03612835, 0.03400124, 0.03765371, -0.01894577, -0.00280903],
## [ 0.01174188, -0.02259516, 0.04194366, -0.04929082, 0.0338232 ,
## 0.01457208, -0.02466416, 0.02199094, -0.00869787, 0.03355692,
## 0.04982425, -0.02181222, -0.00299669, -0.02847819, 0.01925411,
## 0.01393313, 0.03445538, 0.03050548, 0.04769249, 0.04636709]],
## dtype=float32)
Jest dość bezsensowany sposób przedtawiania zanurzeń, dużo łatwiej jest wykorzystać mapę ciepła. Skorzystamy tu także z obiektu index_to_key, przechowującego tokeny:
import seaborn as sns
hm = sns.heatmap(model.wv.vectors, linewidth=1, square=True, cmap="coolwarm", yticklabels = model.wv.index_to_key)
hm.set_yticklabels(hm.get_yticklabels(), rotation=0);
Wygodną funkcją jest most_similar(), która wypisze nam najbardziej podobne tokeny, zgodnie z przestrzenią zanurzeniową:
model.wv.most_similar(positive=["cat"])
## [('puppy', 0.18296225368976593), ('dog', 0.06596562266349792), ('woof', 0.028597965836524963), ('meow', 0.021228104829788208), ('kitten', -0.07021170109510422), ('say', -0.3477143943309784)]
W naszym przypadku dużo łatweij jest po prostu uzyć funkcji cosine_similarity() z pakietu sklearn i sparwdzić jak wygląda podobieństwo pomiedzy wszystkimi słowami:
from sklearn.metrics.pairwise import cosine_similarity
A = cosine_similarity(model.wv.vectors)
hm = sns.heatmap(A, linewidth=1, square=True, cmap="coolwarm", yticklabels = model.wv.index_to_key,xticklabels = model.wv.index_to_key)
hm.set_yticklabels(hm.get_yticklabels(), rotation=0);
Jak widać, nie otrzymamy tu niczego ciekawego, bo nasz model uczony był zaledwie na kilku zdaniach. Aby faktycznie można było mówić o modelu word2vec musimy sięgnąć po coś trochę większego
Tym razem skorzystamy z pliku, który jest zrzutem części Wikipedii o rozmairze ok 100MB - gensim ma funkcję, która odnosi się do tego pliku, ale musimy wskazać jego lokalizację:
from gensim.models.word2vec import Text8Corpus
sentences = Text8Corpus(fname = 'http://www.if.pw.edu.pl/~julas/TEXT/lab/text8')
Powinniśmy też mieć trochę więcej kontroli na tym, co robimy. Zostawimy sobie jeden woly rdzeń procesora i zainicjujemy model, ograniczając się do wymiaru zanurzeniowego 50
import multiprocessing
from time import time
n = multiprocessing.cpu_count()
big_model = Word2Vec(min_count=20, vector_size = 50, workers=n-1)
Teraz budujemy oddzielnie słownik:
t = time()
big_model.build_vocab(sentences, progress_per=10000)
print('Time to build vocab: {} mins'.format(round((time() - t) / 60, 2)))
## Time to build vocab: 0.51 mins
i w końcu uruchamiany model
t = time()
big_model.train(sentences, total_examples=big_model.corpus_count, epochs=20, report_delay=1)
## (242146476, 340104140)
print('Time to train the model: {} mins'.format(round((time() - t) / 60, 2)))
## Time to train the model: 10.05 mins
Jak widać, na w miare sensownym laptopie potrzebujemy ok. 10 minut, aby otrzymać wyniki. Możemy teraz wypisac wyrazy podobne do słowa “kot”:
big_model.wv.most_similar(positive=["cat"])
## [('dog', 0.8301306962966919), ('cow', 0.8061699271202087), ('cute', 0.7866405248641968), ('ass', 0.7724205851554871), ('goat', 0.7664780020713806), ('pig', 0.7587183117866516), ('panda', 0.7568443417549133), ('canine', 0.7529604434967041), ('rat', 0.7407963275909424), ('dumb', 0.73359215259552)]
pokazać reprezentację zanurzeniową wybranych słów:
words = ["dog", "cat", "fish", "man", "boy", "girl", "woman", "star", "planet"]
hm = sns.heatmap(big_model.wv[words], linewidth=1, cmap="coolwarm", yticklabels =words)
hm.set_yticklabels(hm.get_yticklabels(), rotation=0);
czy wreszcie macierz podobieństwa:
A = cosine_similarity(big_model.wv[words])
hm = sns.heatmap(A, linewidth=1, square=True, cmap="coolwarm", yticklabels = words, xticklabels = words)
hm.set_yticklabels(hm.get_yticklabels(), rotation=0);
Ciekawą cechą tego typu modeli jest to, że skoro operujemy w pewnej przestrzeni wektorowej, to w pewien sposób możemy oczekiwać, że będzie tam działać zwykła arytmetyka wektorowa. W szczególności dodawanie i odejmowanie może doprowadzić do ciekawych wyników:
big_model.wv.most_similar(positive=["paris", "germany"], negative = "france")
## [('berlin', 0.8523723483085632), ('munich', 0.8490253686904907), ('leipzig', 0.7829859852790833), ('vienna', 0.7632940411567688), ('zurich', 0.7588172554969788), ('stuttgart', 0.7300403118133545), ('mannheim', 0.7215974926948547), ('frankfurt', 0.7131195068359375), ('heidelberg', 0.7114905118942261), ('hamburg', 0.7075153589248657)]
czy
big_model.wv.most_similar(positive=["man", "she"], negative = "he")
## [('woman', 0.8856458067893982), ('girl', 0.8413165807723999), ('maid', 0.7518028616905212), ('stranger', 0.7340599298477173), ('lover', 0.7298490405082703), ('totoro', 0.7291558980941772), ('love', 0.7291179895401001), ('prostitute', 0.7249441742897034), ('thief', 0.7208672761917114), ('bride', 0.7140963077545166)]