DeepDream and Visualization of filters in Convolutional Neural Networks

Many of us might have the experience when we look up in the sky, we see the clouds as many shapes or objects. Some pieces of clouds look like a human face, while some others look like the dog in your neighbor’s backyards. In this post, I will demonstrate that A.I. nowadays have the similar ability, i.e. to imagine a certain image to some other objects.

But first I want to introduce the Google’s DeepDream. DeepDream is a computer vision program created by Google using Convolutional Neural Networks (CNN) to create dreamlike, deliberately over-processed images. If you are interested in how a certain image is over-processed, you can google ‘DeepDream’ to get a sense of it. I will not demonstrate it here because some of them are really not that aesthetically pleasing.

My experiment starts with using the Python DeepDream code from Google. I decide to use the CNN developed by google Google ImageNet challenge as the architecture. The net has a lot of layers to use and I decide to experiment on two layers (which can be seen as two filters due to the inner nature of the CNN layers) of the CNN to process the original image, which I will show below:

initial

The first layer I will use is called “inception_3a”. It is one of the first several layers in the Google’s ImageNet CNN. The reason why CNN works so well in computer vision problem is the fact that CNN, through back propagation (or some other updating algorithms), learn the feature representation of the images. This implies that the higher the layer, the more complex features CNN will learn. For example, if we want to train a 10 layer CNN to recognize the image of dogs. The first two layers will learn some primitive features, such as the edges and corners. The 5th or 6th layer might be able to learn the face of a dog, or the leg. If we visualize the 8th or 9th layer, we can see features of a dog of any kind. Anyway, let’s visualize what happens if we apply lower layers in CNN to the cloud image.edge1

After about 5 iterations, CNN seems to learn the edges and corners of the cloud and began to alter the image according to the edges and points it detected. Let’s see what happened if we train this image for 27 iterations:

edge3

Now most of the edges in the original image can be detected and amplified, thus creating a dreamlike image of a cloud.

Now it’s time for us to use some deeper layers to our original image. This time I use “inception_5a” layer, which is not far from the output layer. After 5 iterations, here is what we have:

animal1

I am not sure about you, but I can see some eyes of some very weird animals. It seems to be dogs, but not quite. This is because the layer tries to learn the representation of ALL images, not a single image of a particular dog. Besides the layer needs to image the cloud to be some kind of animal. Thus what we have is a ‘synthetic animal’ image derived from a cloud. After 27 iterations, let’s see what we have:

animal2

We can see a little more about animal eyes and everything. Finally, I would like to demonstrate what happens if we train the original cloud image using the deepest convolutional layer in CNN for 27 iterations. Our guess is that it can really learn some very complex features of the cloud. See for yourself if it is true:

cloud2

This is a little gross. What the HELL are these weird animals? I mean, seriously, a rabbit splitting with a fish? A bug with two head? This is delusional. Anyway, this is the power of CNN. It is able to create some deeply hallucinated images, to the extent that we even feel a little disgusted by some. This really is some real complex features of thousands of images!

Learning process of a recurrent neural network

Recently I’ve been developing a random text generator using recurrent neural networks (RNN), inspired by this tutorial. Specifically, I trained a huge corpus of Wall Street Journal with two-layered Long-Short-Term-Memory (LSTM) recurrent neural networks, and try to generate WSJ-styled text. After several hours of training the result gets better and better, but the text generated still does not make any sense. Nevertheless, there are some interesting insights about it.rnn

 

I trained the WSJ corpus with two different kinds of approaches. Word-level approach requires us to use a list of successive words as input data. RNN will learn the probability of the next word from the word representations trained in itself. Character-level approach requires us to use letters and punctuations as input data. With this approach RNN will predict next character.

After training for about 50 iterations of WSJ corpus with character-level RNN model, I am able to get something like this:

tax adjustment than the president of has a return on executive director of the mond-neconticulation firmers said 0 the think 0 they works and catiflity * pressure *-1 to be as *-1 belong the paytent , and the post because of the president of a restriction of the company ‘s consumer entirely novers for large new york , and the market and substancial from the botton for the market is part of a sidely financial

Apparently 50 iterations is far from being perfect, but at least most of words it has generated are actually words. One interested fact I do find is that some of the mistakes computer makes after some training time is very similar to human beings’ learning process. For example, in this paragraph, words like “botton” and “substancial” are very likely the mistakes human makes when we memorize vocabularies. In other generated text displayed in the previous iterations, we can also see words like “finantion”, “assat” or “sociel”.

I am not an expert in linguistic, so I don’t know what conclusion I can draw from this discovery. Nevertheless, it’s hopefully an interesting found-out that shows how similar the learning process between human and computers are! It’s also a good break from running iterations and iterations of training process: (

Finally, to show how powerful the recurrent neural networks can be, below is an example of image captioning generated by a well-trained recurrent neural network!

stcnrn-640x365.jpg

 

generate tag cloud gif for yelp reviews of restaurants in Williamsburg

In this post, we talked about how to generate tag cloud through the yelp reviews of restaurants in Williamsburg. Today we will improve upon the previous project, and generate gif from tag clouds of reviews in different years. This way we can better visualize how the key words in yelp reviews change in years.

1. Generating gif files from python

A great way to generate gif files from a bunch of images does not require installing any packages. The python code written by Almar Klein, Ant1 and Marius van Voorden works very well. To get the code, please refer to https://grass.osgeo.org/grass70/manuals/libpython/_modules/imaging/images2gif.html. Put the images2gif.py file in the same directory as the current directory, then we are good to go.

Throughout this post I will also use Peter Chang as an example, because it’s such a great Chinese restaurant in Williamsburg, VA. First we import the Necessary files:

import os #if you want to import images from local directories

from images2gif import writeGif
from PIL import Image, ImageSequence

Suppose we want to make gif file from three .png files: ‘first.png’, ‘next.png’, ‘last.png’. The following code immediately write the gif file, the comment illustrates each step:

filenames = [ ‘first.png’, ‘next.png’, ‘last.png’] 
im = [Image.open(i) for i in filenames] #getting images from file names
im = [i.resize([650,650], Image.ANTIALIAS) for i in im] #resize all images to the same size, ready to make gif
writeGif(‘peter_chang.gif’, im, duration=1.2) #you can control the duration of displaying every single image.

This way we get a gif from the above three image files.

2. Scrape the text data with date

One problem of the previous post is that we can get the review text, but not the date the review is posted. This is trivial to fix:
def scrapper(url):
      html = urllib2.urlopen(url).read()#.decode(‘utf8’)
      all = re.compile(‘<p itemprop=”description” lang=”en”>(.*?)</p>’)
      all_date = re.compile(‘<meta itemprop=”datePublished” content=”(.*?)”>’) #this line of code scrapes the date string of the review
      List = zip(re.findall(all_date,html),re.findall(all,html)) #zip the date and review string so that they come together. 

      string = ‘ ‘.join([‘ ‘.join(i) for i in List])
      return string

3. Cleaning text and getting reviews by year

Our implementation to clean the text is exactly like in the last post, except we encapsulate the cleaning step into a function for reuse.

from pytagcloud import create_tag_image, make_tags
from pytagcloud.lang.counter import get_tag_counts
import re
from nltk.corpus import stopwords
from collections import Counter

def preprocessing(text, year):
       words = re.findall(r’\w+’, text)
       lower_words = [word.lower() for word in words]
       stops = set(stopwords.words(“english”))
       stops2 = [‘ve’, ‘get’, ‘came’, ‘didn’, ‘ever’, ‘never’, ‘though’, ‘wasn’,’food’,’williamsburg’,’restaurant’, ‘br’, ’39’,’34’, ‘place’,’go’,’even’, ‘2015’,’2014′,’2013′,’2012′,’2011′,’2010′,’2009′,’2008′,’2007′,’2006′,’2005′,’2004′]
       meaningful_words = [w for w in lower_words if ((not w in stops) and (not w in stops2))]

       word_counts = Counter(meaningful_words)
       counts = dict(word_counts)
       most_common,num_most_common = word_counts.most_common(1)[0]

       text = ”
       for i in counts.keys():
              text = text + (‘ ‘ + i) * (counts[i])
              text += (‘ ‘ + str(year)) * (num_most_common)
       return text

One important change is to also include the year string in the tag cloud, so that we know which year the image is referring to. I also considered adding title to each image indicating the year, but making year as an element in the image itself might be a more natural way. The next step we segment reviews by year using a for loop, and creating tag cloud images accordingly:

def get_image(text, image):
tags = make_tags(get_tag_counts(text)[:50], maxsize=100) #we take only first 50 words to avoid crowded images
create_tag_image(tags, image, size=(900, 700), fontname = ‘Lobster’)

f = open(‘peter_chang_date.txt’, ‘r’)
text = f.read()

filenames = []

im = []
for i in range(int(text[:4]), 2004, -1): #yelp was founded in 2004, also, first 4 strings in text is always the year string
       if str(i) in text:
              temp = text.split(str(i -1))[0]
              text = text[len(temp) – 1:]
              get_image(preprocessing(temp, i), str(i) + ‘.png’)
              im.append(Image.open(str(i) + ‘.png’))

filenames.append(str(i) + ‘.png’)

4. Getting the gif to work!!!

Now we get the im variable. The final step is to create gif file from the generated tag cloud images.

im = [i.resize([650,650], Image.ANTIALIAS) for i in im]

writeGif(‘peter_chang.gif’, im, duration=1.2) #make the duration relatively long so that people can see the words in each individual image

Below is my generated tag cloud gif for Peter Chang in Williamsburg:

peter_chang

After you generate the tag cloud, each individual image file is still in the current directory. If you don’t want this to happen, you need to delete those files. The single line of code os.remove(file) for file in filenames will suffice.

For the complete code, please refer to my Github repository: https://github.com/ChaoranWei/Williamsburg_restaurant_yelp_keywords_analysis .

NBA players tweets sentiment analysis (1)

In this post, I will talk about my discovery after the sentiment analysis of NBA players tweets.The code to achieve this can be found on my github: https://github.com/ChaoranWei/NBA-player-tweets-analysis. I will talk about my basic methodology to achieve this, and then something interesting I discovered during the analysis.

1. Basic Methodology

The logic behind this analytic project is simple: get the data, then analyze it. To get the data, we need to use Twitter API. I personally use tweepy package in python to achieve this. Note you also need to register in Twitter to get the necessary keys. After you get the the tweets of NBA players, you can analyze whatever you want and have fun!

2. NBA players sentiment analysis

I use AFINN.txt as the dataset to analyze the sentiment. This dataset has a lot of positive and negative words ranging from -5 to 5. -5 means the given word is extremely negative, which mostly consists of inappropriate words. 5 means the word is extremely positive, such as breathtaking and harrah. The limitation of this dataset is that we can only measure the degree to which a given word is positive or negative, but we cannot get the specific emotion, like excited, painful, etc.

The evaluation metric for the sentiment is the following: We calculate the aggregate sentiment level of a certain player and divided by the number of words in his tweets, we get average sentiment level per word. This turns out to be a very low value, without any surprise. However, if we multiply this value with 100, we get the sentiment level per 100 words, which is better for visualization.

For example, if in Andre Iguodala’s tweets, We add sentiment level of all words and then divided by number of words in his tweets, we get 0.19. This value denotes the expected value of the sentiment level per word. We multiply 0.19 with 100 we get 19, which becomes the expected value of the sentiment level per 100 words, which I consider more illustrative.

After analyzing the tweets of NBA players, here are the interesting results:

For example, we all know the youngest MVP player in the NBA Derrick Rose suffers from a really bad injury several seasons ago. He is still pretty young and promising but due to his injury and psychological side-effect, he did not play very well this season. Now let’s visualize his sentiment and see if the bad game affects his emotion, or vice versa.

figure_1

Note that from this we cannot draw the conclusion that bad game affects the emotion of our D Rose, nor could we conclude that the emotion effect the performance this season. To discover more about this issue, we need to resort to time-series analysis techniques, such as Impulse-response function or co-integration test. This post discuss no further of this.

Another interesting result is the correlation between the sentiment level and the winning percentage of the team in 2015-2016 season. It is intuitive that if a team plays really bad this season, sentiment of all its players cannot be very high. If a team (like Golden State) plays very well, sentiment level of players in this team will be high. Let’s discover whether this claim is true:

figure_1.png

In this graph, each data point denotes a team. We expect the scatter plot to roughly have positive slop, but the graph indicates otherwise. There are two potential reasons for this:

  1. data value for each team is limited. This makes sense, because not all NBA players are big fan of Twitter. Thus for some teams, tweets of only one or two players are collected. This deficiency of data points will result in high variance and maybe more outliers.
  2. There are really no correlations between the two for some reason.

To further develop this argument, we want to eliminate some outliers (thus high variance) and see the result again. Note that from eyeballing the graph we can find that there are 6 apparent outliers but only 29 data points, therefore 20% of all data values might be eliminated due to outlier detection. 20% is too much for the percentage of outliers, but we do it anyway, because the variance in this dataset really is too big.

There are two popular methods for outlier detection that python sklearn package supports: Univariate method and EllipticEnvelope method. We will try both algorithms for outlier detection.

Univariate:

figure_1

This seems not effective. There is a good reason for that: We only consider sentiment level (because this is univariate) when detecting the outlier, which does not capture the interaction between two variables. We may not consider this method.

Elliptic Envelope:

figure_1

This method removes some apparent outliers. This result is satisfactory, because we cannot expect sentiment level to be a strong indicate of winning percentage of a certain team. After calculating the correlation between the two variables, we get 0.45 correlation between two variables, which is low to moderate correlation between two variables.

We take another perspective to analyze this dataset. If we consider team winning percentage as dependent variable and team sentiment level as independent variable. It is then a good idea to calculate Coefficient_of_determination (R^2). By definition, Coefficient of determination is the percentage of variable variation explained by the linear model. In this context, R^2 is the percentage of variation of winning percentage explained by sentiment level. After some calculation by sklearn library, we get R^2 = 0.2. Again, intuitively sentiment level is a weak but potential indicator of team winning percentage, so R^2 = 0.2 means sentiment level has some explaining power to the winning percentage.

In conclusion, both graphical and analytical evidence suggest that there are correlation between the winning percentage of team and the sentiment level of the player in this team, even though we cannot conclude anything about which affects which. This is not only one of many interesting basketball analytical result, but also have some application in the field of basketball analytics. For example, if we want to run some regression analysis against winning percentage of a NBA team, we can use sentiment level as a feature in the analysis.

3. Code

The complete code has been uploaded on my github account. Please refer to: https://github.com/ChaoranWei/NBA-player-tweets-analysis.

 

 

 

 

Collection of Tag Cloud: yelp reviews of restaurants in Williamsburg

In Last post, we talked about the how to use python to generate the tag cloud. This post is the demonstration of the tag cloud of restaurants in Williamsburg.

Peter Chang:

peterchang

Food For Thought:

food_for_thought

Stephanos:

stephanos

 

Nawab Indian Cuisine:

nawab

zpizza:

zpizza

Bangkok Garden:

bangkok_garden

And Kyoto:

kyoto

This is a paradoxical one, because yelp gives only 2.5 stars, but the tag cloud indicates only either good or neutral words.

 

 

Use python pytagcloud to generate tag cloud for yelp reviews of restaurants in Williamsburg

A tag cloud is a visual representation of text data. It’s a great way to visualize word frequency from text. This blog demonstrates how to use python to generate tag cloud from a collection of text data. An example of tag cloud from wikipedia data is shown below:

Foundation-l_word_cloud_without_headers_and_quotes

1. prerequisite

In order to do this small task, a number of python packages are required:

nltk (Natural Language Tool Kit): great library for all kinds of NLP tasks.

pytagcloud: library to generate tag (or word) cloud.

2. scrapping yelp data from the website

A great source to explore more about yelp data is yelp API. Unfortunately, yelp API does not release more than one reviews from any restaurant. Therefore, it’s impossible to get a corpus of reviews of a single restaurant from yelp API. We need to scrap the reviews data by ourselves.

To scrap the reviews data from any website, we need to first import the modules and packages we need to use:

import urllib2
import re

urllib2 package is used to get the html file from the requested url, and re package deal with regular expression, which is used to match a certain pattern from the text file.

Then we need to write a python web scrapper function to encapsulate the scrapping process:

def scrapper(url):
         html = urllib2.urlopen(url).read() #get html from url provided
         all = re.compile(‘<p itemprop=”description” lang=”en”>(.*?)</p>’) #find all the text between two a certain html tag, this serves as a html cleaning tool
         list = re.findall(all,html)
         string = ‘  ‘.join(list) #join the list into a single string
         return string

The comment illustrates the meaning of each line of code. After we complete the scrapper function, we need to write the main program: to iterate through all url pages and save the text into a single file. I will use Peter Chang in Williamsburg as an example:

fil = open(‘peter_chang.txt’, ‘w’)
String = ”
url = ‘http://www.yelp.com/biz/peter-chang-williamsburg&#8217;
String += scrapper(url)
print(0)
for i in range(20, 101, 20): # we need to do a little research on the pattern of the urls we want
String += scrapper(url + ‘?start=’ + str(i))
print(i)

fil.write(String)
fil.close()

This simple program scraps the yelp reviews data of any restaurant into  single text file.

3. making tag cloud!

The text we get from the last section is not ideal. It is filled with the words or tags we don’t want such as ‘the’, ‘a’, or the html tags such as ‘<br>’. We need to get rid of those strings before we can generate tag cloud.

from pytagcloud import create_tag_image, make_tags
from pytagcloud.lang.counter import get_tag_counts
import re
from nltk.corpus import stopwords
from collections import Counter

f = open(‘peter_chang.txt’, ‘r’)
text = f.read()
words = re.findall(r’\w+’, text)
stops = set(stopwords.words(“english”))
stops2 = [‘ve’, ‘get’, ‘came’, ‘didn’, ‘ever’, ‘never’, ‘though’, ‘wasn’,’food’,’williamsburg’,’restaurant’, ‘br’, ’39’,’34’]
meaningful_words = [w for w in words if ((not w in stops) and (not w in stops2))]
lower_words = [word.lower() for word in meaningful_words]

Note stopwords is a nltk corpus that contains common stop words (such as ‘the’, ‘is’). You can download the corpus online.

word_counts = Counter(lower_words)
counts = dict(word_counts)
text = ”
for i in counts.keys():
if counts[i] > 11:
text = text + (‘ ‘ + i) * counts[i]

This step denotes the fact that we will lose the word frequency when we process the text. The counter is the remedy. We also need to tune the number of words appears in the tag cloud, so that there are not too many words, nor too few words in the picture.

The final step is to make the tag cloud.

tags = make_tags(get_tag_counts(text), maxsize=90)
create_tag_image(tags, ‘peter_chang.png’, size=(700, 700), fontname=’Lobster’)

There are only two lines of code, simple and neat. However, the result will not look good if you do not tune the maxsize and size parameters. The parameters given above have already been tuned, so this should produce an appealing tag cloud!

peterchang

For the source code, please refer to https://github.com/ChaoranWei/Williamsburg_restaurant_yelp_keywords_analysis.