Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Sep 23, 2015

Topic Analysis In Depth - Croatia Travel Blogs

I'm headed to Croatia soon, so I decided to try another run at topic analysis from more than a cursory look. One of the challenges I've had with various topic analyses was validating the result set. Recently I've discovered LDAVis which does just that for a topic analysis. I won't go into LDA too much here, but Ted Underwood does *the* best job at explaining LDA in an intuitive way. LDAVis provides the means to discover conditions of your topic through the visual relation to other topics, how distinct topics are from one another, and term frequency/saliency within topics. Here I'll walk through how I used the tool to execute many different topic extraction/data cleaning runs to reveal interesting insights into Croatian travel.

The dataset includes blogs scrapped from travelblog.org and travelpod.com where I included information from the body and title. I have this dataset locally on my computer in ElasticSearch, which includes 1500 blogs on Croatia alone. ElasticSearch isn't really necessary, for the analysis itself, but it was convenient for document storage, term discovery, and blog review. Below is a sample screenshot from my "Croatian" version using a custom search tool. You can see that I searched "organ" which showed up in one of the major topics, and that struck me as odd. It turns out that there is a pipe organ in the city of Zadar called Sea Organ. (described here, 2nd paragraph from the bottom). It plays music by way of sea waves underneath a large set of marble steps.


If you looked at that last blog, that is a typical representation of a good travel blog: descriptive, narrative, lots of pictures, and focused on a distinct region. It's important to note that these blogs are mostly journal-style catalogs, not 'Top 10' posts. The compelling notion is that, theoretically, whatever you find in this data are real experiences that people have had. As you can tell, I'm a fan of this dataset, but it can be pretty messy to analyze. Some things I've had to account for:

  • difficult to filter HTML (even using BeautifulSoup for the main post of the body)
  • only filtering english blogs (using a package called LangId)
  • removing stop words ('a', 'the', 'an'....). I used a much more expansive list than the out of the box NLTK one.
  • removed people names. more on this later.
  • remove words that appear infrequently

Before diving into the topic analysis, a great way to discover some features (and bad data) is by looking at some different n-grams. Basically, what are the most common single words, word pairs, and words that appear in 3's.
Popular Unigrams (starting with most popular)
  • day
  • town
  • time
  • city
  • croatia
  • water
  • dubrovnik
  • people
  • split
  • good
  • bus
  • night
  • boat
  • island
  • walk
  • beautiful
  • well
  • small
  • great
  • walked
  • place
  • dinner
  • will
  • bit
  • park
  • sea
  • nice
  • trip
  • beach
  • decided
  • going
  • morning
  • tour
  • croatian
  • lunch
  • zagreb
  • today
  • hotel
  • road
  • headed
  • didn
  • find
  • left
  • long
  • hours
  • restaurant
  • walls
  • arrived
  • area
  • hour
  • car
  • local
  • couple
  • top
  • hvar
  • pretty
  • side
  • days
  • wine
  • walking
  • early
  • lovely
  • apartment
  • coast
  • lot
  • ferry
  • room
  • lakes
  • food
  • breakfast
  • head
  • big
  • ve
  • view
  • palace
  • amazing
  • group
  • ride
  • pm
  • streets
  • sun
  • don
  • lots
  • minutes
  • bar
  • best
  • started
  • stopped
  • main
  • set
  • called
  • full
  • large
  • views
  • finally
  • train
  • adriatic
  • tomorrow
  • told
  • swim
Popular Bigrams
  • national park
  • city walls
  • ice cream
  • plitvice lakes
  • adriatic sea
  • diocletian palace
  • bus station
  • cable car
  • game thrones
  • walking tour
  • walked town
  • walk town
  • stari grad
  • years ago
  • early morning
  • crystal clear
  • couple hours
  • tour guide
  • walled city
  • cruise ships
  • bell tower
  • half hour
  • train station
  • hvar island
  • bus ride
  • marco polo
  • cruise ship
  • long time
  • small town
  • hvar town
  • main square
  • day dubrovnik
  • island hvar
  • full day
  • narrow streets
  • decided head
  • pretty good
  • town dubrovnik
  • dalmatian coast
  • minute walk
  • olive oil
  • plitvice national
  • split croatia
  • unesco heritage
  • lakes national
  • rest day
  • bosnia herzegovina
  • day split
  • day trip
  • decided walk
  • heritage site
  • boat ride
  • city dubrovnik
  • walk city
  • upper town
  • white wine
  • arrived dubrovnik
  • broken relationships
  • caught bus
  • dubrovnik croatia
  • great day
  • spent time
  • early night
  • long day
  • top hill
  • well worth
  • headed town
  • main street
  • museum broken
  • people watching
  • rental car
  • blue water
  • couple days
  • grocery store
  • red wine
  • roman emperor
  • tour group
  • beautiful city
  • good time
  • shops restaurants
  • top deck
  • air conditioning
  • clear water
  • sail croatia
  • side road
  • blue cave
  • day day
  • emperor diocletian
  • views city
  • amazing views
  • beautiful place
  • glass wine
  • great time
  • pile gate
  • upper lakes
  • bus town
  • day croatia
  • island brac
  • lokrum island
  • side island
Popular Trigrams
  • lakes national park
  • plitvice national park
  • plitvice lakes national
  • museum broken relationships
  • unesco heritage site
  • krka national park
  • roman emperor diocletian
  • crystal clear water
  • walk city walls
  • clear blue water
  • water crystal clear
  • game thrones filmed
  • marco polo born
  • walking tour town
  • bad blue boys
  • cable car top
  • main bus station
  • second largest city
  • zagreb capital croatia
  • hour bus ride
  • largest city croatia
  • caught local bus
  • good nights sleep
  • st mark church
  • crystal clear waters
  • hula hula bar
  • national park croatia
  • town stari grad
  • walked city walls
  • white water rafting
  • austro hungarian empire
  • built roman emperor
  • cruise ship passengers
  • decided head apartment
  • eating ice cream
  • ice cream shop
  • mljet national park
  • national park plitvice
  • spent couple hours
  • town hvar island

Here is the simple source code
def ngrams ():

    corpus = ''
    for blogtext in getblogs ():
        corpus += blogtext

    stops = longstopwords()

    prime_words = [word for word in utils.simple_preprocess(corpus) if word.lower() not in stops]

    bigram_measures = nltk.collocations.BigramAssocMeasures()
    trigram_measures = nltk.collocations.TrigramAssocMeasures()

    finder = BigramCollocationFinder.from_words(prime_words)
    finderII = TrigramCollocationFinder.from_words(prime_words)

    # only bigrams that appear 3+ times
    finder.apply_freq_filter(3)
    finderII.apply_freq_filter(3)

    print "TOP UNIGRAMS:"
    for t in nltk.FreqDist(prime_words).most_common(100):
        print '<li>' + t[0] + '</li>'

    print '-----------------'

    print "TOP BIGRAMS:"
    for bigram in finder.score_ngrams(bigram_measures.raw_freq)[:100]:
        print '<li>' + " ".join(bigram[0]) + '</li>'

    print '-----------------'

    print "TOP TRIGAMS:"
    for trigram in finderII.score_ngrams(trigram_measures.raw_freq)[:40]:
        print '<li>' + " ".join(trigram[0]) + '</li>'

You can see from the code that n-grams can be a simple and powerful way to do some discovery on your dataset. If you take a look you can see 'Game Thrones' in the Bigrams list. 'Of' was filtered out in stop words, but a good deal of filming for the Game of Thrones takes place in Croatia. Numerous national parks and towns are in these lists as well. Searching these terms into my search engine yields some interesting discoveries and I've already discovered an activity of interest: white water rafting.

Below is a sample of LDAVis UI for topic analysis. I debated whether I should write this post in IPython (where I did the LDAVis analysis). Ultimately, I like having my posts in a single place. But IPython (now Jupyter)is a convenient way for analysts to share their work. You can now run these notebooks off of GitHub , and I stuck the best of my data runs and data in this Jupyter Notebook. The process of getting at this result, what this interactive chart says, and the process of getting there are worth some note. As you can see there isn't as much distinction between the topics as I would like, as noted by the overlap in topic circles. However, the results still provide a good bit of insight. Topic #2 contains 'zadar, water, beach, sea, organ' as some of the most frequent+salient terms. Basically, the word 'organ' doesn't appear much in the corpus but when it does it belongs exclusively to this topic. When the lambda slider is set to .5, we see a good mix of popular words vs strong words. Lambda is essentially a balance of frequency and saliency that you can control. Some topics were awash in terms in ambiguous terms, but manipulating Lamba can provide clarity. Topic #2 is what gave me pause to investigate "organ" and discover the Sea Organ in Zadar.

I used Gensim again to perform the LDA analysis. This library takes lengths to scale and be performant, which is important so I don't have to switch to a new library to perform large analyses. Here is the sample code used to produce my corpus, dictionary, and LDA. The general process is as follows:

  1. Get blog text from ElasticSearch
  2. Get an expansive list of firstnames and stopwords to filter out
  3. Only include terms that appear 4 or more times
  4. Generate Dictionary, Corpus, and LDA model
def Dictionary_Corpus_LDA_Withoutnames():
    
    #get array of blogs stored in ElasticSearch
    documents = getblogs ()

    #get a list of first names to filter out (Gathered from US Census + half a dozen foreign names + nicknames)
    firsts = getfirstnames ()

    #get a long list of stopwords to filter out
    stops = longstopwords ()
   
    words_to_exclude = stops + firsts.keys()

    logger.info("Removing stop words and names")

    documents = [[word for word in utils.simple_preprocess (doc) if word not in words_to_exclude]
              for doc in documents]

    logger.info("Removing words that only occur once")

    token_frequency = defaultdict(int)
    for doc in documents:
        for token in doc:
            token_frequency[token] += 1

    #remove words that occur 3 or fewer times
    documents = [ [token for token in doc if token_frequency[token] > 3]
                for doc in documents  ]

    logger.info("Saving Corpus and Dictionary")

    dictionary = corpora.Dictionary(documents)
    dictionary.save('CroatiaTravelBlogs_NoNames.dict')
    corpus = [dictionary.doc2bow(doc) for doc in documents]
    corpora.MmCorpus.serialize('CroatiaTravelBlogs_NoNames.mm', corpus)

    topics = 50
    passes = 100
    lda = models.LdaModel (corpus, id2word=dictionary, num_topics=topics, passes=passes)
    lda.print_topics(topics)
    lda.save("Croatia_Topic_No_Names-{0}_Passes-{1}.lda".format(topics, passes))

Take a look at a few more topics listed in the notebook. Set the Lamba slider on the right graph to .5 and choose a topic number on the left graph. For example Topic #4 is a bit confusing. Toggle the Lambda down to .33 and you'll get 'bus', 'hostel', 'squirt' (nickname I should have filtered)..'cheaper' and 'backpacks'. I think this topic contains blog for budget travelers. Tagging these blogs for would-be travelers could be very compelling feature to the search engine. I'm unclear on Topic #1 and #3. Topic #5 is about Dubrovnik. Topic #6 is relates to the popular islands just off the coast. Topic #7 is about the history and architecture. Topic #8 is about camping and motorhomes. Topic #9 is about some of the national parks. I think you get the idea. To reiterate, I often move back and forth from the LDAVis to my search to check out terms in context of the blog. That's how I knew that I missed a nickname in Topic #4 since it's always the same author and the first few results were about their son.

I didn't go too indepth on LDA here, but its worth reading the blog by Ted Underwood mentioned above. The intro to LDA written by one of the original authors, David Blei, is here. The paper behind LDAVis is interesting too. he website is best to get a better intuition for their methodology of LDA analysis. Finally, if I were to take the exercise further academically, I'd improve LDA specifically for blogs by adding another dimension for author and custom treatment for title.

Jul 24, 2015

Wanderight, a technical journey

While I've been vague about my idea and project, things are coming into focus. In this time of entrepreneurial exploration I've had time to get reacquainted with developing software. Every technology I've employed so far is new to me: operating system, cloud hosting platform, programing language, text based search platform... But like most other software devs I enjoy learning new things. The pragmatist in me knows that many of these tools are the best for the job. Python is good at manipulating text, data analysis, and building things quick. Elasticsearch is great at encapsulating the complexity and learning curve of running Lucene or Solr. Linux is the best platform to run and operate Python and Elasticsearch. Azure is the best platform for giving me free hosting which is awesome at keeping my burn rate low.

I'd like focus on the technology aspects of what I'm working on from the perspective of a beginner on many fronts. But I also have the belief that I'll be able to do somethings with technologies that I barely understand as of yet. That's where the fun comes in. Without explaining the product and the opportunity/market...yada yada, I'll focus on the operational learnings and a bit about the motive for the focus. So first, a bit of a primer: I believe that many textual sources have a wealth of information that is mostly untapped. If you think Google News can aggregate well and Google Search can find things well, I'd hope to do something similar with travel. As a person that's traveled and explored in over a dozen countries, I hate the over-sponsored, highly-advertised world of online travel. There are people out there giving authentic information on travel blogs, forums... you just need to tease it out. Make the content easy to find and relatable to the end user, and be diligent about spotting and identifying that which is 'sponsored'. The easiest way I could think to start is with narrative travel blogs. Which brings me to my tech. Parse, clean, and analyze travel blogs. What I eventually want to have is a site that will serve up authentic travel information to the international planning traveler. As far as I can tell, there are 3 distinct categories.

  1. Build a 'basic' search engine based on a semi-currated content feed. By semi-currated I mean that I'll only be putting in content that I presume isn't sponsored. Some of that authentic content is apparent, some of it is tricky, so start with the obvious.
  2. Discover your data set. Yay data science. Understand key characteristics about it. Get a sense for what is 'good' and make and define those as hypotheses in your product journey. Clean your dataset. Don't even allow things in that are in a foreign language of a certain content length and aren't based in the region of focus. Not to mention that cleaning and data janitorial work that needs to be done before it can be searched. Luckily Elasticsearch does alot of that lifting for you: stemming, stopwords... Obviously I need to pick out the main content, key in on meta data while, and clean html while parsing (covered in step 1).
  3. Generally speaking, find more intelligent ways to serve content up to the user. Things like region discovery through topic analysis. Or categorization to filter content for a traveler archtype. Summarize long posts to make searching faster. Extract places to enhance your search and discover capability. Recommend blogs to read based on blogs of interest. I believe that information extraction, natural language processing, and machine learning have become much more accessible to the non-academic. That being said, this step isn't plug and play but there is wealth of books, platforms, and sample code to get this autodidact well on my way. If nothing else, this is waaaaay better than going back to school for a degree in what I can learn with the power of the internets.

Now the details and my reflection 6 weeks in with so much new technology. To address step 1) I choose 2 key technologies:Python and Elasticsearch. Python for its text parsing prowess and Elasticsearch for the heavy lifting of Lucene. BeautifulSoup is an excellent library for finding information in blogs and scraping out what you want. Learning Python was fairly straight forward. The 2 languages I'm most familiar with are C# and Javascript. Python is alot more like Javascript. The key difference building software this time around is that I have a veteran (read cantankerous) view on technology. Everything in its place. I used to get wrapped around the axle with proper coding technique, architecture, scalability...but that doesn't have much place here. Those things matter most when you have different problems to solve than trying to see if other people give a shit about what you're building. This graphic is telling of the different development mindsets. My nature is to be a 'Settler', but I've longed to be a 'Pioneer'. Which basically means now I'm a giant fucking hack. You could drive a mack truck through my hacks. It's fun and awesome. But I think the key difference is (and this is a big *if*) I would know how to scale things when the time comes. Whether I'd need to burn it to the ground and rewrite or build up what's there, I can figure it out because I have in the past. That's a comfort that not many others have and I consider it a key personal asset.

A long time ago I worked with Lucene. Like 10 years ago. What Elasticsearch has done for text search since that time is awesome. Getting going out of the box is easy. The tutorials and the amount of StackOverflow help make the ease of adoption so much less intimidating than trying to learn what TF-IDF is when you just want to get shit working. Get it working first, dive deep later. Elasticsearch is awesome at that. I don't need to care that it runs on 5 shards or that I need to use a Snowball analyzer for proper stemming. I can get going and find lots of information on the internets when I run into issues. That being said the run-into-walls approach only works so long. Eventually you need to dive deep, like yesterday. I spent the at least half the day understanding how custom query scoring works, how to avoid using TF-IDF on certain fields that are short, and looking at very complex 'explain' query chains. I went deep into the rabbit hole that day my friends, but my search is so much better. Being able to find terms in a statistically relevant way just gets your foot in the door. Boosting blogs that are more recently, longer in length, and contain more pictures really makes a difference in the quality of your first few results.

For hosting I originally started with AWS. Every major cloud platform has some sort of offer for startups. AWS really raises the bar for getting anything free out of them. Like for $1k/year, I'd need to take an online MIT course on entrepreneurship. No thanks. I bought the professor's book on audio, time better spent. Azure has a BizSpark program that lowers the bar to entry and is awesome for people like me who are bootstrapping an MVP. 2 weeks after I applied, I got in. I've got a basic Web App hosting a static single page that uses Angular and other javascript goodies to to talk to the backend. I've got another Ubuntu VM running Elasticsearch (and an experimental Django API). That's it, and my shit is pretty fast, but I've only got like 4k blogs at the moment. It's hard to admit this, but I've been a Windows guy the majority of my career. I was a self-deprecating Windows user and I knew that Linux was a better platform for building most software (save C#), I'd just never taken the time to learn it. I'm a newish Mac user and now I've refreshed my memory on VI, I 'grep' shit, write bash scripts, and in general still have little idea what I'm doing. But the advantage to working in the command line is becoming clear when you get the shortcuts down, especially installing software. pip install is my friend, but don't get me started on how I don't have a virtual environment for my Python libraries. Did you know there are 2 locations for libraries when using Python? It sucks.

Right now I have a domain where you can go search narrative travel blogs in Africa. Eventually, I'll tell the world about it, but I have a few more big ticket items to address. That being said, I'm looking for early adopters! Free internet scouring if you are traveling to Africa!

Nov 28, 2009

Adventures in Information Extraction (Part I)

I'm currently embarking on a personal project to parse and index content from certain specific blogs.  Before this adventure, my knowledge of the relevant body of information science was merely a term, Natural Language Processing (NLP), that I had no understanding of, and still don't.  Now that I've done some google-jerking, and with a bit of helpful clarification from a friend of mine enrolled grad school, I've hopefully started to define my initial effort into some more specific technologies and fields of study.  Nonetheless, alot of this will change as time goes on.

First let me describe, in general, my problem set and let me preface by saying, this is currently my 10,000 ft view of the problem approach.  I wish to target specific blogs and extract from them strictly blog content, minus the useless parts of the page (navigation, footer, header, ect).  Now, I hope to initially target two sites that contain lots of other blogs.  In doing this, I should be able to extract a general template (a common body for example) that contains the content of interest.  With content in hand, I would like to store this stuff in an index for quick retrieval using Lucene.Net.  Now what I am going to extract remains a bit muddy at the moment, as I try to explore the relationship between certain Natural Language Processing techniques and Lucene.  For instance, Lucene has the ability to tokenize (basically, find words), perform stemming (map variations such as 'traveled', 'traveling', and 'travel' to the root 'travel'), and filter stopwords ('the', 'a').  These things seem foundational to search in general, but what I really would like to index specifically are place names like 'The Taj Mahal', 'Pismo Beach', or 'Moe's Tavern'.  My research has pointed me to Named Entity Extraction, a subfield of Information Extraction.  Now the field of  IE starts to get a bit murky for me, and this theme will perpetuate as I go further down the rabbit hole.  I first started to try and find a good api and accompanying tutorial on these things.  Many roads pointed to NLTK and it's quite descriptive, and free, online book.  The library is built with Python, and I've traditionally been brewing C# and .NET for awhile.  But the idea of  learning a new language is welcoming to me.  My initial opinion of Python, is that its much easier to learn and use than a regimented procedural language like C# (though .NET has been making impressive headway into functional programming with F#).  Additionally, the syntax and libraries are more adept at parsing text.  The plan so far is to work my way through the online book to Chapter 7, which goes into exactly what I'm looking for.  Anyway, all this stuff is like drinking from a fire hose: new language, two new api's, and new subject matter, but I'm hoping I'll be able to put together a prototype in my spare time.  So far, I've been able to do some fun things with Python using Frequency Distribution (how many times a word appears in text), finding a word in context (collocation), and filter out some proper nouns using POS Tagging, a small step closer to getting my place names.  So for now, I'll keep inching towards Named Entity Extraction.  Once I have a working prototype for getting place names, I can circle back on some of the other things like feeding content into a simple Lucene index and figuring out the relationship between NLTK and Lucene.  Until I have some automatic extraction methods, I'm using Dapper to get me some data to play with.

It seems funny writing all this up, because tomorrow the direction will change.  But I'll stay flexible, and hopefully writing about my experience with help others avoid my stupid mistakes.