Académique Documents
Professionnel Documents
Culture Documents
fonetyka (dwiki),
metody formalne zbir regu pozwalajcy otrzyma rozbir gramatyczny zdania zgodny z
wybran teori (jak do tej pory brak implementacji wydajnej i dajcej jednoznaczne rozbiory),
segment (token): podstawowy element tekstu oddzielony najczciej odstpami lub znakami
interpunkcyjnymi; moe to by sowo, ale te np. PESEL, kod pocztowy, nr telefonu, data, godzina, adres e-mail,
zdanie
Problemem s wyraenia typu po prostu czasami traktuje si je jako jeden atom.
fleksja opisuje rne formy tego samego fleksemu np. kot kotem
przyswki: stopie
jzyk naturalny jest bardzo skomplikowany i adna z gramatyk nie opisuje go w caoci, w
praktyce oznacza to, e jeeli wemiemy np. codzienn gazet, to prawie na pewno ju na pierwszej stronie
znajdziemy zdania, ktre nie bd analizowane przez adn z istniejcych gramatyk danego jzyka, to znaczy, e
zdania te nie uznane zostan za poprawne,
analiza syntaktyczna jest do kosztowna, nie jest wic moliwa analiza duej liczby zda w
krtkim czasie (cho powoli czasy analizy syntaktycznej staj si akceptowalne).
Najwaniejsz przeszkod w praktycznym wykorzystaniu dokadnych analiz syntaktycznych jest brak metod
pozwalajcych na zapis znaczenia zda w jzyku naturalnym, nawet jeli posiadamy ich bardzo dokadn analiz
syntaktyczn. Sam rozbir gramatyczny zdania nie jest zwykle celem samym w sobie. To, co rzeczywicie chcemy
pozna, to znaczenie zdania.
Prby komputerowej analizy skadniowej zda jzyka polskiego podejmowane s od wielu lat, wci jednak s
do wyrywkowe, a efekty tych prac mao dostpne poza grupami bezporednio si nimi zajmujcymi.
Do wielu zastosowa (np. indeksowanie tekstu, wyszukiwanie nazw wasnych) nie opaca si dokonywa
dokadnej analizy skadniowej.
Parsowanie pytkie rozpoznawanie podstawowych typw fraz (czenie wyrazw zdania w grupy wyrazw
strukturalnie powizanych, czsto odmieniajcych si jednakowo)
Semantyka. Rozpoznawanie sw i konstrukcji skadniowych jest tylko wstpem do zasadniczej operacji, jakiej
naley dokona, by mc posugiwa si jzykiem naturalnym zrozumienia znaczenia. Niestety, aden z
istniejcych obecnie formalizmw nie jest w stanie odda caej rnorodnoci procesw zwizanych z
rozumieniem jzyka naturalnego, a wic adna z zaproponowanych metod reprezentacji semantyki zda jzyka
naturalnego nie pozwala na pene reprezentowanie tego, co dla czowieka jest znaczeniem tekstu.
Sowosie (WordNet) rozbudowana baza wiedzy o powizaniach semantycznych sw konkretnego jzyka
naturalnego.
homonimia jednakowy ksztat sowa, rne znaczenia, np. pokj pomieszczenie i pokj
przeciwiestwo wojny
polisemia wielo powizanych znacze jednego sowa, np. gra (wzniesienie terenu, pitro
domu, cz ubrania)
synonimia rne leksemy o tym samym (prawie) znaczeniu (mogce si nawzajem zastpi
w pewnym kontekcie), np.samochd i auto
korpusy specjalistyczne dla dialektu bd okresu czasu, dla jzyka z jakiej dziedziny
specjalistycznej,
Model wektorowy (VSM, ang. Vector Space Model) dokumenty i pytania przedstawiane s
w postaci wektorw cech reprezentujcych poszczeglne obiekty (dokadniej warto i-tej wsprzdnej okrela,
czy obiekt i-ty wystpuje czy nie w danym dokumencie). Dla dokumentw tekstowych obiektami s zazwyczaj
wystpujce w nich sowa zwykle dokonuje si wstpnego wyboru podzbioru sw istotnych dla separacji
tekstw.
Numeryczne metody wyszukiwania interesujcych nas dokumentw musz uwzgldni fakt, e zarwno sw, jak i
dokumentw jest bardzo wiele, tak wic przestrze przeszukiwania jest wielowymiarowa. Niejawna (ukryta)
analiza semantyczna (LSA Latent Semantic Analysis, lub LSI Latent Semantic Indexing) jest jedn z bardziej
popularnych metod obnienia zoonoci tego problemu.
Zbir dokumentw reprezentowany jest na og jako macierz X, ktrej kolumny opisuj dokumenty w postaci
wektorw czstoci wystpowania poszczeglnych sw. Jeeli zaoymy, e baza zawiera m dokumentw i n sw,
to odpowiednia macierz ma rozmiar nxm. Ide podstawow LSA jest redukcja liczby ocenianych zmiennych, przy
jednoczesnym zapewnieniu warunku, by wykorzystywana do nich macierz bya najblisz (dla wybranego rzdu)
macierzy oryginalnej. W konsekwencji obniania wymiaru wiele poj czonych jest w jedno (uzyskujemy liniowe
kombinacje ich wag). Jeeli czone s pojcia pokrewne, to dziki tej operacji uzyskujemy metod
reprezentowania synonimii. O ile zatem oryginalna macierz reprezentujca dokument zawiera tylko informacje o
sowach, ktre rzeczywicie si w nim znalazy, to macierz uzyskana w wyniku przeksztace zawiera take
informacje o wyrazach bliskoznacznych, czyli takich, ktre czytelnik bez trudu z nim skojarzy (wiemy, e tekst o
wierkach jest tekstem o rolinach, nawet jeli sowo rolina w nim si nie znajduje).
Automatyczne streszczenia
Ocena systemw streszczajcych nie jest atwa, gdy trudno jest znale obiektywny punkt
odniesienia
Sowa, ktre pojawiaj si w tytule i pierwszych paru zdaniach maj wysz wag
Istotne s zdania zawierajce: liczby, nazwy wasne, nazwy dni tygodnia itp.
Na wiecie jest obecnie ok. 4500 opisanych jzykw, z czego ok. 2200 jzykw ma wersj pisan.
Jeeli bierzemy pod uwag jzyk ojczysty, to nie jzyk angielski jest najbardziej popularny, ale
chiski, a dopiero do daleko po nim jest angielski, hiszpaski, hindi i arabski.
Jeli rozpatrujemy liczb mieszkacw krajw, w ktrych dany jzyk jest jzykiem urzdowym
(lub jednym z takowych), to kolejno jest odmienna: angielski, chiski, hindi, hiszpaski i francuski.
tumaczenie ograniczone do wskiego podzbioru jzyka (np. prognozy pogody, raporty giedowe,
instrukcje obsugi urzdze).
Metody automatycznego tumaczenia (w praktyce czy si kilka z nich):
metody mieszane (czenie elementw rnych metod jest najczciej spotykane w praktyce).
Podejmowane s prby opracowania programw tumaczcych teksty na jzyk polski i teksty polskie na inne
jzyki. Gwne obecnie na rynku komercyjne systemy automatycznego tumaczenia to English Translator firmy
Techland oraz Translatica wydawana przez PWN.
System Translatica jest owocem wsppracy poznaskiego rodowiska akademickiego, w ktrym od wielu lat
prowadzone byy prace nad systemem tumaczcym teksty polskie na angielskie oraz uznanego polskiego
wydawcy sownikw (zarwno jzyka polskiego, jak i sownikw dwujzycznych). Historia prac nad Translatic
siga roku 1995. W pierwszej wersji systemu pod nazw PolEng tumaczenie dokonywane byo na drodze
interpretacji klauzul Prologowych. W kolejnej wersji jdro systemu zaimplementowano w C++, a zstpujcy
mechanizm parsowania zastpiono wstpujcym, dziki czemu znacznie wzrosa szybko tumaczenia, a ponadto
moliwe stao si tumaczenie zda, dla ktrych system nie umia znale rozbioru syntaktycznego. W roku 2003
w wyniku wsppracy z PWN wczono do systemu Wielki Sownik Angielsko-Polski PWN-Oxford i zrealizowano
drugi, bardziej komercyjnie interesujcy, kierunek tumaczenia (z angielskiego na polski). Opracowano te
dostosowan do potrzeb tumaczenia baz powiza semantycznych sw.
we need a way to level the playing field for documents of all shapes and sizes. Maybe
just sizes.
Idf, the other factor in the equation, also known as inverse document frequency,
normalizes the term frequency value so that common words used by all documents are
given very little importance. Examples include "the" for English documents or "for" for
source code, as neither term is unique to any particular document even though they both
probably appear very often in all documents.
One example application of this algorithm would be listing the top ten most interesting
words for a post on a blog. This would surface words that more or less uniquely identify a
post, and could be used for the keywords in the HTML header to maximize the SEO
value of a permalink. But of course there's plenty of other uses.
Still confused? Let's just jump right into the code!
Putting tf-idf into action: using Python
As Randall Munroe puts it, Python is executable psuedocode. Take a for loop in PHP for
example:
for ($i=0; $i<10; $i++) {
echo $i;
}
In PHP you use curly braces to indicate control flow. It's great and explicit. But when I'm
prototyping something quickly it's kind of annoying to have to use curly braces to realize
an idea in my head. Sheesh. If I just wanted to write the pseudocode for it now and write
the real, executable code later I would write something like this:
for i in range(10):
print i
Oh wait, that's Python. And it's executable. Niiiiice. The whitespace is important as it
contains the control flow information. Everything that's indented after that for statement
will be looped through and the first non-indented statement after the for loop will indicate
the end of the for loop.
OK, so let's put this tf-idf algorithm into psuedocode/Python! Let's make it object-oriented
so I'll start with the tf part of the equation:
def tf(word, document):
return (freq(word,document) / float(wordCount(document)))
Hmm, looks like we'll need to write a couple helper functions...
def freq(word, document):
return document.split(None).count(word)
def wordCount(document):
return len(document.split(None))
There we go. If you're curious what the split(None) does it breaks a string into chunks
when it hits whitespace. Alright, half way there...now for idf:
def idf(word, documentList):
return math.log(len(documentList) /
numDocsContaining(word,documentList))
Again we'll need a helper function that counts the number of documents containing a
word:
def numDocsContaining(word,documentList):
count = 0
for document in documentList:
if freq(word,document) > 0:
count += 1
return count
Finally we've got both parts of the equations so all we need is one last function!
def tfidf(word, document, documentList):
if __name__ == '__main__':
documentList = []
documentList.append("""DOCUMENT #1 TEXT""")
documentList.append("""DOCUMENT #2 TEXT""")
documentList.append("""DOCUMENT #3 TEXT""")
words = {}
documentNumber = 0
for word in documentList[documentNumber].split(None):
words[word] =
tfidf(word,documentList[documentNumber],documentList)
for item in sorted(words.items(), key=itemgetter(1),
reverse=True):
print "%f <= %s" % (item[1], item[0])
Download or fork the source code on Github: http://github.com/timtrueman/tf-idf
#!/usr/bin/env python
"""
The simplest TF-IDF library imaginable.
Add your documents as two-element lists `[docname,
[list_of_words_in_the_document]]` with `addDocument(docname,
list_of_words)`. Get a list of all the `[docname, similarity_score]` pairs relative
to a document by calling `similarities([list_of_words])`.
See the README for a usage example.
"""
import sys
import os
class tfidf:
def __init__(self):
self.weighted = False
self.documents = []
self.corpus_dict = {}
def addDocument(self, doc_name, list_of_words):
# building a dictionary
doc_dict = {}
for w in list_of_words:
doc_dict[w] = doc_dict.get(w, 0.) + 1.0
self.corpus_dict[w] = self.corpus_dict.get(w, 0.0) + 1.0
# normalizing the dictionary
length = float(len(list_of_words))
for k in doc_dict:
doc_dict[k] = doc_dict[k] / length
# add the normalized document to the corpus
self.documents.append([doc_name, doc_dict])
def similarities(self, list_of_words):
"""Returns a list of all the [docname, similarity_score] pairs relative to a
list of words."""
# building the query dictionary
query_dict = {}
for w in list_of_words:
query_dict[w] = query_dict.get(w, 0.0) + 1.0
# normalizing the query
length = float(len(list_of_words))
for k in query_dict:
query_dict[k] = query_dict[k] / length
# computing the list of similarities
sims = []
for doc in self.documents:
score = 0.0
doc_dict = doc[1]
for k in query_dict:
if doc_dict.has_key(k):
score += (query_dict[k] / self.corpus_dict[k]) + (doc_dict[k] /
self.corpus_dict[k])
sims.append([doc[0], score])
return sims
*IthasbeenalongtimesinceIwrotetheTFIDFtutorial(Part IandPart II)andasI
promissed,hereisthecontinuationofthetutorial.UnfortunatelyIhadnotimetofixthe
previoustutorialsforthenewerversionsofthescikit-learn (sklearn)packagenorto
answerallthequestions,butIhopetodothatinaclosefuture.
So,ontheprevioustutorialswelearnedhowadocumentcanbemodeledintheVector
Space,howtheTFIDFtransformationworksandhowtheTFIDFiscalculated,now
whatwearegoingtolearnishowtouseawellknownsimilaritymeasure(Cosine
Similarity)tocalculatethesimilaritybetweendifferentdocuments.
Letsbeginwiththedefinitionofthedotproductfortwovectors:
and
,where and arethecomponentsofthevector(featuresofthe
document,orTFIDFvaluesforeachwordofthedocumentinourexample)andthe is
thedimensionofthevectors:
Asyoucansee,thedefinitionofthedotproductisasimplemultiplicationofeach
componentfromthebothvectorsaddedtogether.Seeanexampleofadotproductfor
twovectorswith2dimensionseach(2D):
Thefirstthingyouprobablynoticedisthattheresultofadotproductbetweentwo
vectorsisntanothervectorbutasinglevalue,ascalar.
Thisisallverysimpleandeasytounderstand,butwhatisadotproduct?Whatisthe
intuitiveideabehindit?Whatdoesitmeantohaveadotproductofzero?To
understandit,weneedtounderstandwhatisthegeometricdefinitionofthedot
product:
Rearrangingtheequationtounderstanditbetterusingthecommutativeproperty,we
have:
So,whatistheterm
?Thistermistheprojectionofthevector intothevector
asshownontheimagebelow:
THEPROJECTIONOFTHEVECTORAINTOTHEVECTORB.BYWIKIPEDIA.
Now,whathappenswhenthevector isorthogonal(withanangleof90degrees)tothe
vector likeontheimagebelow?
TWOORTHOGONALVECTORS(WITH90DEGREESANGLE).
Therewillbenoadjacentsideonthetriangle,itwillbeequivalenttozero,the
term
willbezeroandtheresultingmultiplicationwiththemagnitudeofthe
vector willalsobezero.Nowyouknowthat,whenthedotproductbetweentwo
differentvectorsiszero,theyareorthogonaltoeachother(theyhaveanangleof90
degrees),thisisaveryneatwaytochecktheorthogonalityofdifferentvectors.Itisalso
importanttonotethatweareusing2Dexamples,butthemostamazingfactaboutitis
thatwecanalsocalculateanglesandsimilaritybetweenvectorsinhigherdimensional
spaces,andthatiswhymathletusseefarthantheobviousevenwhenwecantvisualize
orimaginewhatistheanglebetweentwovectorswithtwelvedimensionsforinstance.
Thecosinesimilaritybetweentwovectors(ortwodocumentsontheVectorSpace)isa
measurethatcalculatesthecosineoftheanglebetweenthem.Thismetricisa
measurementoforientationandnotmagnitude,itcanbeseenasacomparisonbetween
documentsonanormalizedspacebecausewerenottakingintotheconsiderationonly
themagnitudeofeachwordcount(tfidf)ofeachdocument,buttheanglebetweenthe
documents.Whatwehavetodotobuildthecosinesimilarityequationistosolvethe
equationofthedotproductforthe
:
Andthatisit,thisisthecosinesimilarityformula.CosineSimilaritywillgeneratea
metricthatsayshowrelatedaretwodocumentsbylookingattheangleinsteadof
magnitude,likeintheexamplesbelow:
THECOSINESIMILARITYVALUESFORDIFFERENTDOCUMENTS,1(SAME
DIRECTION),0(90DEG.),1(OPPOSITEDIRECTIONS).
Notethatevenifwehadavectorpointingtoapointfarfromanothervector,theystill
couldhaveansmallangleandthatisthecentralpointontheuseofCosineSimilarity,
themeasurementtendstoignorethehighertermcountondocuments.Supposewehave
adocumentwiththewordskyappearing200timesandanotherdocumentwiththe
wordskyappearing50,theEuclideandistancebetweenthemwillbehigherbutthe
anglewillstillbesmallbecausetheyarepointingtothesamedirection,whichiswhat
matterswhenwearecomparingdocuments.
NowthatwehaveaVectorSpaceModelofdocuments(likeontheimagebelow)
modeledasvectors(withTFIDFcounts)andalsohaveaformulatocalculatethe
similaritybetweendifferentdocumentsinthisspace,letsseenowhowwedoitin
practiceusingscikit-learn (sklearn).
VECTORSPACEMODEL
*InthistutorialImusingthePython2.7.5andScikitlearn0.14.1.
Thefirstthingweneedtodoistodefineoursetofexampledocuments:
documents = (
"The sky is blue",
"The sun is bright",
"The sun in the sky is bright",
"We can see the shining sun, the bright sun"
AndthenweinstantiatetheSklearnTFIDFVectorizerandtransformourdocuments
intotheTFIDFmatrix:
sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(documents)
tfidf_matrix.shape
11)
NowwehavetheTFIDFmatrix(tfidf_matrix)foreachdocument(thenumberofrows
ofthematrix)with11tfidfterms(thenumberofcolumnsfromthematrix),wecan
calculatetheCosineSimilaritybetweenthefirstdocument(Theskyisblue)witheach
oftheotherdocumentsoftheset:
sklearn.metrics.pairwise import cosine_similarity
cosine_similarity(tfidf_matrix[0:1], tfidf_matrix)
array([[ 1.
, 0.36651513, 0.52305744, 0.13448867]])
Thetfidf_matrix[0:1]istheScipyoperationtogetthefirstrowofthesparsematrixand
theresultingarrayistheCosineSimilaritybetweenthefirstdocumentwithall
documentsintheset.Notethatthefirstvalueofthearrayis1.0becauseitistheCosine
Similaritybetweenthefirstdocumentwithitself.Alsonotethatduetothepresenceof
similarwordsonthethirddocument(Thesunintheskyisbright),itachievedabetter
score.
Ifyouwant,youcanalsosolvetheCosineSimilarityfortheanglebetweenvectors:
Weonlyneedtoisolatetheangle( )andmovethe
The
isthesameastheinverseofthecosine(
totherighthandoftheequation:
).
Letsforinstance,checktheanglebetweenthefirstandthirddocuments:
import math
# This was already calculated on the previous step, so we just use the value
cos_sim = 0.52305744
angle_in_radians = math.acos(cos_sim)
math.degrees(angle_in_radians)
58.462437107432784
Andthatangleof~58.5istheanglebetweenthefirstandthethirddocumentofour
documentset.
Thatisit,Ihopeyoulikedthisthirdtutorial!