<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Brian Odhiambo on Medium]]></title>
        <description><![CDATA[Stories by Brian Odhiambo on Medium]]></description>
        <link>https://medium.com/@brianodhiambo530?source=rss-abe237d7f4c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A_r2MQhb94AW1xBCP5yqMw.jpeg</url>
            <title>Stories by Brian Odhiambo on Medium</title>
            <link>https://medium.com/@brianodhiambo530?source=rss-abe237d7f4c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:53:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brianodhiambo530/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Perfomance Of Different Machine Learning Models On Classifier Problem]]></title>
            <link>https://medium.com/@brianodhiambo530/perfomance-of-different-machine-learning-models-on-classifier-problem-8893903d5672?source=rss-abe237d7f4c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8893903d5672</guid>
            <category><![CDATA[sales-prediction]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Brian Odhiambo]]></dc:creator>
            <pubDate>Sat, 29 Aug 2020 18:18:11 GMT</pubDate>
            <atom:updated>2020-08-30T15:48:11.401Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DVjqTokRAILfcZwD" /><figcaption>Classifier machine learning models</figcaption></figure><p>Knowing the best model to use when solving a business problem can be very handy. However this depends with the type of problem being solved. In this article we will tackle a classifier problem. We consider a marketing campaign of a Portuguese bank and do prediction of customers who will subscribe to their bank term deposit.</p><p>This automatically leads to selection of machine learning models that can be used in this particular use case. Since there are vast options when it comes this kind of problem, we will use three models, and compare their performance before and after hyperparameter tuning. We will first look at the structure of our dataset, do univariate and bivariate analysis on the data, preprocess it to be ready for machine learning models and eventually do some predictions using our models. The models we will use are Logistic Regression, XGBoost and Multilayer Perceptron. We will look briefly on what these models are and how they fit this problem at hand before implementing them.</p><p>Data used in this project can be found from the UCI Machine Learning Repository, <a href="http://archive.ics.uci.edu/ml/datasets/Bank+Marketing">Bank Marketing dataset</a>.</p><h4>Exploratory Data Analysis</h4><p>Before starting our EDA journey, we will import our dataset. We will use pandas read_csv() funtion. Since we are using a cookiecutter template, we will set the path to join it the data’s directory. Cookiecutter is a standard template for data science projects which comes with prearranged python files and directories. More on cookiecutter can be found in <a href="https://nsls-ii.github.io/scientific-python-cookiecutter/preliminaries.html">this website</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2965a607be564fb2f20b251ee671ac3/href">https://medium.com/media/a2965a607be564fb2f20b251ee671ac3/href</a></iframe><p>To get a quick overview of our data set, we will use df.info(). This way we will be able to know the size of our data set, the features we have and their data types. We can easily tell if there is any missing values for any of the features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f585572e40476791c7f0e75fe1b1b0af/href">https://medium.com/media/f585572e40476791c7f0e75fe1b1b0af/href</a></iframe><p>From the above analysis, we have 11 categorical features and 21 features in total. There are 41188 rows in the data set. Before we jump to univariate and bivariate analysis, let’s have a look at the statistical descriptions of our columns. This can quickly be done using .describe() function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df412c34003637c9d69da9b06688dddb/href">https://medium.com/media/df412c34003637c9d69da9b06688dddb/href</a></iframe><h4>Univariate Analysis</h4><p>We will look at the distribution of our features at this point. Plotting the features will help us grasp quickly the distribution of the values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMFRmBGtfsyiCx_IYo-Qhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*uNSqhLpfQYj2EDRo2lRzwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*4PY1LSxHVm2apzBeJhZKFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*-wJ0Bbd7BAjBwLTO-emGoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*XIEdgp8iKJ4P2RqW2KzeaQ.png" /></figure><p>For the age category, most bank’s customers fall in the age of 30s. For the education feature, high school and university degree categories hold the highest frequencies. Married bank client’s tend to be high in number in the dataset compared to other marital statuses. Generally, the number of client’s who did not subscribe to the bank’s term deposit are more than those who did.</p><h4>Bivariate Analysis</h4><p>How does the features correlate to each other? Does this affect the client’s subscription to the bank’s term deposit? We will plot a heat map to quickly help us grasp the trend in feature correlation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zf7OIj0h14QNFbFGCHXqaQ.png" /><figcaption>Heatmap showing correlation of features</figcaption></figure><p>The highly concentrated parts in the heatmap denotes high correlation between the features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9he3gcZUzu6qe65eiR_INg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Ha8kglgimXI-y60__dRyg.png" /><figcaption>Box plots of different features in correlation with the y variable</figcaption></figure><p>The box plot shows presence of outliers in the data set which we will have to deal with before modelling. Since our main objective is to applying machine learning to the dataset, we will start our preprocessing phase on the dataset.</p><p>Before jumping into preprocessing part, let’s get nformation on one of our features in the dataset. The “duration” feature highly affect the output variable (e.g., if duration=0 then y=’no’). Yet, the duration is not known before a call is performed. Also, at the end of the call y is obviously known. In order to have a realistic predictive model, we will drop this attribute at this point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4829cb47938dcb7905747d1af70a7082/href">https://medium.com/media/4829cb47938dcb7905747d1af70a7082/href</a></iframe><h4>Data Preprocessing</h4><p>Looking at our dataframe at this point, we have seen the correlation between the features. We also seen the distribution of the features across the data set. We will now transform our data into a form that can be used for machine learning. This will involve the following steps:</p><p><strong><em>1. Feature Encoding</em></strong></p><p>Since machine learning models only use numbers, we will transform our categorical features into numbers. We will use two techniques for this case, binary encoding and one hot encoding. Binary encoding is used where there are only two possible values in a feature, hence the name binary. This will suite our case for the target feature. For the rest of the categorical variables, we will use pandas dummies function which does one hot encoding just the same way OneHotEncoder library does. More on feature encoding techniques can be found on <a href="https://www.geeksforgeeks.org/feature-encoding-techniques-machine-learning/">this website.</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a6a29c8001b57995712aae0bb400d64/href">https://medium.com/media/7a6a29c8001b57995712aae0bb400d64/href</a></iframe><p>We drop our y variable since we have encoded subscription variable. Having the output variable as the first or the last position is always my norm. We will rearrange the dataset columns to achieve this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f24f60879940432ca5270b98a9d2bc56/href">https://medium.com/media/f24f60879940432ca5270b98a9d2bc56/href</a></iframe><p><strong><em>2. Feature Standardization</em></strong></p><p>We do not want the distribution of our variables to be far from the mean value, hence the need to standardize. This will help to attain normal distribution in the dataset. Scaling also help in speeding calculations in algorithms .We will use StandardScaler class from the sklearn preprocessing module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cffe82cd3b973ece28d1150f1cd264f1/href">https://medium.com/media/cffe82cd3b973ece28d1150f1cd264f1/href</a></iframe><p>At this point we will divide our independent variables and dependent variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa8157d60738ae0bca3b648af2dd6bec/href">https://medium.com/media/fa8157d60738ae0bca3b648af2dd6bec/href</a></iframe><p><strong><em>3. Dealing with class imbalance</em></strong></p><p>Having underpresented datapoints in our variables will lead to to biased machine learning model. For example, let’s see visualization for the target variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*XIEdgp8iKJ4P2RqW2KzeaQ.png" /><figcaption>subscription distribution</figcaption></figure><p>We can clearly see the yes values in the subscription features is greatly underpresented. This calls for dealing with the class imbalance in the dataset. We will use RandomOverSampler library to deal with this issue, which comes from the imbalance-learn package. We will need to install this package before using RandomOverSampler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6062448a5c901d27f6b2963ceb6a74aa/href">https://medium.com/media/6062448a5c901d27f6b2963ceb6a74aa/href</a></iframe><p><strong><em>4. Dimension Reduction</em></strong></p><p>One drawbacks of using one hot encoder is that it creates dummy features hence multiplying the number of features in total. This forces us to do dimension reduction on our independent features since we do not want to use so many features. One technique we will use for this purpose is Principal Component Analysis which we will refer as PCA. This will reduce our dataframe to only ten components. We have reduced the dataframe to ten in this project for demonstration purposes but you are free to reduce it even to a lower number.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e7e20b36e0d403a6336ad57fa62a4e5/href">https://medium.com/media/0e7e20b36e0d403a6336ad57fa62a4e5/href</a></iframe><p>We will save our preprocessed dataset at this point and head straight to machine learning models.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fdca64144553ae1c0662f2e81e78e8f/href">https://medium.com/media/1fdca64144553ae1c0662f2e81e78e8f/href</a></iframe><h4>Machine Learning Models</h4><p>We will do a comparison on performance of three machine learning models and decide on which suites most on solving this problem at hand. As a first stepping stone, we will build a dummy classifier to act as our base model from which we will compare the performance of our outlined models.</p><h4>1. Dummy Classifier</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b2c4fdd430069fb7ef33c0d752d22d0/href">https://medium.com/media/7b2c4fdd430069fb7ef33c0d752d22d0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*2o_fp9tXtoBO3u5R46zSQg.png" /><figcaption>Baseline model ROC</figcaption></figure><p>We will train our models using KFold and Stratified KFold techniques which we will also do a comparison to see which performs better. KFold and Stratified KFold on each model before and after hyperparameter tuning.</p><p>KFold is a cross-validation technique where resampling procedure is used to evaluate machine learning models on a limited data sample. The procedure has a single parameter called k that refers to the number of groups that a given data sample is to be split into. As such, the procedure is often called k-fold cross-validation. When a specific value for k is chosen, it may be used in place of k in the reference to the model, such as k=10 becoming 10-fold cross-validation.</p><p>StratifiedKFold is a variation of KFold. First, StratifiedKFold shuffles your data, after that splits the data into n_splits parts. Now, it will use each part as a test set. Note that it only and always shuffles data one time before splitting.</p><p>We will create a function for this task hence reusing it for the difference models we have.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1e850ec35e3dece1d5e04c1a4cdebe8/href">https://medium.com/media/a1e850ec35e3dece1d5e04c1a4cdebe8/href</a></iframe><h4>2. Logistic Regression</h4><p>Logistic regression is a supervised learning classification algorithm used to predict the probability of a target variable. The nature of target or dependent variable is dichotomous, which means there would be only two possible classes. In simple words, the dependent variable is binary in nature having data coded as either 1 (stands for success/yes) or 0 (stands for failure/no).</p><p>Mathematically, a logistic regression model predicts P(Y=1) as a function of X. It is one of the simplest machine learning algorithms that can be used for various classification problems and hence suites our use case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/901fb75de34ba6775b377ff4e38fe4b0/href">https://medium.com/media/901fb75de34ba6775b377ff4e38fe4b0/href</a></iframe><p>Let’s look at the performance metrics using KFold and Stratified KFold</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7dbe10ffa4ebf27cae535997745084f/href">https://medium.com/media/b7dbe10ffa4ebf27cae535997745084f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*OmcYOnbrbGgHXOQmF6I-cA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*_BHj4DveoQulHzmIjZvMMg.png" /><figcaption>Roc Curve for Logistic Regression</figcaption></figure><h4>3. XGBoost</h4><p>XGBoost is an optimized distributed gradient boosting library designed to be highly <strong>efficient</strong>, <strong>flexible</strong> and <strong>portable</strong>. It implements machine learning algorithms under the <a href="https://en.wikipedia.org/wiki/Gradient_boosting">Gradient Boosting</a> framework. XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many data science problems in a fast and accurate way. We will XGBClassifier class for our classification problem. But first, will need to install XGBoost package. Run this command on your terminal to have xgboost installed: <strong><em>pip install xgboost. </em></strong>Ensure you are in the you have enabled your virtual environment<strong><em>.</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bca677c73646c58d1fe0ed84591d3bd3/href">https://medium.com/media/bca677c73646c58d1fe0ed84591d3bd3/href</a></iframe><p>Let’s look at XGBoost’s performance metrics using KFold and Stratified KFold</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66fb6992644e6f0bfcd19cb4348897ea/href">https://medium.com/media/66fb6992644e6f0bfcd19cb4348897ea/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*wX7_Z76mPFBHoZl7oDxoUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*po0_kKkEmC5-EO4wyrfETQ.png" /><figcaption>XGBoost ROC Curve</figcaption></figure><h4>4. Multilayer Perceptron</h4><p>A <strong>multilayer perceptron</strong> (MLP) is a class of feedforward artificial <strong>neural network</strong> (ANN). A perceptron is a single neuron model that was a precursor to larger neural networks. It is a field that investigates how simple models of biological brains can be used to solve difficult computational tasks like the predictive modeling tasks we see in machine learning. The goal is not to create realistic models of the brain, but instead to develop robust algorithms and data structures that we can use to model difficult problems. The power of neural networks comes from their ability to learn the representation in your training data and how to best relate it to the output variable that you want to predict. In this sense neural networks learn a mapping. Mathematically, they are capable of learning any mapping function and have been proven to be a universal approximation algorithm</p><p>We will use Multilayer Perceptron Classifier for our problem at hand. Since it is class of neural network, we will use sklearn to import it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d23b3208bf90495f423dcd1356f06f6/href">https://medium.com/media/7d23b3208bf90495f423dcd1356f06f6/href</a></iframe><p>Let’s look at MLP’s performance metrics using KFold and Stratified KFold</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1ec14fa3c136b6c3a2c2ab1fb95c631/href">https://medium.com/media/f1ec14fa3c136b6c3a2c2ab1fb95c631/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*jPP765zx_WKYyA9mcycVCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*hDpVIyS4xi4js3igVc-LKQ.png" /><figcaption>MLP ROC Curve</figcaption></figure><p>From the three models, we can justify that XGBoost has the best performance compared to the other models with an accuracy score of 85%. However, model performance always depend with the dataset you have. Another way of affecting model performance is through hyperparameter tuning. For example, tuning hyperparameters in XGBoost can be done as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f771317f3e32f7b9e9897f0c9e94f541/href">https://medium.com/media/f771317f3e32f7b9e9897f0c9e94f541/href</a></iframe><h3>Future Work</h3><p>We will look at other machine learning models like SVM and Decision Trees and investigate their performance metrics. We will also perform hyperparameter tuning for our models.</p><p>The whole of this project can be found on my <a href="https://github.com/BrianOdhiambo/Bank-Term-Deposit-Prediction.git">github repo.</a></p><h3>Resources</h3><p>Some of the resources that I find useful for a project like this are:</p><ol><li><a href="https://machinelearningmastery.com/model-based-outlier-detection-and-removal-in-python/">Outlier Detection</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.html">Multilayer Perceptron</a></li><li><a href="https://xgboost.readthedocs.io/en/latest/python/python_api.html">XGBoost</a></li><li><a href="https://www.tutorialspoint.com/machine_learning_with_python/machine_learning_with_python_classification_algorithms_logistic_regression.htm#:~:text=Logistic%20regression%20is%20a%20supervised,be%20only%20two%20possible%20classes.&amp;text=Mathematically%2C%20a%20logistic%20regression%20model,as%20a%20function%20of%20X.">Logistic Regression</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8893903d5672" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Twitter Mining and Analysis on Influential Twitter Users and Africa Government Officials]]></title>
            <link>https://medium.com/@brianodhiambo530/twitter-mining-and-analysis-on-influential-twitter-users-and-africa-government-officials-a61fced65e38?source=rss-abe237d7f4c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a61fced65e38</guid>
            <category><![CDATA[twitter-marketing]]></category>
            <category><![CDATA[twitter-mining]]></category>
            <dc:creator><![CDATA[Brian Odhiambo]]></dc:creator>
            <pubDate>Fri, 24 Jul 2020 07:05:04 GMT</pubDate>
            <atom:updated>2020-07-24T07:05:04.596Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Social media campaigns are mostly driven by influencial individuals in the network and therefore identifying them becomes such a big win. This project was undertaken to find out the most influential twitter users, which hashtags are used, and what parameters are used to identify influential rate of a twitter user. Parameters used for the task were:</p><ul><li>Popularity score: measured by the number of retweets and likes users get</li><li>Reach score: measured by the size of audience a single user has (comprise of followers and the people they follow)</li><li>Relevance score: measured by the number of mentions a single user has.</li></ul><h3>Methodology</h3><h4>Data Extraction</h4><p>Data extraction is the process of getting access to data from its source. The source can be different formats like databases, websites, APIs, electronic devices, forms and many more. In this case I extracted twitter handles for both Africa goverment officials and twitter influencers from the following websites respectively: <a href="https://www.atlanticcouncil.org/blogs/africasource/african-leaders-respond-to-coronavirus-ontwitter/#east-africa">Africa leaders response to Corona virus</a> websites. <a href="https://africafreak.com/100-most-influential-twitter-users-in-africa">Africa Influential TweeterUsers</a> I used beautiful soup for scraping the websites. Beautiful soup is a Python third party library for parsing HTML and XML documents. It creates a parse tree for parsed pages that can be used to extract data from HTML, also known as web scraping. One advantage of beautiful soup is its ability scrape websites that have mulformed markup, i.e., non-closed tags. More information on beautiful soup can be found on its <a href="https://pypi.org/project/beautifulsoup4/">documentation page</a> Other packages used in this project include pandas, matplotlib and seaborn. These packages comes pre-installed when using jupyter notebook.</p><p>The code below shows the data extraction part:</p><pre>#Imports<br>from requests import get from requests.exceptions<br>import RequestException<br>from contextlib import closing<br>from bs4 import BeautifulSoup<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import os, sys     <br>import requests     <br>import urllib.request     <br>import time     <br>import fire     <br>import re</pre><pre># functions for data extraction<br>def simple_get(url):<br>&quot;&quot;&quot;<br>Attempts to get the content at `url` by making an HTTP GET request.<br>If the content-type of response is some kind of HTML/XML, return the<br>text content, otherwise return None.<br>&quot;&quot;&quot;<br>try:     <br>   with closing(get(url, stream=True)) as resp:         <br>     if is_good_response(resp):      <br>       return resp.content #.encode(BeautifulSoup.original_encoding)           <br>     else:      <br>       return None        <br>except RequestException as e:     <br>  log_error(&#39;Error during requests to {0} : {1}&#39;.format(url,str(e)))     <br>  return None</pre><pre>def is_good_response(resp):<br>   &quot;&quot;&quot;<br>   Returns True if the response seems to be HTML, False otherwise.<br>   &quot;&quot;&quot;<br>   content_type = resp.headers[&#39;Content-Type&#39;].lower()<br>   return (resp.status_code == 200<br>           and content_type is not None <br>           and content_type.find(&#39;html&#39;) &gt; -1)</pre><pre>def log_error(e):<br>    &quot;&quot;&quot;<br>    It is always a good idea to log errors. <br>    This function just prints them, but you can<br>    make it do anything.<br>    &quot;&quot;&quot;<br>    print(e)<br>    <br>def get_elements(url, tag=&#39;&#39;,search={}, fname=None):<br>    &quot;&quot;&quot;<br>    Downloads a page specified by the url parameter<br>    and returns a list of strings, one per tag element<br>    &quot;&quot;&quot;<br>    <br>    if isinstance(url,str):<br>        response = simple_get(url)<br>    else:<br>        #if already it is a loaded html page<br>        response = url</pre><pre>if response is not None:<br>        html = BeautifulSoup(response, &#39;html.parser&#39;)<br>        <br>        res = []<br>        if tag:    <br>            for li in html.select(tag):<br>                for name in li.text.split(&#39;\n&#39;):<br>                    if len(name) &gt; 0:<br>                        res.append(name.strip())<br>                       <br>        if search:<br>            soup = html            <br>            <br>            r = &#39;&#39;<br>            if &#39;find&#39; in search.keys():<br>                print(&#39;findaing&#39;,search[&#39;find&#39;])<br>                soup = soup.find(**search[&#39;find&#39;])<br>                r = soup</pre><pre>if &#39;find_all&#39; in search.keys():<br>                print(&#39;finding all of&#39;,search[&#39;find_all&#39;])<br>                r = soup.find_all(**search[&#39;find_all&#39;])<br>   <br>            if r:<br>                for x in list(r):<br>                    if len(x) &gt; 0:<br>                        res.extend(x)<br>            <br>        return res</pre><pre># Raise an exception if we failed to get any data from the url<br>    raise Exception(&#39;Error retrieving contents at {}&#39;.format(url))    <br>    <br>    <br>if get_ipython().__class__.__name__ == &#39;__main__&#39;:<br>    fire(get_tag_elements)</pre><pre># scraping data for the influential twitter users in Africa<br>url = get_elements(&#39;https://africafreak.com/100-most-influential-twitter-users-in-africa&#39;,tag=&#39;h2&#39;)<br>new = pd.DataFrame(res).head(100)<br>new<br>#Data manipulation<br>df1 = new[0].str.split(&#39;.&#39;, expand=True)<br>df1.head(100)<br>df2 = df1[1].str.split(&#39;(&#39;, expand=True)<br>df2.head(100)<br>df2[1] = df2[1].str.strip(&#39;)&#39;)<br>df2.head(100)<br>df2.columns = [&#39;Twitter_name&#39;,&#39;Twitter_handle&#39;]</pre><pre>twitter_handle = df2[&quot;Twitter_handle&quot;].astype(str).tolist()<br>twitter_handle</pre><p>The twitter handles for influential twitter users should be printed when the list is called.</p><p>We repeat the scraping process for Africa government officials</p><pre>`# scraping the data Africa government officials<br>url = get_elements(&#39;https://www.atlanticcouncil.org/blogs/africasource/african-leaders-respond-to-coronavirus-on-twitter/#east-africa&#39;)<br>response = simple_get(url)<br>response = get_elements(response, search={&#39;find_all&#39;:{&#39;class_&#39;:&#39;twitter-tweet&#39;}})<br>twitter_handles_gov = []<br>for tag in response:<br>  if tag.string != None:<br>    twitter_handles_gov.append(tag.string)</pre><pre># getting clean twitter handles<br>my_regex = re.compile(r&#39;@[a-zA-Z0-9_]{0,15}&#39;)<br>tags = &#39;&#39;.join(mystrings)<br>twitter_handles = my_regex.findall(tags)<br>twitter_handles = pd.DataFrame(twitter_handles)<br>twitter_handles.columns = [&quot;Twitter_handle&quot;]<br>twitter_handles_gov = twitter_handles[&quot;Twitter_handles&quot;].astype(str).to_list()</pre><p>By now both the list for goverment twitter handles and influential twitter users should be ready</p><p>The next step is to scrape twitter information for the two lists of the twitter handles. To do this, we will need a very handy library called tweepy. For more tweepy information and installation process, read the documentation <a href="http://docs.tweepy.org/en/latest/">here</a> The code below scrapes the twitter data and does some cleaning on the user’s text.</p><pre>`from __future__ import unicode_literals<br>import sys<br>import os<br>import json<br>import re<br>import string<br>import matplotlib.dates as mdates<br># to view all columns<br>pd.set_option(&quot;display.max.columns&quot;, None)<br># Import the necessary methods from tweepy library<br>import tweepy<br>from tweepy.streaming import StreamListener<br>from tweepy import OAuthHandler<br>from tweepy import Stream<br># Sentiment analysis package<br>from textblob import TextBlob # general text pre-processor<br>import nltk<br>from nltk.corpus import stopwords<br>#nltk.download(&#39;punkt&#39;)<br># tweet pre-processor<br>import preprocessor as p<br>&#39;&#39;&#39;<br>def print_full(x):<br># This is to print nicely DataFrame wide tables<br>pd.set_option(&#39;display.max_rows&#39;, len(x))<br>pd.set_option(&#39;display&#39;)&#39;<br>&#39;&#39;&#39;<br>class tweetsearch():<br>def __init__(self, cols=None, auth=None):<br>if not cols is None:<br>self.cols = cols<br>else:<br>self.cols = [<br>&#39;id&#39;, &#39;created_at&#39;, &#39;source&#39;, &#39;original_text&#39;, &#39;clean_text&#39;,<br>&#39;sentiment&#39;, &#39;polarity&#39;, &#39;subjectivity&#39;,&#39;lang&#39;,&#39;favorite_count&#39;,<br>&#39;retweet_count&#39;,&#39;original_author&#39;, &#39;hashtgs&#39;,&#39;user_mentions&#39;,<br>&#39;followers&#39;, &#39;following&#39;, &#39;place_coordinates&#39;, &#39;place&#39;<br>]<br>if auth is None:<br>consumer_key = os.environ.get(&#39;TWITTER_API_KEY&#39;)<br>consumer_secret = os.environ.get(&#39;TWITTER_API_SECRET&#39;)<br>access_token = os.environ.get(&#39;TWITTER_ACCESS_TOKEN&#39;)<br>access_token_secret = os.environ.get(&#39;TWITTER_ACCESS_TOKEN_SECRET&#39;)<br># This handles Twitter authentication<br>auth = OAuthHandler(consumer_key, consumer_secret)<br>auth.set_access_token(access_token, access_token_secret)<br>self.auth = auth<br>self.api = tweepy.API(auth, wait_on_rate_limit=True)<br>self.filtered_tweet = &#39;&#39;<br>def clean_tweets(self, twitter_text):<br># use pre processor<br>tweet = p.clean(twitter_text)<br>#Happy Emoticons<br>emoticons_happy = set([<br>&#39;:-)&#39;, &#39;:)&#39;, &#39;;)&#39;, &#39;:o)&#39;, &#39;:]&#39;, &#39;:3&#39;, &#39;:c)&#39;, &#39;:&gt;&#39;, &#39;=]&#39;, &#39;8)&#39;, &#39;=)&#39;, &#39;:}&#39;,<br>&#39;:^)&#39;, &#39;:-D&#39;, &#39;:D&#39;, &#39;8-D&#39;, &#39;8D&#39;, &#39;x-D&#39;, &#39;xD&#39;, &#39;X-D&#39;, &#39;XD&#39;, &#39;=-D&#39;, &#39;=D&#39;,<br>&#39;=-3&#39;, &#39;=3&#39;, &#39;:-))&#39;, &quot;:&#39;-)&quot;, &quot;:&#39;)&quot;, &#39;:*&#39;, &#39;:^*&#39;, &#39;&gt;:P&#39;, &#39;:-P&#39;, &#39;:P&#39;, &#39;X-P&#39;,<br>&#39;x-p&#39;, &#39;xp&#39;, &#39;XP&#39;, &#39;:-p&#39;, &#39;:p&#39;, &#39;=p&#39;, &#39;:-b&#39;, &#39;:b&#39;, &#39;&gt;:)&#39;, &#39;&gt;;)&#39;, &#39;&gt;:-)&#39;,<br>&#39;&lt;3&#39;<br>])<br># Sad Emoticons<br>emoticons_sad = set([<br>&#39;:L&#39;, &#39;:-/&#39;, &#39;&gt;:/&#39;, &#39;:S&#39;, &#39;&gt;:[&#39;, &#39;:@&#39;, &#39;:-(&#39;, &#39;:[&#39;, &#39;:-||&#39;, &#39;=L&#39;, &#39;:&lt;&#39;,<br>&#39;:-[&#39;, &#39;:-&lt;&#39;, &#39;=\\&#39;, &#39;=/&#39;, &#39;&gt;:(&#39;, &#39;:(&#39;, &#39;&gt;.&lt;&#39;, &quot;:&#39;-(&quot;, &quot;:&#39;(&quot;, &#39;:\\&#39;, &#39;:-c&#39;,<br>&#39;:c&#39;, &#39;:{&#39;, &#39;&gt;:\\&#39;, &#39;;(&#39;<br>])<br>#Emoji patterns<br>emoji_pattern = re.compile(&quot;[&quot;<br>u&quot;\U0001F600-\U0001F64F&quot; # emoticons<br>u&quot;\U0001F300-\U0001F5FF&quot; # symbols &amp; pictographs<br>u&quot;\U0001F680-\U0001F6FF&quot; # transport &amp; map symbols<br>u&quot;\U0001F1E0-\U0001F1FF&quot; # flags (iOS)<br>u&quot;\U00002702-\U000027B0&quot;<br>u&quot;\U000024C2-\U0001F251&quot;<br>&quot;]+&quot;, flags=re.UNICODE)<br># combine sad and happy emoticons<br>emoticons = emoticons_happy.union(emoticons_sad)<br>stop_words = set(stopwords.words(&#39;english&#39;))<br>word_tokens = nltk.word_tokenize(tweet)<br>tweet = re.sub(r&#39;:&#39;, &#39;&#39;, tweet)<br>tweet = re.sub(r&#39;‚Ä¶&#39;, &#39;&#39;, tweet)<br>#replace consecutive non-ASCII characters with a space<br>tweet = re.sub(r&#39;[^\x00-\x7F]+&#39;,&#39; &#39;, tweet)<br>#remove emojis from tweet<br>tweet = emoji_pattern.sub(r&#39;&#39;, tweet)<br>#filter using NLTK library append it to a string<br>filtered_tweet = [w for w in word_tokens if not w in stop_words]<br># looping through conditions<br>filtered_tweet = []<br>for w in word_tokens:<br># check tokens againts stop words, emoticons and punctuations<br>if w not in stop_words and w not in emoticons and w not in string.punctuation:<br>filtered_tweet.append(w)<br>return &#39; &#39;.join(filtered_tweet)<br>def get_tweets(self, name, csvfile=None):<br>df = pd.DataFrame(columns=self.cols)<br>if not csvfile is None:<br># If the file exists, then read the existing data from the CSV file<br>if os.path.exists(csvfile):<br>df = pd.read_csv(csvfile, header=0)<br># page attribute in tweepy.cursor and iteration<br>for page in tweepy.Cursor(self.api.user_timeline, id=name).pages(1):<br>for status in page:<br>new_entry = []<br>status = status._json<br># filter by language<br>#if status[&#39;lang&#39;] != &#39;en&#39;:<br># continue<br># if this tweet is a retweet update retweet count<br>if status[&#39;created_at&#39;] in df[&#39;created_at&#39;].values:<br>i = df.loc[df[&#39;created_at&#39;] == status[&#39;created_at&#39;]].index[0]<br>cond1 = status[&#39;favorite_count&#39;] != df.at[i, &#39;favorite_count&#39;]<br>cond2 = status[&#39;retweet_count&#39;] != df.at[i, &#39;retweet_count&#39;]<br>if cond1 or cond2:<br>df.at[i, &#39;favorite_count&#39;] = status[&#39;favorite_count&#39;]<br>df.at[i, &#39;retweet_count&#39;] = status[&#39;retweet_count&#39;]<br>continue<br># calculate sentiment<br>filtered_tweet = self.clean_tweets(status[&#39;text&#39;])<br>blob = TextBlob(filtered_tweet)<br>Sentiment = blob.sentiment<br>polarity = Sentiment.polarity<br>subjectivity = Sentiment.subjectivity<br>new_entry += [status[&#39;id&#39;], status[&#39;created_at&#39;],<br>status[&#39;source&#39;], status[&#39;text&#39;], filtered_tweet,<br>Sentiment, polarity, subjectivity, status[&#39;lang&#39;],<br>status[&#39;favorite_count&#39;], status[&#39;retweet_count&#39;]]<br>new_entry.append(status[&#39;user&#39;][&#39;screen_name&#39;])<br>hashtags = &quot;, &quot;.join([hashtag_item[&#39;text&#39;] for hashtag_item in status[&#39;entities&#39;][&#39;hashtags&#39;]])<br>new_entry.append(hashtags) # append the hashtags<br>mentions = &quot;, &quot;.join([mention[&#39;screen_name&#39;] for mention in status[&#39;entities&#39;][&#39;user_mentions&#39;]])<br>new_entry.append(mentions) # append user mentions<br>try:<br>followers = status[&#39;user&#39;][&#39;followers_count&#39;]<br>except TypeError:<br>followers = None<br>new_entry.append(followers)<br>try:<br>following = status[&#39;user&#39;][&#39;friends_count&#39;]<br>except TypeError:<br>following = None<br>new_entry.append(following)<br>try:<br>xyz = status[&#39;place&#39;][&#39;bounding_box&#39;][&#39;coordinates&#39;]<br>coordinates = [coord for loc in xyz for coord in loc]<br>except TypeError:<br>coordinates = None<br>new_entry.append(coordinates)<br>try:<br>location = status[&#39;user&#39;][&#39;location&#39;]<br>except TypeError:<br>location = &#39;&#39;<br>new_entry.append(location)<br># appending a row to the data frame<br>single_user_df = pd.DataFrame([new_entry], columns=self.cols)<br>df = df.append(single_user_df, ignore_index=True)<br>if not csvfile is None:<br>df.to_csv(csvfile, columns=self.cols, index=False, encoding=&quot;utf-8&quot;)<br>return df</pre><p>Since we now have a twitter data in dataframes, we can do some data processing in the next step.</p><h3>Data Cleaning</h3><p>Since the data was not all clean, some of the cleaning tasks like removing emojis and non-text symbols was necessary. The code below did the functionality</p><pre>`def clean_tweets(self, twitter_text):<br># use pre processor<br>tweet = p.clean(twitter_text)<br>#Happy Emoticons<br>emoticons_happy = set([<br>&#39;:-)&#39;, &#39;:)&#39;, &#39;;)&#39;, &#39;:o)&#39;, &#39;:]&#39;, &#39;:3&#39;, &#39;:c)&#39;, &#39;:&gt;&#39;, &#39;=]&#39;, &#39;8)&#39;, &#39;=)&#39;, &#39;:}&#39;,<br>&#39;:^)&#39;, &#39;:-D&#39;, &#39;:D&#39;, &#39;8-D&#39;, &#39;8D&#39;, &#39;x-D&#39;, &#39;xD&#39;, &#39;X-D&#39;, &#39;XD&#39;, &#39;=-D&#39;, &#39;=D&#39;,<br>&#39;=-3&#39;, &#39;=3&#39;, &#39;:-))&#39;, &quot;:&#39;-)&quot;, &quot;:&#39;)&quot;, &#39;:*&#39;, &#39;:^*&#39;, &#39;&gt;:P&#39;, &#39;:-P&#39;, &#39;:P&#39;, &#39;X-P&#39;,<br>&#39;x-p&#39;, &#39;xp&#39;, &#39;XP&#39;, &#39;:-p&#39;, &#39;:p&#39;, &#39;=p&#39;, &#39;:-b&#39;, &#39;:b&#39;, &#39;&gt;:)&#39;, &#39;&gt;;)&#39;, &#39;&gt;:-)&#39;,<br>&#39;&lt;3&#39;<br>]) # Sad Emoticons<br>emoticons_sad = set([<br>&#39;:L&#39;, &#39;:-/&#39;, &#39;&gt;:/&#39;, &#39;:S&#39;, &#39;&gt;:[&#39;, &#39;:@&#39;, &#39;:-(&#39;, &#39;:[&#39;, &#39;:-||&#39;, &#39;=L&#39;, &#39;:&lt;&#39;,<br>&#39;:-[&#39;, &#39;:-&lt;&#39;, &#39;=\\&#39;, &#39;=/&#39;, &#39;&gt;:(&#39;, &#39;:(&#39;, &#39;&gt;.&lt;&#39;, &quot;:&#39;-(&quot;, &quot;:&#39;(&quot;, &#39;:\\&#39;, &#39;:-c&#39;,<br>&#39;:c&#39;, &#39;:{&#39;, &#39;&gt;:\\&#39;, &#39;;(&#39;<br>])<br>#Emoji patterns<br>emoji_pattern = re.compile(&quot;[&quot;<br>u&quot;\U0001F600-\U0001F64F&quot; # emoticons<br>u&quot;\U0001F300-\U0001F5FF&quot; # symbols &amp; pictographs<br>u&quot;\U0001F680-\U0001F6FF&quot; # transport &amp; map symbols<br>u&quot;\U0001F1E0-\U0001F1FF&quot; # flags (iOS)<br>u&quot;\U00002702-\U000027B0&quot;<br>u&quot;\U000024C2-\U0001F251&quot;<br>&quot;]+&quot;, flags=re.UNICODE)<br># combine sad and happy emoticons<br>emoticons = emoticons_happy.union(emoticons_sad)<br>stop_words = set(stopwords.words(&#39;english&#39;))<br>word_tokens = nltk.word_tokenize(tweet)<br>tweet = re.sub(r&#39;:&#39;, &#39;&#39;, tweet)<br>tweet = re.sub(r&#39;‚Ä¶&#39;, &#39;&#39;, tweet)<br>#replace consecutive non-ASCII characters with a space<br>tweet = re.sub(r&#39;[^\x00-\x7F]+&#39;,&#39; &#39;, tweet)<br>#remove emojis from tweet<br>tweet = emoji_pattern.sub(r&#39;&#39;, tweet)<br>#filter using NLTK library append it to a string<br>filtered_tweet = [w for w in word_tokens if not w in stop_words]<br># looping through conditions<br>filtered_tweet = []<br>for w in word_tokens:<br># check tokens againts stop words, emoticons and punctuations<br>if w not in stop_words and w not in emoticons and w not in string.punctuation:<br>filtered_tweet.append(w)<br>return &#39; &#39;.join(filtered_tweet)</pre><h3>Data Analysis and Visualizations</h3><p>Data analysis helped in getting some insights about the trends in the datasets obtained. For both influential twitter users and government officials, insights on reach score, popularity score and relevance score could be attained. For example, finding popularity score, I examined the favorite count and retweet count for a particular twitter user, and grouping the two attributes resulted to a popularity score for a particular score.</p><pre>`# Creating a sample dataframe containing the columns : favorite_count, retweet_count and original_author<br>popularity_df = df_influencer[[&#39;original_author&#39;,&#39;favorite_count&#39;,&#39;retweet_count&#39;]]<br># Grouping the columns using original author and finding summation<br>popularity_df = popularity_df.groupby([&#39;original_author&#39;])[&#39;favorite_count&#39;, &#39;retweet_count&#39;].sum()<br># Finding a total of favorite and retweet counts per author<br>popularity_col = popularity_df[&#39;favorite_count&#39;] + popularity_df[&#39;retweet_count&#39;]<br># Creating a column for the summation of favorite and retweet counts per author.<br>popularity_df[&quot;popularity_col&quot;] = popularity_col<br># Sorting the dataframe with the popularity column<br>pop_score_twitter_influencers = popularity_df.sort_values(&quot;popularity_col&quot;, ascending=False)</pre><p>Visualizations below shows comparisons of the metric on both government officials and influencial twitter users.</p><h4>Popularity score for Africa goverment officials and Africa twitter influencers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xk1iF3oAZhPoLQt-UanguQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDUL9bAUbSfdABJdWgX0Sg.png" /></figure><p>For the reach score metric, a combination for both followers and followng attributes for a single user was a examined.</p><pre>`# Creating a sample dataframe containing the columns : followers, following and original_author<br>reach_df = df_influencer[[&#39;original_author&#39;,&#39;followers&#39;,&#39;following&#39;]]<br># Grouping the columns using original author and finding summation<br>reach_df = reach_df.groupby([&#39;original_author&#39;])[&#39;followers&#39;, &#39;following&#39;].sum()<br># Finding a total of followers and following counts per author<br>reach_col = reach_df[&#39;followers&#39;] + reach_df[&#39;following&#39;]<br># Creating a column for the summation of followers and following counts per author.<br>reach_df[&quot;reach_col&quot;] = reach_col<br># Sorting the dataframe with the popularity column<br>reach_score_twitter_influencers = reach_df.sort_values(&quot;reach_col&quot;, ascending=False)<br>Visualizations for the reach score metric</pre><h4>Reach score for Africa goverment officials and Africa twitter influencers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bul1wlJPIF05uEiqBvpLEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynM_QU-8VZ2qxRrEwJe-cQ.png" /></figure><p>Relevance score was determined by the number of mentions a user gets in other tweets.</p><pre>`relevance_df = df_influencer[[&#39;original_author&#39;,&#39;user_mentions&#39;]]<br>relevance_df = relevance_df.groupby(&#39;original_author&#39;).count()<br>rel_score_twitter_influencers = relevance_df.sort_values(&#39;user_mentions&#39;, ascending=False)<br>rel_score_twitter_influencers = rel_score_twitter_influencers .reset_index()<br>rel_score_twitter_influencers</pre><p>The visualization for this metric is displayed below</p><h4>Relevance score for Africa goverment officials and Africa twitter influencers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*juCDAX5zhdbEn4puKaiLvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCqEuyQPChW1VvDQR9dE8Q.png" /></figure><h3>Conclusion and Recommendation</h3><p>Retweet influence, mentions influence and indegree influence have big a role to play in determining the level of influence a user has on the society and its environment. And this is a strength that can be tapped into and utilized by businesses to push products and services through campaigns by partnering with the most influential users through marketing and advertising. This is dependent on the category of the content of the user. I would recommend other factors that determine a user’s influence to be factored in determining if one is more influential other than the use of the three ranks of measuring influence. For instance, the interpersonal relationship of a user with the virtual community can be considered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a61fced65e38" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>