<?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 Anastasia Kiiru on Medium]]></title>
        <description><![CDATA[Stories by Anastasia Kiiru on Medium]]></description>
        <link>https://medium.com/@kiiru.anastasia?source=rss-80158a505cc5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3FPYjKfPlrWGBMB0d9MWDA.jpeg</url>
            <title>Stories by Anastasia Kiiru on Medium</title>
            <link>https://medium.com/@kiiru.anastasia?source=rss-80158a505cc5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:20:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kiiru.anastasia/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[Pre-Processing and Model Training using Python]]></title>
            <link>https://medium.com/analytics-vidhya/pre-processing-and-model-training-using-python-174ed43dd8bb?source=rss-80158a505cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/174ed43dd8bb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pre-processing]]></category>
            <category><![CDATA[model-training]]></category>
            <category><![CDATA[data-pre-processing]]></category>
            <dc:creator><![CDATA[Anastasia Kiiru]]></dc:creator>
            <pubDate>Sat, 29 Aug 2020 22:01:39 GMT</pubDate>
            <atom:updated>2020-08-31T13:38:03.603Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding data pre-processing and it’s importance in model training</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OxpYWxBSblfO-6kD" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Pre-processing and model training go hand in hand in machine learning to mean that one cannot do without the other. The thing is, we humans interact with data we can understand, that is data written in natural language, and we expect our machine learning models to take in the same data and give us some insights. Well, machines only understand binary language (0s and 1s) and there must be a way for the machines to understand this same data. That’s where pre-processing comes in. Pre-processing is basically transforming the data in natural language to a form the machine can understand. This process is also referred to as encoding.</p><p>So how do we do pre-processing and model training to get insights from data? There are multiple ways to pre-process data and train machine learning models, for sure I don’t know all of them. In this post, we’ll look at some of the pre-processing methods and explore three machine learning algorithms we can use to train a model. Therefore, we’ll look into:</p><p><strong>Pre-Processing</strong></p><ul><li>Data Cleaning</li><li>Categorical features encoding using OneHotEncoder</li><li>Numerical features scaling using StandardScaler</li><li>Dimensionality reduction using PCA, T-SNE and Autoencoders</li><li>Balancing classes by oversampling</li><li>Feature Extraction</li></ul><p><strong>Model Training</strong></p><ul><li>Logistic Regression</li><li>Random Forests</li><li>Decision Trees</li></ul><p>For this post, we will be using bank campaign data which can be found <a href="http://archive.ics.uci.edu/ml/datasets/Bank+Marketing">here</a>. In addition to the data, the source gives a full description of the features in the data. In brief, our data consist of 20 features describing a customer, 10 categorical features and 10 numerical features, and the target variable. Our target variable is a representation of whether a customer subscribed to a term deposit or not. The goal of this project would be to predict on which future customers will subscribe to the term deposits. For a full Exploratory Data Analysis of our dataset you can check <a href="https://dub01.online.tableau.com/t/multipleviews/views/Kiiru-Anastasia_Bank_Data_EDA/EDAforTermDepositSubscriptionsY?:showAppBanner=false&amp;:display_count=n&amp;:showVizHome=n&amp;:origin=viz_share_link">my Tableau Dashboard</a> or go through the same on <a href="https://github.com/Kiiru-Anastasia/10acadWeeklyChallenges/blob/master/Week6/notebooks/Term_Deposit.Predictive_Model.ipynb">this GitHub repository</a>. This post will only focus on pre-processing and model training.</p><h3>Pre-Processing</h3><h4>Data Cleaning</h4><p>Data cleaning involves checking for missing values in a dataset and dropping the null rows or imputing the missing values depending on how many they are and their significance in our data. Data cleaning also involves looking for duplicates in our data and dropping them as they may significantly affect the effectiveness of the model. Data cleaning also involves checking for outliers in our data and replacing the data with median or mean based on how frequent they occur. This are just some of the few ways of data cleaning that we will explore in this post.</p><p><strong>Missing Values</strong></p><p>We can check for missing values in our data by calling dataset.info() and inspecting all the features in our dataset or simply running dataset.isnull().values.any() which will return True if there’s any null values in our dataset or False if there is none. We can then decide to drop values which contain unique data, or impute categorical features with mode data and numerical features with mean data. Our bank dataset has no missing values and we therefore, proceed to the next step.</p><p><strong>Duplicated Data</strong></p><p>Check for duplicated rows in your data using dataset[dataset.duplicated()] . Our bank data has 12 duplicated rows, therefore, we can go ahead and drop the rows using dataset = dataset.drop_duplicates() and assigning the resulting data to our dataset variable as the new dataset.</p><p><strong>Outlier Detection</strong></p><p>It is easy to detect outliers in numerical features by simply ploting a box plot of the features. I have defined a function that can help you plot all the boxplots of your numerical features, you just have to pass your dataset and the name of the features to the function. The function is:</p><pre>def plot_outliers(data, features):<br>    fig, ax = plt.subplots(len(features), figsize = (8, 40))<br>    <br>    for i, feature in enumerate(features):<br>        sns.boxplot(y = data[feature], ax = ax[i])<br>        ax[i].set_title(&#39;Box plot - {}&#39;.format(feature), fontsize = 10)<br>        ax[i].set_xlabel(feature, fontsize = 8)<br>    <br>    plt.show()</pre><p>We can then go ahead and replace the outliers with median value if the outliers are many and with the mean value if the outliers are not many. The following function will automate this process for you. You just need to pass in your data, the features with outliers to be replaced and indicate whether you’re replacing with mean or with median.</p><pre>def replace_outlier(data, features, with_median=False, with_mean=False):<br>    for feature in features:<br>        Q1 = data[feature].quantile(0.25)<br>        Q3 = data[feature].quantile(0.75)<br>    <br>        median = data[feature].quantile(0.50)<br>        mean = data[feature].mean()<br>    <br>        IQR = Q3 - Q1<br>    <br>        upper_whisker = Q3 + (1.5 * IQR)<br>        lower_whisker = Q1 - (1.5 * IQR)<br>    <br>        if with_median:<br>            data[feature] = np.where(data[feature] &gt; upper_whisker, median, data[feature])<br>            data[feature] = np.where(data[feature] &lt; lower_whisker, median, data[feature])<br>    <br>        if with_mean:<br>            data[feature] = np.where(data[feature] &gt; upper_whisker, mean, data[feature])<br>            data[feature] = np.where(data[feature] &lt; lower_whisker, mean, data[feature])</pre><h4>Categorical Features Encoding using OneHotEncoder</h4><p>Encoding of categorical features is done by transforming the categorical values to binary values. OneHotEncoder achieves this by creating a separate column with binary values for each category in a feature. In the new column, the value 1 represents that the catogory is present and 0 indicates its absence. For instance in our bank data, one of the categorical features is marital which has four possible categories; ‘married’, ‘single’, ‘divorced’ and ‘unknown’. For each of these categories, OneHotEncoder creates a new column and uses 1 where the category was present and 0 for otherwise.</p><p>OneHotEncoding can be achieved through a number of ways such as using get_dummies in pandas. However, this post will use CountVectorizer, a better approach in comparison to get_dummies since get_dummies returns data with different dimensions.</p><p>Once again, using the following functions you can easily OneHotEncode your categorical features, you only need to pass in the naes of your categorical features, the X_train set and the X_test set.</p><pre>from sklearn.feature_extraction.text import CountVectorizer</pre><pre>def add_onehot_to_dataframe(sparse, df, vectorizer, name):<br>  &#39;&#39;&#39;<br>  This function will add the one hot encoded to the dataframe.<br>  &#39;&#39;&#39;<br>  for i, col in enumerate(vectorizer.get_feature_names()):<br>    colname = name+&quot;_&quot;+col<br>    # df[colname] = pd.SparseSeries(sparse[:, i].toarray().flatten(), fill_value=0)<br>    df[colname] = sparse[:, i].toarray().ravel().tolist()<br>  <br>  return df</pre><pre>def OneHotEncoder(categorical_cols, X_train, X_test):<br>  &#39;&#39;&#39;<br>    This function takes categorical column names as inputs. The objective of this function is to take the column names iteratively and encode the features using One hot Encoding mechanism and also adding the encoded feature to the respective dataframe.<br>  &#39;&#39;&#39;</pre><pre>for i in categorical_cols:<br>    Vectorizer = CountVectorizer(token_pattern=&quot;[A-Za-z0-9-.]+&quot;)<br>    print(&quot;Encoding for feature: &quot;, i)<br>    # Encoding training dataset <br>    temp_cols = Vectorizer.fit_transform(X_train[i])<br>    X_train = add_onehot_to_dataframe(temp_cols, X_train, Vectorizer, i)</pre><p># Encoding Test dataset<br> temp_cols = Vectorizer.transform(X_test[i])<br> X_test = add_onehot_to_dataframe(temp_cols, X_test, Vectorizer, i)</p><h4>Numerical Features Scaling using StandardScaler()</h4><p>Each numerical feature in a dataset is usually measured on different scales and this may cause some biasness while training the model. Therefore it is advisable to always normalize your data by either using MinMaxScaler() or StandardScaler() In this post, we will use the StandardScaler() with the code snippet below to achieve normalization in our numerical features.</p><pre>from sklearn.preprocessing import StandardScaler<br>    <br>scaler = StandardScaler()</pre><pre>numerical_cols = [&#39;age&#39;, &#39;duration&#39;, &#39;campaign&#39;, &#39;pdays&#39;, &#39;previous&#39;, &#39;emp.var.rate&#39;, &#39;cons.price.idx&#39;, &#39;cons.conf.idx&#39;, &#39;euribor3m&#39;, &#39;nr.employed&#39;]<br>    <br>#normalizing train set<br>X_train = X_train.reset_index()<br>temp_df = X_train.filter(numerical_cols, axis = 1)<br>X_train = X_train.drop(numerical_cols, axis = 1)<br>   <br>cols = temp_df.values<br>    <br>temp_cols = scaler.fit_transform(cols)<br>temp_df = pd.DataFrame(temp_cols, columns = numerical_cols)<br>X_train = X_train.merge(temp_df, left_index=True, right_index=True)<br>X_train = X_train.drop([&#39;index&#39;], axis=1)<br>    <br>#normalizing test set<br>X_test = X_test.reset_index()<br>temp_df = X_test.filter(numerical_cols, axis = 1)<br>X_test = X_test.drop(numerical_cols, axis = 1)<br>    <br>cols = temp_df.values<br>    <br>temp_cols = scaler.fit_transform(cols)<br>temp_df = pd.DataFrame(temp_cols, columns = numerical_cols)<br>X_test = X_test.merge(temp_df, left_index=True, right_index=True)<br>X_test = X_test.drop([&#39;index&#39;], axis=1)</pre><h4>Dimensionality Reduction</h4><p>This pre-processing technique involves transforming high dimensional data to a low dimensional data while still maintaining a good representation of the entire dataset. There are several dimensionality reduction techniques but this post will only go through PCA (Principal Component Analysis), t-SNE (t-distributed Stochastic Neighbor Embedding) and Autoencoders.</p><p><strong>PCA (Principal Component Analysis)</strong></p><p>The following code reduced the dimension of our data to a 2D. the n_components attribute is the section used to specify the number of components the data should be reduced to.</p><pre>from sklearn.decomposition import PCA</pre><pre>pca = PCA(n_components=2)<br>X_pca_2train = pca.fit_transform(X_train)<br>PCA_df_2train = pd.DataFrame(data = X_pca_2train, columns = [&#39;PC1&#39;, &#39;PC2&#39;])<br>PCA_df_2train = pd.concat([PCA_df_2train, y_train], axis = 1)</pre><p>PCA also offers a way of inspecting the variance ratio preserved by the selected components and this can be done through : pca.explained_variance_ratio_ For our code above the output of this variance is out[]: [0.29620347 0.09104375] indicating that 29.62% of our data is represented by component 1 and only 9.10% is represented by component 2.</p><p>We can also plot the resulting distribution of our PCA using the following code:</p><pre>plt.figure(figsize=(8, 8))</pre><pre>classes = [1, 0]<br>colors = [&#39;r&#39;, &#39;b&#39;]<br>for clas, color in zip(classes, colors):<br>    plt.scatter(PCA_df_2train.loc[PCA_df_2train[&#39;y&#39;] == clas, &#39;PC1&#39;], <br>                PCA_df_2train.loc[PCA_df_2train[&#39;y&#39;] == clas, &#39;PC2&#39;], <br>                c = color)<br>    <br>plt.xlabel(&#39;Principal Component 1&#39;, fontsize = 12)<br>plt.ylabel(&#39;Principal Component 2&#39;, fontsize = 12)<br>plt.title(&#39;2D PCA&#39;, fontsize = 15)<br>plt.legend([&#39;Subscription&#39;, &#39;No Subscription&#39;])<br>plt.grid()</pre><p>The above code gave us the following plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*OQiz-wsla3dCpirAgLLgzA.png" /><figcaption>Image by author</figcaption></figure><p>You can see from the above plot that the distinction between the two outputs is not as clear and therefore using two components may not be the best option.</p><p>To get the ideal number of components to use for your dimensionality reduction you can use PCA without asigning a value to n_components and plot the explained variance ratio of the data as illustred by the code snippet below:</p><pre>pca = PCA()<br>pca_data = pca.fit_transform(X_train)<br>plt.plot(np.cumsum(pca.explained_variance_ratio_))<br>plt.xlabel(&#39;number of components&#39;)<br>plt.ylabel(&#39;cumulative explained variance&#39;)</pre><p>This code resulted in the following plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*ZwwJrj21mgEyb3e1cFl5DQ.png" /><figcaption>Image by author</figcaption></figure><p>We can see from the above plot that using close to 30 components is what will give us 100% representation of the data. 10 componenets also have a good representation at nearly 80%. After analyzing this plot you can then run PCA again, this time assigning n_components to the ideal number of components for better data representation.</p><p><strong>t-SNE (t-distributed Stochastic Neighbor Embedding)</strong></p><p>Unlike PCA, t-SNE is a non-linear dimensionality reduction technique. To apply t-SNE dimensionality reduction to your data, use the following code snippet and specify the number of components using n_components.</p><pre>tsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=300)<br>X_tsne_2train = tsne.fit_transform(X_train)</pre><p>To inspect the distribution of the t-SNE using visualization use the following code:</p><pre>plt.figure(figsize=(8,8))<br>plt.scatter(X_tsne_2train[:, 0], X_tsne_2train[:, 1], c=y_train.values)<br>plt.show()</pre><p>The above code gives us a plot like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*E5bXpsO3E6tQmToO0HBHVA.png" /><figcaption>Image by author</figcaption></figure><p>The distinction is also not as clear between the two classes just as indicated by PCA and it might therefore be better using more components.</p><p><strong>Autoencoders</strong></p><p>Autoencoders are machine learning algorithms which can be used for dimensionality reduction. They use non-linear transformations to project data from high dimensions to lower dimensions. There are different types of autoencoders such as; Variational Autoencoder, Convolutional Autoencoder, Denoising Autoencoder, and Sparse Autoencoder. In this post, we’ll just build a basic Autoencoder which contains 2 main components: encoder and decoder.</p><p>Autoencoders use Keras API in python, therefore, ensure you have Keras and tensorflow installed in your environment before running the following code. Installation of the two can easily be done on Jupyter notebook by running !pip install keras and !pip install tensorflow for python 3.7 and anaconda3 environment.</p><pre>from keras.layers import Input, Dense<br>from keras.models import Model</pre><pre>X = pd.concat([X_train, X_test], ignore_index=True)</pre><pre>input_layer = Input(shape=(X.shape[1],))<br>encoded = Dense(3, activation=&#39;relu&#39;)(input_layer)<br>decoded = Dense(X.shape[1], activation=&#39;softmax&#39;)(encoded)<br>autoencoder = Model(input_layer, decoded)<br>autoencoder.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;)</pre><pre>X1, X2, Y1, Y2 = train_test_split(X, X, test_size=0.3, random_state=101)</pre><pre>autoencoder.fit(X1, Y1,<br>                epochs=100,<br>                batch_size=300,<br>                shuffle=True,<br>                verbose = 30,<br>                validation_data=(X2, Y2))</pre><pre>encoder = Model(input_layer, encoded)<br>X_ae3 = encoder.predict(X)</pre><p>Notice that I concat my train and test set because Autoencoders take the input feature (X) as both the feature and the label. We’ve also used ReLu activation function for our encoder and Softmax for our decoder to achieve a non-linear transformation.</p><h4>Balancing Classes by Oversampling</h4><p>From our data exploration, we noticed that our target variable was imbalanced with a ratio of 89:11 for no subscription to subscription. Class imbalance also affectcs model training and we’ll therefore have to balance our target variable. Some ML algorithms like the Logistic Regression algorithms comes with an attribute for balancing the class; that is LogisticRegression(class_weight=&#39;balanced&#39;) and we can use this option for such models, otherwise, we have to balance our clases by other methods such as undersamplin and oversampling. In this scenario will use use SMOTE to oversample our class as shown in the code below:</p><pre>from imblearn.over_sampling import SMOTE</pre><pre>os = SMOTE(random_state = 0)</pre><pre>columns = X_train.columns<br>os_data_X, os_data_y = os.fit_sample(X_train, y_train)<br>os_data_X = pd.DataFrame(data=os_data_X, columns=columns)<br>os_data_y = pd.DataFrame(data=os_data_y, columns=[&#39;y&#39;])</pre><h4>Feature Extraction</h4><p>Feature extraction involves selecting a few features from the entire dataset to be used for model training. This features are selected based on their importance in predicting the target variable. This post will explore RFE method for feature extraction. The code below selects the top 20 important features by repeatedly fiting the training data and seleceting the top feature then droping it in the next round until 20 features are selected.</p><pre>from sklearn.feature_selection import RFE</pre><pre>rfe = RFE(logreg, n_features_to_select=20)<br>rfe = rfe.fit(X_train, y_train)<br>rank = rfe.ranking_</pre><h3>Model Training</h3><p>Next we move on to model training where we will explore three machine learning algorithms as listed earlier.</p><h4>Logistic Regression</h4><p>First, it is important to note that for our dataset, the ‘duration’ column should not be used for model training, therefore, we drop it from our training data simply by using the following code:</p><pre>#Removing duration feature from dataset</pre><pre>#From train<br>X_train = X_train.drop(&#39;duration&#39;, axis=1)</pre><pre>#From test<br>X_test = X_test.drop(&#39;duration&#39;, axis=1)</pre><p>Then we apply a logistic regression algorithm to our data. Remember, this model has an inbuilt method for handling imbalanced data and therefore, we’ll use it.</p><pre>from sklearn.linear_model import LinearRegression</pre><pre>logreg = LogisticRegression(class_weight=&#39;balanced&#39;)<br>logreg.fit(X_train, y_train)<br>y_pred_logreg = logreg.predict_proba(X_test)</pre><p>We can test the accuracy of our model by using the ROC (Receiver Operating Characteristic) score</p><pre>from sklearn.metrics import roc_auc_score</pre><pre>print(&#39;AUC score without duration columns : &#39;, roc_auc_score(y_test, y_pred_logreg[:, 1]))</pre><p>We can also plot the ROC curve for more insights from the model using the code below.</p><pre>from sklearn.metrics import roc_curve</pre><pre>logit_roc_auc = roc_auc_score(y_test, logreg.predict(X_test))<br>fpr, tpr, thresholds = roc_curve(y_test, logreg.predict_proba(X_test)[:,1])<br>plt.figure()<br>plt.plot(fpr, tpr, label=&#39;Logistic Regression (area = %0.2f)&#39; % logit_roc_auc)<br>plt.plot([0, 1], [0, 1],&#39;r--&#39;)<br>plt.xlim([0.0, 1.0])<br>plt.ylim([0.0, 1.05])<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.title(&#39;Receiver operating characteristic&#39;)<br>plt.legend(loc=&quot;lower right&quot;)<br>plt.savefig(&#39;Log_ROC&#39;)<br>plt.show()</pre><p>The above code generates the following plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*FdfpWz5TNzzVa9YSeus-oQ.png" /><figcaption>Image by author</figcaption></figure><p>The dotted line is a representation of a ROC curve for a purely random classifier. A good classifier should be far from this line.</p><h4>Random Forests</h4><p>Random forests are among the classifiers that come with the scikit-learn library, therefore, to run this model we just call the classifier form the library as shown below:</p><pre>from sklearn.ensemble import RandomForestClassifier</pre><pre>rfclf = RandomForestClassifier(class_weight=&#39;balanced&#39;, max_depth=2, random_state=0)<br>rf_model = rfclf.fit(X_train, y_train)</pre><pre>y_pred_rf=rfclf.predict(X_test)</pre><p>We can test the accuracy of the model by generating a confusion matrix as well as computing Accuracy, Precision, Recall, Fmeasure and support as shown below:</p><pre>target = np.array(y_test)<br>rf_prediction = np.array(y_pred_rf)</pre><pre>print(&#39;Confusion matrix : &#39;, confusion_matrix(target, rf_prediction))<br>print(classification_report(y_test, y_pred_rf))</pre><h4>Decision Trees</h4><p>Decision trees also come with the scikit-library, therefore, implmenting a decision tree model is as easy as importing the library and fitting your training data as shown below:</p><pre>from sklearn.tree import DecisionTreeClassifier</pre><pre>dt = DecisionTreeClassifier(class_weight=&#39;balanced&#39;)</pre><pre>dt_model = dt.fit(X_train, y_train)</pre><pre>y_pred_dt = dt.predict(X_test)</pre><p>Just like the Random forests, we can also test the accuracy of our decision tree model by generating a confusion matrix and computing the Accuracy, Recall, Precision, Fmeasure and Support.</p><p>The post gives a general overview of data pre-processing and model training in machine learning. It has provided a number of ways to perform pre-processing on data and explained how and when to use them. The post has also touched on three machine learning algorithms which can be used for model training and the basics in running the model with these algorithms as well as different ways of getting the accuracy of the model. To follow with the code, you can download the data used in the links provided or access the full code in the GitHub link provided.</p><h3>References</h3><p>[1]: L. Susan, <em>Building a logistic regression in python, step by step</em> (2017), <a href="https://towardsdatascience.com/building-a-logistic-regression-in-python-step-by-step-becd4d56c9c8">https://towardsdatascience.com/building-a-logistic-regression-in-python-step-by-step-becd4d56c9c8</a></p><p>[2]: R.Sukanta, <em>Machine Learning case study: A data-driven approach to predict the success of bank telemarketing</em> (2019), <a href="https://towardsdatascience.com/machine-learning-case-study-a-data-driven-approach-to-predict-the-success-of-bank-telemarketing-20e37d46c31c">https://towardsdatascience.com/machine-learning-case-study-a-data-driven-approach-to-predict-the-success-of-bank-telemarketing-20e37d46c31c</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=174ed43dd8bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/pre-processing-and-model-training-using-python-174ed43dd8bb">Pre-Processing and Model Training using Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scrapping, Downloading Twitter Data, and Performing Sentimental Analysis using Python]]></title>
            <link>https://medium.com/data-science/web-scrapping-downloading-twitter-data-and-performing-sentimental-analysis-using-python-fce3ea45c825?source=rss-80158a505cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/fce3ea45c825</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <dc:creator><![CDATA[Anastasia Kiiru]]></dc:creator>
            <pubDate>Fri, 24 Jul 2020 22:14:19 GMT</pubDate>
            <atom:updated>2020-07-25T21:54:55.580Z</atom:updated>
            <content:encoded><![CDATA[<h3>Web Scrapping, Downloading Twitter Data and Performing Sentimental Analysis using Python</h3><h4>Using data to segment African influencers to drive a marketing decision.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5JjjdPo3qosoqa-o" /><figcaption>Photo by <a href="https://unsplash.com/@srd844?utm_source=medium&amp;utm_medium=referral">Stephen Dawson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Social media influencers play an important role in the current society of increasing human interconnection; and business organizations are realizing the need for influencer marketing campaigns (Newberry, 2019). A successful influencer marketing campaign requires a partnership with the right social media influencer. So how do we determine the right influencer?</p><p>For the data science community, only data has the answer. Let’s take a case study for determining the right influencers from Africa to partner with, for a digital marketing campaign. We will explore scrapping of data from relevant websites, data extraction from twitter for specific users, and perform sentimental analysis to determine the right influencers to partner with.</p><h3>Web Scrapping</h3><p><a href="https://africafreak.com/100-most-influential-twitter-users-in-africa">This</a> website has a predetermined list of 100 influential individuals in Africa and <a href="https://www.atlanticcouncil.org/blogs/africasource/african-leaders-respond-to-coronavirus-on-twitter/#east-africa">this</a> website has the list to key government officials in Africa. To scrap these two websites, we first import the necessary libraries:</p><pre>from requests import get<br>from requests.exceptions import RequestException<br>from contextlib import closing<br>from bs4 import BeautifulSoup<br>import pandas as pd<br>import re<br>import os, sys</pre><pre>import fire</pre><p>Next, we define a function for getting website content by making a HTTP GET request :</p><pre>def simple_get(url):<br>    try:<br>        with closing(get(url, stream=True)) as resp:<br>            if is_good_response(resp):<br>                return resp.content<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><p>We’ll also define another function for downloading a page specified by a URL and return a list of strings, one per tag element:</p><pre>def get_elements(url, tag=&#39;&#39;,search={}, fname=None):<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>                <br>        if search:<br>            soup = html            <br>            <br>            <br>            r = &#39;&#39;<br>            if &#39;find&#39; in search.keys():<br>                print(&#39;finding&#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><p>The above function uses the BeautifulSoup library for raw HTML selection and content extraction. Selection is done based on either the tag element or using search together with find or find_all.</p><p>We can now call our defined functions and pass in the URL of our two websites.</p><pre>res = get_elements(&#39;<a href="https://africafreak.com/100-most-influential-twitter-users-in-africa&#39;">https://africafreak.com/100-most-influential-twitter-users-in-africa&#39;</a>, tag = &#39;h2&#39;)<br></pre><pre>url= &#39;<a href="https://www.atlanticcouncil.org/blogs/africasource/african-leaders-respond-to-coronavirus-on-twitter/#east-africa&#39;">https://www.atlanticcouncil.org/blogs/africasource/african-leaders-respond-to-coronavirus-on-twitter/#east-africa&#39;</a><br>response = simple_get(url)<br>res_gov = get_elements(response, search={&#39;find_all&#39;:{&#39;class_&#39;:&#39;twitter-tweet&#39;}})</pre><p>The functions return all the content from the websites that satisfy our search criteria and we’ll, therefore, need to clean the data to get twitter usernames only:</p><h4>Data Cleaning</h4><p>The .split() and .strip() methods are used in the data cleaning process to get rid of any white-spaces or special characters. For instance, cleaning the res data will be:</p><pre>res_cleaned = []<br>for element in res:<br>    if re.findall(&quot;@&quot;, element):<br>        res_cleaned.append(element)<br>        <br>        <br>df = pd.DataFrame(res_cleaned)<br>df1 = df[0].str.split(&#39;@&#39;, expand = True)</pre><pre>influencers = df1[1].tolist()</pre><pre>final = []<br>for influencer in influencers:<br>    influencer = influencer.strip(&#39;)&#39;)<br>    final.append(influencer)</pre><p>And finally, we save our scrapped and cleaned data to a CSV file:</p><pre>pd.DataFrame(final, columns = [&#39;Twitter handles&#39;]).to_csv(&#39;influencers_scraped.csv&#39;, index = False, encoding = &#39;utf-8&#39;)</pre><h3>Downloading Twitter Data</h3><p>Just like its necessary for any python program, we start by importing the needed libraries. For this extraction, we will use the Tweepy library to extract Twitter data:</p><pre>import tweepy<br>from tweepy.streaming import StreamListener<br>from tweepy import OAuthHandler<br>from tweepy import Stream<br>from tweepy import Cursor<br>from tweepy import API</pre><p>Next, we initialize variables to store user credentials for accessing Twitter API, authenticate the credentials, and create a connection to Twitter Streaming API:</p><pre>consumer_key = &#39;YOUR TWITTER API KEY&#39;<br>consumer_secret = &#39;YOUR TWITTER API SECRET KEY&#39;<br>access_token = &#39;YOUR TWITTER ACCESS TOKEN&#39;<br>access_token_secret = &#39;YOUR TWITTER ACCESS TOKEN SECRET&#39;</pre><pre>#authentication and connection<br>auth = OAuthHandler(consumer_key, consumer_secret)<br>auth.set_access_token(access_token, access_token_secret)<br>            <br>auth_api = API(auth)</pre><p>After creating a successful connection to twitter, we proceed with extracting data for the users and storing the data in a CSV file for easier access during analysis.</p><p>The following function receives a list of users and a CSV file name as arguments, iterates through the list getting data for each user, and saves that data to a CSV file.</p><pre>def get_user_info(list, csvfile):<br>    users_info = []<br>    for user in list:<br>        print (&#39;GETTING DATA FOR &#39; + user)<br>        try:<br>            item = auth_api.get_user(user)<br>        <br>            users_info.append([item.name, item.description, item.screen_name, item.created_at, item.statuses_count, item.friends_count, item.followers_count])<br>            <br>        except Exception:<br>            pass<br>        <br>    print(&#39;Done!!&#39;)<br>    <br>    user_df = (pd.DataFrame(users_info, columns = [&quot;User&quot;, &quot;Description&quot;, &quot;Handle&quot;, &quot;Creation Date&quot;, &quot;Tweets&quot;, &quot;Following&quot;, &quot;Followers&quot;])).to_csv(csvfile, index = False, encoding = &#39;utf-8&#39;)</pre><p>Hashtags and mentions in a user’s tweets also help to determine the level of influence of an individual. We, therefore, get the hashtags and mentions in each tweet of a user with the help of the Cursor object and again save the data in a CSV file using the following function:</p><pre>def get_tweets(list,csvfile1, csvfile2, csvfile3):<br>    hashtags = []<br>    mentions = []</pre><pre>for user in list:<br>        print (&quot;GETTING DATA FOR &quot;+ user)<br>        try:<br>            for status in Cursor(auth_api.user_timeline, id = user).items():<br>                if hasattr(status, &quot;entities&quot;):<br>                    entities = status.entities<br>                    if &quot;hashtags&quot; in entities:<br>                        for ent in entities[&quot;hashtags&quot;]:<br>                            if ent is not None:<br>                                if &quot;text&quot; in ent:<br>                                    hashtag = ent[&quot;text&quot;]<br>                                    if hashtag is not None:<br>                                        hashtags.append(hashtag)<br>                    if &quot;user_mentions&quot; in entities:<br>                        for ent in entities[&quot;user_mentions&quot;]:<br>                            if ent is not None:<br>                                if &quot;screen_name&quot; in ent:<br>                                    name = ent[&quot;screen_name&quot;]<br>                                    if name is not None:<br>                                        mentions.append([user, name])<br>        except Exception:<br>            pass<br><br>    print(&quot;Done!&quot;)<br>    <br>    hashtags_df = (pd.DataFrame(hashtags, columns = [&quot;hashtags&quot;])).to_csv(csvfile1, index = False, encoding = &quot;utf-8&quot;)<br>    mentions_df = (pd.DataFrame(mentions, columns = [&quot;mentions&quot;])).to_csv(csvfile2, index = False, encoding = &quot;utf-8&quot;)</pre><h3>Sentimental Analysis</h3><p>Now that we have mined all the necessary data, we can proceed with analysis to determine the rank of the influencers and the most commonly used hashtags. The formulas used for ranking are based on the <a href="http://twitter.mpi-sws.org/icwsm2010_fallacy.pdf">‘Measuring User Influence in Twitter: The Million Follower Fallacy’</a> paper.</p><p>According to Gummadi, Benevenuto, Haddadi, and Cha (2010), the influence of a person can be measured in terms of:</p><ul><li><em>indegree influence </em>— the audience of an individual,</li><li><em>retweet influence</em> — the ability of the individual to generate valuable content, and</li><li><em>mention influence</em> — the ability of the individual to hold an engaging conversation.</li></ul><p>The three metrics can be calculated as reach score, popularity score, and relevance score respectively.</p><pre>reach_score = item.followers_count - item.friends_count<br>popularity_score = retweet_count + favorites_count<br>relevance_score = mentions_count</pre><p>The most common used hashtags, on the other hand, are calculated using the Counter module:</p><pre>unique_hashtags = []<br>for item, count in Counter(hashtags).most_common(5):<br>        unique_hashtags.append([item, count])</pre><p>The most common hashtags data can be used to understand the distribution of hashtags and how they are used by different influencers. The following code outputs a bar-plot with this information.</p><pre>df = pd.DataFrame(pd.read_csv(&#39;hashtags_data.csv&#39;))</pre><pre>unique_hashtags = [&#39;...&#39;,...,&#39;...&#39;] <br>  <br># selecting rows based on condition <br>hashtags_grouping_data = df[df[&#39;hashtags&#39;].isin(unique_hashtags)]</pre><pre>grouped = hashtags_grouping_data.groupby([&#39;hashtags&#39;, &#39;user_type&#39;]).agg({&#39;user_type&#39;: [&#39;count&#39;]})</pre><pre>grouped.columns = [&#39;count&#39;]<br>grouped = grouped.reset_index()</pre><pre>bp = sns.barplot(x = &#39;hashtags&#39;, y = &#39;count&#39;, hue = &#39;user_type&#39;, data = grouped)</pre><pre>#Position the legend out the graph<br>bp.legend(bbox_to_anchor=(1.02, 1),<br>          loc=2, <br>          borderaxespad=0.0);<br>bp.set(title=&#39;Bar plot for Influencers and Top Government Officials by hashtag&#39;, xlabel=&#39;Hashtags&#39;, ylabel=&#39;Count&#39;)</pre><p>A sample bar-plot constructed by the above code looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*p72uZO9DPmv0TaF33agrgw.png" /><figcaption>Image by author</figcaption></figure><h3>Conclusion</h3><p>Influencer marketing has become the new marketing niche and business organizations are on the lookout for the right social media influencers to partner with for an effective marketing campaign. Using data science, we can help drive the marketing decision based on factual data. It is as systematic as scrapping data from relevant websites, downloading user data from a social media platform such as Twitter, and performing sentimental analysis on the data to come up with visuals that business organizations can better understand. The post outlines the main codes used in the process, and the full code can be found <a href="https://github.com/Kiiru-Anastasia/QuickStart2020/blob/contribs/week1/Kiiru-Anastasia/scrapping_starter.ipynb">here.</a></p><h3>References</h3><p>[1]: C. Meeyoung, H. Hamed, B. Fabricio, and G. Krishna, <em>Measuring user influence in Twitter: The million follower fallacy</em> (2010), <a href="http://twitter.mpi-sws.org/icwsm2010_fallacy.pdf">http://twitter.mpi-sws.org/icwsm2010_fallacy.pdf</a></p><p>[2]: N. Christina, <em>Influencer marketing guide: How to work with social media influencers </em>(2019), <a href="https://blog.hootsuite.com/influencer-marketing/">https://blog.hootsuite.com/influencer-marketing/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fce3ea45c825" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/web-scrapping-downloading-twitter-data-and-performing-sentimental-analysis-using-python-fce3ea45c825">Web Scrapping, Downloading Twitter Data, and Performing Sentimental Analysis using Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>