aitech-eks-pub/cw/03b_tfidf_newsgroup.ipynb

13 KiB

Logo 1

Ekstrakcja informacji

3. tfidf (2) [ćwiczenia]

Jakub Pokrywka (2021)

Logo 2

Importy

import numpy as np
import sklearn.metrics

from sklearn.datasets import fetch_20newsgroups

from sklearn.feature_extraction.text import TfidfVectorizer

Zbiór danych

newsgroups = fetch_20newsgroups()['data']
len(newsgroups)
11314
print(newsgroups[0])
From: lerxst@wam.umd.edu (where's my thing)
Subject: WHAT car is this!?
Nntp-Posting-Host: rac3.wam.umd.edu
Organization: University of Maryland, College Park
Lines: 15

 I was wondering if anyone out there could enlighten me on this car I saw
the other day. It was a 2-door sports car, looked to be from the late 60s/
early 70s. It was called a Bricklin. The doors were really small. In addition,
the front bumper was separate from the rest of the body. This is 
all I know. If anyone can tellme a model name, engine specs, years
of production, where this car is made, history, or whatever info you
have on this funky looking car, please e-mail.

Thanks,
- IL
   ---- brought to you by your neighborhood Lerxst ----





Naiwne przeszukiwanie

all_documents = list() 
for document in newsgroups:
    if 'car' in document:
        all_documents.append(document)
print(all_documents[0])
From: lerxst@wam.umd.edu (where's my thing)
Subject: WHAT car is this!?
Nntp-Posting-Host: rac3.wam.umd.edu
Organization: University of Maryland, College Park
Lines: 15

 I was wondering if anyone out there could enlighten me on this car I saw
the other day. It was a 2-door sports car, looked to be from the late 60s/
early 70s. It was called a Bricklin. The doors were really small. In addition,
the front bumper was separate from the rest of the body. This is 
all I know. If anyone can tellme a model name, engine specs, years
of production, where this car is made, history, or whatever info you
have on this funky looking car, please e-mail.

Thanks,
- IL
   ---- brought to you by your neighborhood Lerxst ----





print(all_documents[1])
From: guykuo@carson.u.washington.edu (Guy Kuo)
Subject: SI Clock Poll - Final Call
Summary: Final call for SI clock reports
Keywords: SI,acceleration,clock,upgrade
Article-I.D.: shelley.1qvfo9INNc3s
Organization: University of Washington
Lines: 11
NNTP-Posting-Host: carson.u.washington.edu

A fair number of brave souls who upgraded their SI clock oscillator have
shared their experiences for this poll. Please send a brief message detailing
your experiences with the procedure. Top speed attained, CPU rated speed,
add on cards and adapters, heat sinks, hour of usage per day, floppy disk
functionality with 800 and 1.4 m floppies are especially requested.

I will be summarizing in the next two days, so please add to the network
knowledge base if you have done the clock upgrade and haven't answered this
poll. Thanks.

Guy Kuo <guykuo@u.washington.edu>

jakie są problemy z takim podejściem?

TFIDF i odległość cosinusowa- gotowe biblioteki

vectorizer = TfidfVectorizer()
#vectorizer = TfidfVectorizer(use_idf = False, ngram_range=(1,2))
document_vectors = vectorizer.fit_transform(newsgroups)
document_vectors
<11314x130107 sparse matrix of type '<class 'numpy.float64'>'
	with 1787565 stored elements in Compressed Sparse Row format>
document_vectors[0]
<1x130107 sparse matrix of type '<class 'numpy.float64'>'
	with 89 stored elements in Compressed Sparse Row format>
document_vectors[0].todense()
matrix([[0., 0., 0., ..., 0., 0., 0.]])
document_vectors[0:4].todense()
matrix([[0., 0., 0., ..., 0., 0., 0.],
        [0., 0., 0., ..., 0., 0., 0.],
        [0., 0., 0., ..., 0., 0., 0.],
        [0., 0., 0., ..., 0., 0., 0.]])
query_str = 'speed'
#query_str = 'speed car'
#query_str = 'spider man'
query_vector = vectorizer.transform([query_str])
document_vectors
<11314x130107 sparse matrix of type '<class 'numpy.float64'>'
	with 1787565 stored elements in Compressed Sparse Row format>
query_vector
<1x130107 sparse matrix of type '<class 'numpy.float64'>'
	with 1 stored elements in Compressed Sparse Row format>
similarities = sklearn.metrics.pairwise.cosine_similarity(query_vector,document_vectors)
np.sort(similarities)[0][-4:]
array([0.26949927, 0.3491801 , 0.44292083, 0.47784165])
similarities.argsort()[0][-4:]
array([4517, 5509, 2116, 9921])
for i in range (1,5):
    print(newsgroups[similarities.argsort()[0][-i]])
    print(np.sort(similarities)[0,-i])
    print('-'*100)
    print('-'*100)
    print('-'*100)

Zadanie domowe

  • Wybrać zbiór tekstowy, który ma conajmniej 10000 dokumentów (inny niż w tym przykładzie).

  • Na jego podstawie stworzyć wyszukiwarkę bazującą na OKAPI BM25, tzn. system który dla podanej frazy podaje kilka (5-10) posortowanych najbardziej pasujących dokumentów razem ze scorami. Należy wypisywać też ilość zwracanych dokumentów, czyli takich z niezerowym scorem. Można korzystać z gotowych bibliotek do wektoryzacji dokumentów, należy jednak samemu zaimplementować OKAPI BM25.

  • Znaleźć frazę (query), dla której wynik nie jest satysfakcjonujący.

  • Poprawić wyszukiwarkę (np. poprzez zmianę preprocessingu tekstu, wektoryzer, zmianę parametrów algorytmu rankującego lub sam algorytm) tak, żeby zwracała satysfakcjonujące wyniki dla poprzedniej frazy. Należy zrobić inną zmianę niż w tym przykładzie, tylko wymyślić coś własnego.

  • prezentować pracę na następnych zajęciach (14.04) odpowiadając na pytania:

  • jak wygląda zbiór i system wyszukiwania przed zmianami

  • dla jakiej frazy wyniki są niesatysfakcjonujące (pokazać wyniki)

  • jakie zmiany zostały naniesione

  • jak wyglądają wyniki wyszukiwania po zmianach

  • jak zmiany wpłynęły na wyniki (1-2 zdania)

    Prezentacja powinna być maksymalnie prosta i trwać maksymalnie 2-3 minuty. punktów do zdobycia: 60