Files
2021-11-02 11:49:48 +01:00

474 KiB

ABC News: Kaggle competition

By performing topic modeling on the news dataset, we are able to understand the dominant themes of discussion through out the time.

Sourced from the reputable Australian news source ABC (Australian Broadcasting Corporation)

https://www.kaggle.com/therohk/million-headlines

We will start by importing the packages we will need!

In [20]:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
In [21]:
headlines = pd.read_csv('abcnews-date-text.csv',parse_dates=[0], infer_datetime_format=True)
headlines.head()
Out [21]:
publish_date headline_text
0 2003-02-19 aba decides against community broadcasting lic...
1 2003-02-19 act fire witnesses must be aware of defamation
2 2003-02-19 a g calls for infrastructure protection summit
3 2003-02-19 air nz staff in aust strike for pay rise
4 2003-02-19 air nz strike to affect australian travellers

Sweet! Now that we have imported the data, let's start an exploratory data analysis to get a feeling of the data. We will start by adding a column for the average number of words in each headline.

In [23]:
headlines['number_words'] = headlines['headline_text'].apply(lambda x: len(x.split()))
headlines.describe()
Out [23]:
number_words
count 1.226258e+06
mean 6.538226e+00
std 1.862832e+00
min 1.000000e+00
25% 5.000000e+00
50% 6.000000e+00
75% 8.000000e+00
max 1.500000e+01

Now let's see how the data is being distributed.

In [24]:
headlines[['number_words']].hist(figsize=(12,6), bins=10, xlabelsize=8, ylabelsize=8)
plt.title('Distribution: Number of words in headlines')
Out [24]:
Text(0.5, 1.0, 'Distribution: Number of words in headlines')
In [25]:
headlines['year'] = pd.DatetimeIndex(headlines['publish_date']).year
headlines['month'] = pd.DatetimeIndex(headlines['publish_date']).month
headlines['day'] = pd.DatetimeIndex(headlines['publish_date']).day
headlines.head()
Out [25]:
publish_date headline_text number_words year month day
0 2003-02-19 aba decides against community broadcasting lic... 6 2003 2 19
1 2003-02-19 act fire witnesses must be aware of defamation 8 2003 2 19
2 2003-02-19 a g calls for infrastructure protection summit 7 2003 2 19
3 2003-02-19 air nz staff in aust strike for pay rise 9 2003 2 19
4 2003-02-19 air nz strike to affect australian travellers 7 2003 2 19
In [26]:

headlines['day'].hist(figsize=(12, 6), bins=10, xlabelsize=8, ylabelsize=8);
plt.title("Distributon of number of headlines across days")
Out [26]:
Text(0.5, 1.0, 'Distributon of number of headlines across days')
In [27]:
headlines['month'].hist(figsize=(12, 6), bins=10, xlabelsize=8, ylabelsize=8);
plt.title("Distributon of number of headlines across months")
Out [27]:
Text(0.5, 1.0, 'Distributon of number of headlines across months')
In [28]:
headlines['year'].hist(figsize=(12, 6), bins=10, xlabelsize=8, ylabelsize=8);
plt.title("Distributon of number of headlines across years")
Out [28]:
Text(0.5, 1.0, 'Distributon of number of headlines across years')
In [29]:
from wordcloud import WordCloud
all_words = ''.join([word for word in headlines['headline_text'][0:100000]])
all_words
wordcloud = WordCloud(width=800, height=500, random_state=21, max_font_size=110).generate(all_words)
plt.figure(figsize=(15, 8))
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis('off')
plt.title("Some frequent words used in the headlines", weight='bold', fontsize=14)
plt.show()

The wordcloud seems so interesting. Inspite of the news channel belonging to Australia, we can see some frequent words like 'iraq' and some other words like 'police', 'plan', 'health', 'council', etc.

Since, LDA has a lot of computations, we will sample 1% of the data and perform the analysis which might not lead to very intelligent topics but it will give us a high level understanding of what LDA does.

In [31]:
news = headlines.sample(frac = 0.01, random_state= 423)
news.head()
Out [31]:
publish_date headline_text number_words year month day
1049948 2016-09-27 colombian marxist rebels sign peace deal endin... 10 2016 9 27
777673 2013-04-11 darwin harbour safe for bush tucker 6 2013 4 11
586742 2011-01-09 nsw beach evacuated after shark sighting 6 2011 1 9
641074 2011-09-25 abduction alert after baby kidnapped 5 2011 9 25
346284 2007-11-25 jets mariners share the spoils 5 2007 11 25
In [32]:
news = news.drop(columns = 'publish_date')
news = news.reset_index()
news.head()
Out [32]:
index headline_text number_words year month day
0 1049948 colombian marxist rebels sign peace deal endin... 10 2016 9 27
1 777673 darwin harbour safe for bush tucker 6 2013 4 11
2 586742 nsw beach evacuated after shark sighting 6 2011 1 9
3 641074 abduction alert after baby kidnapped 5 2011 9 25
4 346284 jets mariners share the spoils 5 2007 11 25
In [38]:
import nltk
from nltk.corpus import stopwords
import gensim
import pyLDAvis
import pyLDAvis.gensim_models
from nltk.stem import WordNetLemmatizer, PorterStemmer
from nltk.tokenize import word_tokenize

def get_lda_objects(text):
    nltk.download('stopwords')
    stop_words = set(stopwords.words('english'))
    
    def preprocess_news(df):
        corpus=[]
        stemmer = PorterStemmer()
        lemmatizer = WordNetLemmatizer()
        for news in df['headline_text']:
            #tokenize each headline and remove its stopwords
            words=[word for word in word_tokenize(news) if (word not in stop_words)]
            words=[lemmatizer.lemmatize(word) for word in words if len(word)>2]
            
            corpus.append(words)
        return corpus
    corpus = preprocess_news(text)
    
    dic = gensim.corpora.Dictionary(corpus)
    bow_corpus = [dic.doc2bow(doc) for doc in corpus]
    
    lda_model = gensim.models.LdaMulticore(bow_corpus,
                                           num_topics = 4,
                                           id2word = dic,
                                           passes = 10,
                                           workers = 2)
    return lda_model, bow_corpus, dic

def plot_lda_vis(lda_model, bow_corpus,dic):
    pyLDAvis.enable_notebook()
    vis = pyLDAvis.gensim_models.prepare(lda_model, bow_corpus, dic)
    return vis
In [39]:
lda_model, bow_corpus, dic = get_lda_objects(news[['headline_text']])
[nltk_data] Downloading package stopwords to
[nltk_data]     C:\Users\arman\AppData\Roaming\nltk_data...
[nltk_data]   Package stopwords is already up-to-date!
In [40]:
lda_model.show_topics()
Out [40]:
[(0,
  '0.007*"say" + 0.005*"health" + 0.005*"australia" + 0.004*"cup" + 0.004*"water" + 0.004*"still" + 0.004*"fire" + 0.004*"police" + 0.004*"call" + 0.004*"world"'),
 (1,
  '0.015*"man" + 0.009*"death" + 0.008*"police" + 0.006*"woman" + 0.005*"attack" + 0.005*"coast" + 0.005*"new" + 0.004*"hospital" + 0.004*"get" + 0.004*"local"'),
 (2,
  '0.007*"record" + 0.006*"govt" + 0.005*"sale" + 0.004*"plan" + 0.004*"drug" + 0.004*"public" + 0.004*"price" + 0.004*"national" + 0.004*"police" + 0.004*"coronavirus"'),
 (3,
  '0.007*"new" + 0.006*"council" + 0.006*"court" + 0.005*"interview" + 0.005*"budget" + 0.004*"welcome" + 0.004*"back" + 0.004*"resident" + 0.004*"driver" + 0.004*"get"')]
  • On the left side, the area of each circle represents the importance of the topic relative to the corpus. As there are four topics, we have four circles.
  • The distance between the center of the circles indicates the similarity between the topics. Here you can see that the topic 3 and topic 4 overlap, this indicates that the topics are more similar.
  • On the right side, the histogram of each topic shows the top 30 relevant words. For example, in topic 1 the most relevant words are police, new, may, war, etc
In [41]:
plot_lda_vis(lda_model, bow_corpus, dic)
Out [41]:
C:\Users\arman\anaconda3\envs\tm-lda38\lib\site-packages\pyLDAvis\_prepare.py:246: FutureWarning: In a future version of pandas all arguments of DataFrame.drop except for the argument 'labels' will be keyword-only
  default_term_info = default_term_info.sort_values(
In [ ]: