In [1]:
import os
TEXT_DIR = os.path.join(os.getcwd(), 'text/')

In [29]:
import os, os.path, codecs
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import decomposition

from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS
import numpy as np

In [30]:
dir_data = "text"
file_paths = [os.path.join(dir_data, fname) for fname in os.listdir(dir_data) if fname.endswith(".txt") ]
documents = [codecs.open(file_path, 'r', encoding="utf8", errors='ignore').read() for file_path in file_paths ]

In [31]:
tfidf = TfidfVectorizer(stop_words=ENGLISH_STOP_WORDS, lowercase=True, strip_accents="unicode", use_idf=True, norm="l2", min_df = 5) 
A = tfidf.fit_transform(documents)

In [32]:
A


Out[32]:
<119x13235 sparse matrix of type '<class 'numpy.float64'>'
	with 431707 stored elements in Compressed Sparse Row format>

In [33]:
num_terms = len(tfidf.vocabulary_)
terms = [""] * num_terms
for term in tfidf.vocabulary_.keys():
    terms[ tfidf.vocabulary_[term] ] = term

In [34]:
model = decomposition.NMF(init="nndsvd", n_components=30, max_iter=200)
W = model.fit_transform(A)
H = model.components_

In [35]:
for topic_index in range( H.shape[0] ):
    top_indices = np.argsort( H[topic_index,:] )[::-1][0:10]
    term_ranking = [terms[i] for i in top_indices]
    print("Topic %d: %s" % ( topic_index, ", ".join( term_ranking ) ))


Topic 0: et, room, paris, apartment, la, bed, le, kitchen, living, metro
Topic 1: apartment, paris, bed, floor, kitchen, located, room, bedroom, et, bathroom
Topic 2: paris, apartment, une, room, et, avec, kitchen, est, chambre, la
Topic 3: montmartre, sacre, coeur, abbesses, joffrin, jules, du, 12, rouge, moulin
Topic 4: mouffetard, pantheon, luxembourg, latin, notre, dame, sorbonne, paris, rue, monge
Topic 5: chaumont, buttes, villette, canal, ourcq, la, parc, et, du, des
Topic 6: batignolles, monceau, champs, elysees, des, ternes, montmartre, brochant, arc, triomphe
Topic 7: passy, trocadero, eiffel, tower, auteuil, boulogne, 16th, champs, elysees, garros
Topic 8: martin, canal, saint, gare, republique, du, st, nord, est, bars
Topic 9: montorgueil, sentier, paris, rue, louvre, halles, opera, les, reaumur, heart
Topic 10: alesia, montparnasse, denfert, daguerre, rochereau, montsouris, et, pernety, 14th, rue
Topic 11: marais, vosges, temple, des, metiers, rue, le, republique, du, place
Topic 12: et, vincennes, daumesnil, bastille, nation, bercy, la, lyon, metro, gare
Topic 13: cailles, italie, et, la, butte, mouffetard, gobelins, tolbiac, place, quartier
Topic 14: et, metro, la, pantin, une, minutes, hoche, room, avec, paris
Topic 15: montmartre, martyrs, pigalle, opera, moulin, rue, rouge, 9th, cadet, grands
Topic 16: gambetta, lachaise, pere, et, belleville, menilmontant, nation, une, metro, la
Topic 17: bastille, oberkampf, republique, lachaise, pere, marais, place, voltaire, bars, parmentier
Topic 18: eiffel, invalides, tower, cler, rue, mars, militaire, des, la, ecole
Topic 19: louvre, paris, honore, royal, tuileries, palais, rue, vendome, les, place
Topic 20: et, une, la, avec, est, le, paris, appartement, apartment, dans
Topic 21: marais, paris, saint, vosges, louis, room, notre, dame, des, paul
Topic 22: montmartre, et, sacre, du, flat, coeur, gare, barbes, dormoy, minutes
Topic 23: champs, elysees, monceau, avenue, paris, des, honore, saint, arc, madeleine
Topic 24: une, et, avec, lit, bed, double, chambre, appartement, walk, en
Topic 25: saint, germain, des, luxembourg, pres, odeon, du, sulpice, st, room
Topic 26: paris, apartment, minutes, une, la, vous, studio, bed, est, flat
Topic 27: bastille, lachaise, pere, nation, place, voltaire, 11th, marais, oberkampf, la
Topic 28: eiffel, tower, convention, 15th, motte, metro, tour, mars, 10, la
Topic 29: et, flat, la, une, bed, living, place, room, avec, machine

As you can see we need to do more cleaning - it is clear from above that there are a number of French stop words there. However some of the topics are interesting, we see words like montmartre, bastille, eiffel etc all included - which is what we would expect naively in Parisian locations.

Text Analysis

We'll do a more sophisicated model by using the new LDA functionality in Scikit-Learn


In [45]:
n_samples = 20000
n_features = 1000
n_topics = 50
n_top_words = 20
from time import time
def print_top_words(model, feature_names, n_top_words):
    for topic_idx, topic in enumerate(model.components_):
        print("Topic #%d:" % topic_idx)
        print(" ".join([feature_names[i]
                        for i in topic.argsort()[:-n_top_words - 1:-1]]))
    print()

tfidf_vectorizer = TfidfVectorizer(max_df=0.80, min_df=5, #max_features=n_features,
                                   stop_words='english')
# Use tf (raw term count) features for LDA.
print("Extracting tf features for LDA...")
tf_vectorizer = CountVectorizer(max_df=0.80, min_df=2, max_features=n_features,
                                stop_words='english')
t0 = time()
tf = tf_vectorizer.fit_transform(documents)
print("done in %0.3fs." % (time() - t0))

print("Fitting LDA models with tf features, n_samples=%d and n_features=%d..."
      % (n_samples, n_features))
lda = decomposition.LatentDirichletAllocation(n_topics=n_topics, max_iter=5,
                                learning_method='online', learning_offset=50.,
                                random_state=0)
t0 = time()
lda.fit(tf)
print("done in %0.3fs." % (time() - t0))

print("\nTopics in LDA model:")
tf_feature_names = tf_vectorizer.get_feature_names()
print_top_words(lda, tf_feature_names, n_top_words)


Extracting tf features for LDA...
done in 6.209s.
Fitting LDA models with tf features, n_samples=20000 and n_features=1000...
done in 1.687s.

Topics in LDA model:
Topic #0:
lachaise belleville père gambetta ménilmontant buttes chaumont nation jourdain cemetery oberkampf 20th pere rouge 26 république menilmontant tram populaire dumas
Topic #1:
montorgueil beaubourg luxembourg mouffetard arts tuileries pont république honoré pantheon vosges royal temple métiers prés madeleine martin paul projector 17th
Topic #2:
butte cailles italie madeleine rochereau rouge pigalle monceau luxembourg abbesses 16th gobelins mouffetard etoile trocadero tramway elysée printemps passy 13th
Topic #3:
pigalle rouge moulin martyrs 9th boulevards abbesses printemps georges garnier sacre anvers butte cadet department martin clichy blanche madeleine 18th
Topic #4:
chaumont buttes lachaise république oberkampf belleville père villette martin nation voltaire ourcq 11th republique parmentier vosges charonne pere ménilmontant musique
Topic #5:
vosges denfert rochereau louis paul 14th daguerre ile montsouris république lachaise luxembourg river pernety oberkampf alesia beaubourg island père picasso
Topic #6:
vosges arts picasso république beaubourg temple paul rochereau métiers denfert bretagne moulin louis martin republique 14th pernety 17th rouge 18th
Topic #7:
montorgueil sentier boulevards royal beaubourg buttes lachaise garnier belleville nouvelle chaumont louis denis père bourse printemps etienne vosges réaumur tuileries
Topic #8:
vosges temple arts picasso beaubourg république bretagne métiers rouges republique rambuteau paul georges 17th oldest 18th river poutres antique fashionable
Topic #9:
batignolles monceau ternes etoile clichy 17th brochant villiers pigalle maillot guy martin pereire rouge moulin rome levis 17ème poncelet wagram
Topic #10:
versailles mars 15th motte convention invalides tram picquet georges 15ème nation tramway champ expositions beaugrenelle montorgueil grenelle lachaise vaugirard père
Topic #11:
invalides lachaise oberkampf père mars république nation prés river vosges belleville cler martin rouge orsay chaumont moulin luxembourg buttes militaire
Topic #12:
trocadero passy trocadéro 16th boulogne victor auteuil hugo garros muette etoile roland 16 ranelagh 16ème river 22 52 élysées versailles
Topic #13:
lachaise père chaumont buttes belleville martin rouge ménilmontant nation république gambetta abbesses pigalle jourdain cemetery oberkampf joffrin 18th republique pere
Topic #14:
lachaise père luxembourg belleville prés buttes gambetta ménilmontant rochereau chaumont montsouris daguerre oberkampf denfert république nation alésia alesia jourdain cailles
Topic #15:
trocadéro passy 16th trocadero hugo boulogne victor auteuil luxembourg rochereau etoile 8th royal faubourg nation denfert monceau honoré tuileries 16ème
Topic #16:
trocadero passy 16th trocadéro victor boulogne hugo muette auteuil martin arts garros river etoile 16 vosges temple république rouge beaubourg
Topic #17:
tuileries royal batignolles prés honoré butte 17th cailles monceau river italie clichy pont luxembourg vendôme montorgueil arts orsay luxurious rivoli
Topic #18:
buttes chaumont villette belleville ourcq martin jourdain bassin crimée sciences stalingrad république ourq jaurès pyrénées 104 musique tramway butte 26
Topic #19:
montorgueil batignolles monceau rouge abbesses pigalle moulin butte clichy 18th 17th sentier louis etoile printemps joffrin river villiers luxembourg beaubourg
Topic #20:
buttes beaubourg batignolles pigalle chaumont martin rouge 17th denfert belleville villette montorgueil vosges temple georges ourcq bretagne republique arts picasso
Topic #21:
montorgueil royal tuileries sentier honoré beaubourg garnier boulevards marcel rivoli denis etienne vendôme bourse river strasbourg 18th nouvelle 17th réaumur
Topic #22:
luxembourg mouffetard sorbonne prés plantes panthéon pantheon river sulpice nation pres batignolles république monge louis ile denfert oberkampf vincennes monceau
Topic #23:
buttes chaumont pigalle villette moulin invalides belleville martin luxembourg abbesses jules prés lachaise rouge butte ourcq lamarck sacre mars père
Topic #24:
nation vincennes bercy daumesnil aligre reuilly 12th diderot verte coulée république promenade tramway ledru antoine rollin faubourg vosges tram lachaise
Topic #25:
passy trocadéro boulogne 16th trocadero lachaise auteuil pigalle hugo rouge abbesses père garros moulin roland etoile river ranelagh nation vosges
Topic #26:
luxembourg prés denfert rochereau daguerre 14th royal pres montorgueil tuileries odeon odéon sulpice montsouris alesia monceau alésia 17th pernety honoré
Topic #27:
luxembourg prés pres sorbonne odeon odéon sulpice river pantheon mouffetard panthéon arts flore 17th orsay pont louis trocadéro andré plantes
Topic #28:
louis paul ile vosges river island beaubourg 17th cathedral picasso pont marie 18th georges île rivoli rambuteau layout dream martin
Topic #29:
martin république republique 10th denis boulevards belleville goncourt strasbourg jacques bonsergent faubourg louis nouvelle fabien colonel montorgueil republic beaubourg eurostar
Topic #30:
batignolles ternes clichy martin 17th monceau etoile rouge pigalle moulin république maillot nation bercy guy brochant abbesses villiers vincennes rome
Topic #31:
rouge pigalle martin moulin lachaise mouffetard luxembourg république plantes boulevards oberkampf royal abbesses père sacre 18th pantheon panthéon joffrin martyrs
Topic #32:
mars 15th versailles motte grenelle convention invalides beaugrenelle buttes tramway river lachaise chaumont 15ème commercial piquet expositions trocadero brassens vaugirard
Topic #33:
denfert rochereau daguerre montsouris 14th alesia pernety alésia plaisance luxembourg tram tramway universitaire 38 versailles théâtres 62 prés t3 artists
Topic #34:
martin vincennes nation république daumesnil louis bercy 10th diderot reuilly republique aligre buttes 12th denis faubourg belleville boulevards chaumont verte
Topic #35:
prés luxembourg pres sulpice odéon odeon pont arts river flore orsay rennes 17th ile invalides midi 18th andré prestigious antique
Topic #36:
lachaise père oberkampf nation république belleville gambetta ménilmontant 11th cemetery voltaire pere charonne republique martin parmentier menilmontant vosges cimetière 20th
Topic #37:
paul louis vosges river ile trocadero 16th beaubourg montorgueil mars passy invalides nation trocadéro versailles 15th island 17th picasso boulogne
Topic #38:
lachaise oberkampf nation père république 11th charonne belleville martin republique voltaire parmentier pigalle rouge ménilmontant moulin abbesses cemetery goncourt 11ème
Topic #39:
monceau madeleine batignolles 8th etoile élysées montaigne honoré faubourg ternes printemps triangle clichy luxurious george villiers elysée prestigious palace tuileries
Topic #40:
montorgueil vosges royal père oberkampf abbesses pigalle 18th beaubourg lachaise louis république moulin nation rouge boulevards sentier paul martin jules
Topic #41:
lachaise père nation belleville gambetta versailles mars 15th buttes ménilmontant chaumont invalides tramway convention champ expositions tram cemetery motte picquet
Topic #42:
batignolles lachaise père oberkampf nation république martin etoile 11th monceau charonne ternes voltaire ménilmontant parmentier belleville republique chaumont royal 11ème
Topic #43:
martin pigalle abbesses moulin rouge république joffrin versailles sacre boulevards denfert butte jules mars belleville anvers chapelle republique 10th 15th
Topic #44:
pigalle rouge moulin buttes luxembourg abbesses mouffetard chaumont butte plantes 9th versailles italie panthéon vincennes martin prés pantheon nation garnier
Topic #45:
prés luxembourg 15th moulin batignolles abbesses rouge versailles pigalle jules tertre royal champ mars sacre beaugrenelle river 15ème printer convention
Topic #46:
invalides mars versailles 15th convention motte champ orsay grenelle beaugrenelle militaire river prés ecole expositions cler picquet tramway 15ème brassens
Topic #47:
luxembourg mouffetard panthéon pantheon plantes sorbonne italie cailles butte river monge gobelins cathedral louis prés ile royal port 13th austerlitz
Topic #48:
abbesses rouge moulin joffrin jules pigalle sacre butte 18th lamarck marcadet tertre caulaincourt chapelle clignancourt dormoy marx puces clichy simplon
Topic #49:
martin république republique denis invalides 10th boulevards versailles batignolles montorgueil goncourt beaubourg mars nation buttes bonsergent vosges belleville jacques chaumont


In [ ]: