<?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 Manusha Priyanjalee on Medium]]></title>
        <description><![CDATA[Stories by Manusha Priyanjalee on Medium]]></description>
        <link>https://medium.com/@manushapriyanjalee?source=rss-3fb0df000e0d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LpqdIMJCID3KSuXrsOlQLw.jpeg</url>
            <title>Stories by Manusha Priyanjalee on Medium</title>
            <link>https://medium.com/@manushapriyanjalee?source=rss-3fb0df000e0d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:58:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manushapriyanjalee/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[Understanding Support Vector Machine with Kernels]]></title>
            <link>https://manushapriyanjalee.medium.com/understanding-support-vector-machine-with-kernels-6b9dc5de1ec5?source=rss-3fb0df000e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b9dc5de1ec5</guid>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[kernel-trick]]></category>
            <dc:creator><![CDATA[Manusha Priyanjalee]]></dc:creator>
            <pubDate>Sun, 20 Jun 2021 16:52:53 GMT</pubDate>
            <atom:updated>2021-06-27T02:55:25.444Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical guide on how to predict whether a client will subscribe to a term deposit or not using a bank marketing dataset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IVNNDz8xeMUM_FrR" /><figcaption>Photo by <a href="https://unsplash.com/@homajob?utm_source=medium&amp;utm_medium=referral">Scott Graham</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I am going to describe how to build a support vector machine with kernels to predict whether a client will subscribe to a term deposit or not. The dataset I am using is a Bank Marketing dataset. The dataset can be downloaded <a href="https://archive.ics.uci.edu/ml/datasets/bank+marketing#">here</a>.</p><h3>1. What is Support Vector Machine?</h3><p>Support vector machine is a supervised machine learning algorithm that can be used for both classification or regression challenges. But, it is mostly used in classification problems.</p><p>Support vectors simply mean the coordinates of individual observations. Classification in SVM is done by segregating classes with a hyper-plane or a line.</p><p>SVM performs well with small datasets.</p><h4>What is Support Vector Machine with kernels?</h4><p>Using kernels is an optimization technique for SVM. When the kernel function is applied it will make the calculation easier for the SVM. When the classes cannot be linearly separable, the kernel function is useful. It can take low-dimensional input space and transforms it into a higher-dimensional space. And then the class segregation can be done in the higher dimensional space.</p><p>Examples of SVM kernels are polynomial kernel, gaussian kernel, radial basis function, and sigmoid kernel.</p><h3>2. Dataset description</h3><p>Bank Marketing dataset is obtained from UCI Machine Learning Repository.</p><p><strong>Attribute Information</strong></p><blockquote>Input variables:<br># bank client data:<br>1. <strong>age</strong> (numeric)<br>2. <strong>job</strong> : type of job (categorical: ‘admin.’,’blue-collar’,’entrepreneur’,’housemaid’,’management’,’retired’,’self-employed’,’services’,’student’,’technician’,’unemployed’,’unknown’)<br>3. <strong>marital</strong> : marital status (categorical: ‘divorced’,’married’,’single’,’unknown’; note: ‘divorced’ means divorced or widowed)<br>4. <strong>education</strong> (categorical: ‘basic.4y’,’basic.6y’,’basic.9y’,’high.school’,’illiterate’,’professional.course’,’university.degree’,’unknown’)<br>5. <strong>default</strong>: has credit in default? (categorical: ‘no’,’yes’,’unknown’)<br>6. <strong>housing</strong>: has housing loan? (categorical: ‘no’,’yes’,’unknown’)<br>7. <strong>loan</strong>: has personal loan? (categorical: ‘no’,’yes’,’unknown’)<br># related with the last contact of the current campaign:<br>8. <strong>contact</strong>: contact communication type (categorical: ‘cellular’,’telephone’)<br>9. <strong>month</strong>: last contact month of year (categorical: ‘jan’, ‘feb’, ‘mar’, …, ‘nov’, ‘dec’)<br>10. <strong>day_of_week</strong>: last contact day of the week (categorical: ‘mon’,’tue’,’wed’,’thu’,’fri’)<br>11. <strong>duration</strong>: last contact duration, in seconds (numeric). Important note: this attribute highly affects the output target (e.g., if duration=0 then y=’no’). Yet, the duration is not known before a call is performed. Also, after the end of the call y is obviously known. Thus, this input should only be included for benchmark purposes and should be discarded if the intention is to have a realistic predictive model.<br># other attributes:<br>12. <strong>campaign</strong>: number of contacts performed during this campaign and for this client (numeric, includes last contact)<br>13. <strong>pdays</strong>: number of days that passed by after the client was last contacted from a previous campaign (numeric; 999 means client was not previously contacted)<br>14. <strong>previous</strong>: number of contacts performed before this campaign and for this client (numeric)<br>15. <strong>poutcome</strong>: outcome of the previous marketing campaign (categorical: ‘failure’,’nonexistent’,’success’)<br># social and economic context attributes<br>16. <strong>emp_var_rate</strong>: employment variation rate — quarterly indicator (numeric)<br>17. <strong>cons_price_idx</strong>: consumer price index — monthly indicator (numeric)<br>18. <strong>cons_conf_idx</strong>: consumer confidence index — monthly indicator (numeric)<br>19. <strong>euribor3m</strong>: euribor 3 month rate — daily indicator (numeric)<br>20. <strong>nr_employed</strong>: number of employees — quarterly indicator (numeric)</blockquote><blockquote>Output variable (desired target):<br>21. <strong>y</strong> — has the client subscribed a term deposit? (binary: ‘yes’,’no’)</blockquote><h3>3. Problem Statement</h3><blockquote>The data is related with direct marketing campaigns of a Portuguese banking institution. The marketing campaigns were based on phone calls. Often, more than one contact to the same client was required, in order to access if the product (bank term deposit) would be (‘yes’) or not (‘no’) subscribed.</blockquote><blockquote>The classification goal is to predict if the client will subscribe (yes/no) a term deposit (variable y).</blockquote><h3>4. Developing the SVM</h3><p>The target column of our dataset is y. It indicates whether the client has subscribed to a term deposit or not. The values are binary ‘1’ and ‘0’. First, the target column needs to be checked to get an understanding of the class distribution.</p><pre>X[‘y’].value_counts()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*xyAOLSIDnIAzWq5Lddx6Bw.png" /><figcaption>Count of class labels in y column</figcaption></figure><p>The class imbalance is graphically represented below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*qlcgIU6YZwCqXtThfIy8hg.png" /><figcaption>Graphical representation of class imbalance</figcaption></figure><p>It is obvious that there is a considerable class imbalance in the dataset. To handle the class imbalance I will apply SMOTE later.</p><h4>Data Preprocessing</h4><p>There were 12 duplicate records in the dataset and they were removed. The dataset was checked to identify missing values but there were not any missing values. But when we check the dataset we can see there are values called ‘unknown’ in few columns. But I did not remove them since they may be recorded as unknown due to some valid reason although we do not know for sure.</p><p>In the dataset description below note is included for the column duration.</p><blockquote>duration: This attribute highly affects the output target (e.g., if duration=0 then y=’no’). Yet, the duration is not known before a call is performed. Also, after the end of the call y is obviously known. Thus, this input should only be included for benchmark purposes and should be discarded if the intention is to have a realistic predictive model.</blockquote><p>So I dropped the column ‘duration’.</p><p><strong>Handling outliers</strong></p><p>In the dataset, there are both numerical and categorical columns. Numerical columns should be checked to detect outliers. Boxplots for all 9 numerical columns are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_bh4r5GNBgX43o8O6WiBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBKgxLfyB_661CJUjup9Fg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*qzbkrXqdzWRGF2Tbcd6sqA.png" /><figcaption>Box plots of numerical attributes</figcaption></figure><p>When we consider the box plots age, pdays, emp_var_rate, cons_price_idx, euribor3m and nr_employed do not have outliers.</p><p>But campaign, cons_conf_idx, previous have outliers.</p><p>Below code snippet is used to drop outliers in the campaign column.</p><pre>warnings.filterwarnings(&quot;ignore&quot;)</pre><pre>fig, axes = plt.subplots(1,2)<br>plt.tight_layout(0.2)<br>print(&quot;Before Shape:&quot;, X.shape)</pre><pre>#remove outliers that is more than 50<br>X_df =X[X[&#39;campaign&#39;]&lt;50]<br>print(&quot;After Shape:&quot;, X_df.shape)<br>sns.boxplot(X[&#39;campaign&#39;],orient=&#39;v&#39;,ax=axes[0])<br>axes[0].title.set_text(&quot;Before&quot;)<br>sns.boxplot(X_df[&#39;campaign&#39;],orient=&#39;v&#39;,ax=axes[1])<br>axes[1].title.set_text(&quot;After&quot;)<br>plt.show()</pre><pre>X=X_df;<br>X=X.reset_index(drop=True)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*wjvhFXl0tnN5KbdDA2Q9cQ.png" /><figcaption>Before and after outliers in the campaign column are removed</figcaption></figure><p>Likewise, all the outliers are removed in other columns also.</p><h4>Feature Encoding</h4><p>Feature encoding should be applied to all categorical columns. To identify the categorical columns in the dataset following code snippet is used.</p><pre>cat_df = X1.select_dtypes(include = np.object)<br>cat_df.info()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*y7CfwoNo8D_BbfQKh5OFYg.png" /><figcaption>Details of categorical columns</figcaption></figure><p>To check the unique values in each of these columns use the below code.</p><pre>cat_df.nunique()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*4UqWWkaU0dbAa4aNew9rEA.png" /><figcaption>Unique values in each categorical column</figcaption></figure><p>We can apply label encoding to all categorical columns. But when we consider the education column we know that there is an order in educational qualification. So education column can be considered as ordinal. We need to assign each qualification a rank accordingly.</p><p>To find the unique values in the education column below code is used.</p><pre>X1.education.unique()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*CUFqpvlLpFcK3ewi9hbtEg.png" /><figcaption>Unique values in the education column</figcaption></figure><p>To assign a rank for the values below code can be used.</p><pre>scale_mapper = {&quot;unknown&quot;:0, &quot;illiterate&quot;:1, &quot;basic.4y&quot;:2, &quot;basic.6y&quot;:3, &quot;basic.9y&quot;:4, &quot;high.school&quot;:5, &quot;professional.course&quot;:6, &quot;university.degree&quot;:7}</pre><pre>X1[&quot;education&quot;] = X1[&quot;education&quot;].replace(scale_mapper)</pre><p>I have provided the least value 0 for unknown values and the highest value 7 for university degree. Other values also are mapped in order. The output column can be seen as below.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/113/1*mz8uO-JeFT8JsieD_i1vxw.png" /><figcaption>Education column after encoding</figcaption></figure><p>All the other categorical columns can be encoded using label encoder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ab7f920fcccd1372452de44e3b1f4ae/href">https://medium.com/media/6ab7f920fcccd1372452de44e3b1f4ae/href</a></iframe><p>The output dataset is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qpdQtQ1cIFiGNGtuaTbElQ.png" /><figcaption>Dataset after applying feature coding</figcaption></figure><h4>Transformations</h4><p>Q-Q plots and histograms for each numerical column are shown below. By analyzing those graphs skewness can be identified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*XrIxTkD6eq5JBugDPQpvJw.png" /><figcaption>Q-Q plots and Histograms for age and campaign</figcaption></figure><p>Both age and campaign show a right skewness. So, we need to transform data to get a normal distribution. In the below code, I have shown how to apply square root transformation to reduce the right skewness of age.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/130c352bb3f45fd887802b5371ccf280/href">https://medium.com/media/130c352bb3f45fd887802b5371ccf280/href</a></iframe><p>The normal distribution can be seen now in age and campaign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*siwT6GCjxiR-vkiwBwGDlA.png" /><figcaption>Histogram for age after applying square root transformation</figcaption></figure><p>Similarly, square root transformation should be applied to campaign as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPN-NIihFM3S6_qhXRhWtw.png" /><figcaption>Q-Q plots and histograms for pdays and previous</figcaption></figure><p>I decided not to apply transformations for pdays since it is distributed only in 2 separate regions. But previous is right-skewed. So I applied square root transformation to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXT1E8byC6oEY57Y81gyvg.png" /><figcaption>Q-Q plots and Histograms for emp_var_rate and cons_price_isx</figcaption></figure><p>We can see emp_car_rate shows a left skewness and I applied square transformation to reduce the left skewness of emp_var_rate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdec4284fb47ff56745590f3e92d8fe9/href">https://medium.com/media/bdec4284fb47ff56745590f3e92d8fe9/href</a></iframe><p>The output is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*0vJyvdeZDhim_tAcpzTe4w.png" /><figcaption>Histogram after applying square transformation to emp_var_rate</figcaption></figure><p>For cons_price_idx transformations were not applied.</p><p>The Q-Q plots and histograms for cons_conf_idx and euribor3m are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*95YBBB3rXwdcfEpLlUFUfg.png" /><figcaption>Q-Q plots and Histograms for cons_conf_idx and euribor3m</figcaption></figure><p>Transformations were not applied to both cons_conf _idx and euribor3m.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*v8VK63IyMZMd7GwoTx_S2Q.png" /><figcaption>Q-Q plot and Histogram for nr_employed</figcaption></figure><p>Since it shows a left skewness square transformation was applied to nr_employed. The output is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*aTxfSZevKwOhQIsoWyKlKA.png" /><figcaption>Histogram after applying square transformation to nr_employed</figcaption></figure><p>Now we have applied the necessary transformations and next, we should do standardization.</p><h4>Standardization</h4><p>We apply standardization only for numerical columns. The code used is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbdc2a65cf36f3ebfb037988679320f6/href">https://medium.com/media/bbdc2a65cf36f3ebfb037988679320f6/href</a></iframe><h4>Feature Extraction</h4><p>To identify the significant features we can use the significance matrix.</p><pre>plt.figure(figsize = (18,10))<br>sns.heatmap(X3.corr(), annot = True);</pre><p>Significance Matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lxaSdKW8hQkHF-Q0hJktpg.png" /><figcaption>Significance Matrix</figcaption></figure><p>Here when we consider the correlation between attributes we cannot see any attributes with considerably high correlated attributes. And when we consider the significance of attributes there are some attributes with low significance.</p><p>I decided to drop 4 attributes which are day_of_week, job, housing, and loan. I tried dropping few different combinations of attributes but dropping those 4 attributes gave a high precision than other combinations. The recall and F1 score did not show much difference.</p><h4>SMOTE</h4><p>SMOTE is applied after first, training SVM with class imbalance. But it was observed that the overall performance was less. So, SMOTE is applied and although the performance was not highly increased, it was better than without applying SMOTE.</p><p>Now I am going to separate the target variable, and split the dataset, and after splitting handle class imbalance by applying SMOTE technique.</p><p>First, I separated the target column ‘y’.</p><pre>y_true = X4[&#39;y&#39;]<br>X_dataset = X4.drop(&#39;y&#39;, axis=1)</pre><p>Then the dataset is split into a 0.8 : 0.2 ratio and SMOTE is applied to the training data which was obtained after splitting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c27e67d43634af37a18979bc41d45e72/href">https://medium.com/media/c27e67d43634af37a18979bc41d45e72/href</a></iframe><p>When we visualize the values of the target variable ‘y’, we can see that the class imbalance problem is resolved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*Anzc_dB4-epcKk3W4CNGtg.png" /><figcaption>Class frequencies in y after handling class imbalance</figcaption></figure><pre>X_train = smoted_X<br>y_train = smoted_y</pre><p>smoted_X is out X_train data and smoted_y is our y_train data. For X_test and y_test those changes were not applied.</p><h4>Principal Component Analysis</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff768539f875d49e29959fc0c693b15a/href">https://medium.com/media/ff768539f875d49e29959fc0c693b15a/href</a></iframe><p>We should consider the summation of high variance dimensions. The summation of 9 high variance dimensions is 96%. So, I made n_componets equal to 9.</p><pre>pca.explained_variance_ratio_</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*07jsGQUTrZTORv1nf-1RHA.png" /><figcaption>pca.explained_variance_ratio</figcaption></figure><h4>SVM with Kernel</h4><p>RBF kernel is used since it works well in practice and it is relatively easy to tune.</p><blockquote>Intuitively, the gamma parameter defines how far the influence of a single training example reaches, with low values meaning ‘far’ and high values meaning ‘close’. The gamma parameters can be seen as the inverse of the radius of influence of samples selected by the model as support vectors.</blockquote><blockquote>The C parameter trades off correct classification of training examples against maximization of the decision function’s margin. For larger values of C, a smaller margin will be accepted if the decision function is better at classifying all training points correctly. A lower C will encourage a larger margin, therefore a simpler decision function, at the cost of training accuracy. In other words C behaves as a regularization parameter in the SVM.</blockquote><p>I used C=1 and gamma=0.05. These values produced the result with better predictions than other different combinations of C and gamma values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/350051fd960bae50f3e35264f02b5f6f/href">https://medium.com/media/350051fd960bae50f3e35264f02b5f6f/href</a></iframe><p>Confusion matrix is created to evaluate the performance of the classification model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0506241d759830dbd42663d3e6b73c47/href">https://medium.com/media/0506241d759830dbd42663d3e6b73c47/href</a></iframe><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*L7lSU8NC-ZqtMIM3yDJHTw.png" /><figcaption>Confusion Matrix</figcaption></figure><ul><li>True positives — 560</li><li>True negatives — 6500</li><li>False positives — 830</li><li>False negatives — 380</li></ul><p>The classification performace for true positives is low. It may be due to the class imbalance of the original dataset.</p><p>Classification report is used to measure the quality of predictions of a classification model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79ee715451e1dc7c42f4d503a82aec6b/href">https://medium.com/media/79ee715451e1dc7c42f4d503a82aec6b/href</a></iframe><p>The output is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*SLGBG6CXTSYbkx9YfFkW1Q.png" /><figcaption>Classification Report</figcaption></figure><blockquote>The precision is the ratio <em>tp / (tp + fp)</em> where <em>tp</em> is the number of true positives and <em>fp</em> the number of false positives. The precision is intuitively the ability of the classifier not to label as positive a sample that is negative.</blockquote><blockquote>The recall is the ratio <em>tp / (tp + fn)</em> where <em>tp</em> is the number of true positives and <em>fn</em> the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples.</blockquote><blockquote>The F-beta score can be interpreted as a weighted harmonic mean of the precision and recall, where an F-beta score reaches its best value at 1 and worst score at 0.</blockquote><blockquote>The F-beta score weights recall more than precision by a factor of beta. beta == 1.0 means recall and precision are equally important.</blockquote><blockquote>The support is the number of occurrences of each class in y_true.</blockquote><p>Precision, recall, and F1 score for test data is obtained as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b09ca54527a987344aaf2431d1e9224/href">https://medium.com/media/5b09ca54527a987344aaf2431d1e9224/href</a></iframe><p>Results are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*3mj7lowLLWhlV0bMLUGGWw.png" /><figcaption>Precision, Recall, and F1 score</figcaption></figure><p>We can also get training set score and testing set score as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5795f7f5e2374ccaa20d7d4b1d9276ab/href">https://medium.com/media/5795f7f5e2374ccaa20d7d4b1d9276ab/href</a></iframe><p>The result is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*f8tsOg1O89ts8BdYM8G75A.png" /><figcaption>Training set and Testing set scores</figcaption></figure><p>Here test set score is high but it’s due to the class imbalance in the testing data. Since the number of true negatives is very high it gives a high test score.</p><h3>Conclusion</h3><p>In this article, I gave you a step-by-step guide on data preprocessing, feature encoding, transformations, standardization, feature extraction, handling class imbalance, dimensionality reduction and finally building a support vector machine with kernels.</p><p>I hope this article helped you to gain a good understanding of the important steps we should follow to build a binary classification model using SVM.</p><p>Happy Coding!</p><h4>Colab Code</h4><p><a href="https://colab.research.google.com/drive/1hfLlZk0cOxyLFO2-zvk3Lf1azmZu0Qre?usp=sharing">Google Colaboratory</a></p><h4>References</h4><ol><li><a href="https://www.analyticsvidhya.com/blog/2017/09/understaing-support-vector-machine-example-code/">https://www.analyticsvidhya.com/blog/2017/09/understaing-support-vector-machine-example-code/</a></li><li><a href="https://scikit-learn.org/stable/auto_examples/svm/plot_rbf_parameters.html">https://scikit-learn.org/stable/auto_examples/svm/plot_rbf_parameters.html</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_recall_fscore_support.html">https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_recall_fscore_support.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b9dc5de1ec5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to exploit Random Forest Classifier in PySpark]]></title>
            <link>https://medium.com/data-science/a-guide-to-exploit-random-forest-classifier-in-pyspark-46d6999cb5db?source=rss-3fb0df000e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/46d6999cb5db</guid>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Manusha Priyanjalee]]></dc:creator>
            <pubDate>Tue, 01 Jun 2021 08:59:51 GMT</pubDate>
            <atom:updated>2021-06-02T12:21:34.719Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical explanatory guide for the classification of Iris flowers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FIj65s952XFWEoFZ" /><figcaption>Photo by <a href="https://unsplash.com/@ninszi?utm_source=medium&amp;utm_medium=referral">Adél Grőber</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I am going to give you a step-by-step guide on how to use PySpark for the classification of Iris flowers with Random Forest Classifier.</p><p>I have used the popular Iris dataset and I have provided the link to the dataset at the end of the article. I used Google Colab for coding and I have also provided Colab notebook in Resources.</p><p>Pyspark is a Python API for Apache Spark and pip is a package manager for Python packages.</p><pre>!pip install pyspark</pre><p>With the above command, pyspark can be installed using pip.</p><pre>from pyspark.sql import SparkSession<br>spark = SparkSession.builder.appName(&#39;ml-iris&#39;).getOrCreate()<br>df = spark.read.csv(&#39;IRIS.csv&#39;, header = True, inferSchema = True)<br>df.printSchema()</pre><p>First, I need to create an entry point into all functionality in Spark. SparkSession class is used for this. SparkSession.builder() creates a basic SparkSession. To set a name for the application use appName(name). Here I have set ‘ml-iris’ as the application name. Setting a name is not necessary and if it is not set, a random name will be generated for the application. getOrCreate() creates a new SparkSession if there is no existing session. Otherwise, it gets the existing session.</p><p>spark.read.csv(“path”) is used to read the CSV file into Spark DataFrame. A Data Frame is a 2D data structure and it sets data in a tabular format. Iris dataset has a header, so I set header = True, otherwise, the API treats the header as a data record. inferSchema attribute is related to the column types. By default, inferSchema is false. It will give all columns as strings. Here I set inferSchema = True, so Spark goes through the file and infers the schema of each column. printSchema() will print the schema in a tree format.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*-9ZcvZ_XE4Q4MRh_7E09OQ.png" /></figure><pre>import pandas as pd<br>pd.DataFrame(df.take(5), columns=df.columns).transpose()</pre><p>pandas is a toolkit used for data analysis. Here df.take(5) returns the first 5 rows and df.columns returns the names of all columns. DataFrame.transpose() transpose index and columns of the DataFrame. It writes columns as rows and rows as columns.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*U4f1rH64zZite7S4x5j5QQ.png" /></figure><pre>numeric_features = [t[0] for t in df.dtypes if t[1] == &#39;double&#39;]<br>df.select(numeric_features).describe().toPandas().transpose()</pre><p>df.dtypes returns names and types of all columns. Here we assign columns of type Double to numeric_features. select(numeric_features) returns a new Data Frame. describe() computes statistics such as count, min, max, mean for columns and toPandas() returns current Data Frame as a Pandas DataFrame.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*If7N94QIamaRuVkKfhZdgg.png" /></figure><p>Since we have a good idea about the dataset we are working with now, we can start feature transforming. Feature transforming means scaling, converting, and modifying features so they can be used to train the machine learning model to make more accurate predictions. For this purpose, I have used String indexer, and Vector assembler.</p><p>First, I have used Vector Assembler to combine the sepal length, sepal width, petal length, and petal width into a single vector column. Here the new single vector column is called features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/681d2220eac5ccc0323cd6dec26c3cb0/href">https://medium.com/media/681d2220eac5ccc0323cd6dec26c3cb0/href</a></iframe><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*w_YzKKPJELNgUxBzG77-Cw.png" /></figure><p>Then I have used String Indexer to encode the string column of species to a column of label indices. By default, the labels are assigned according to the frequencies. So, the most frequent species gets an index of 0.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dd1f2ae0ec5666f11b3ebc39b9340ea/href">https://medium.com/media/7dd1f2ae0ec5666f11b3ebc39b9340ea/href</a></iframe><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*_o4M3MXZYQ_7MnKaI0Q1CQ.png" /></figure><p>As you can see, we now have new columns named labelIndex and features.</p><pre>pd.DataFrame(df.take(110), columns=df.columns).transpose()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9xgBW3-YNaX3H3XH38u5w.png" /></figure><p>The bottom row is the labelIndex. We can see that Iris-setosa has the labelIndex of 0 and Iris-versicolor has the label index of 1. And Iris-virginica has the labelIndex of 2.</p><p>Now we have transformed our features and then we need to split our dataset into training and testing data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edb72e78010482c9a92092adbf594973/href">https://medium.com/media/edb72e78010482c9a92092adbf594973/href</a></iframe><p>randomSplit() splits the Data Frame randomly into train and test sets. Here I set the seed for reproducibility. 0.7 and 0.3 are weights to split the dataset given as a list and they should sum up to 1.0.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*aydyHQAGWR9tK8g4" /></figure><p>Now we can import and apply random forest classifier. Random forest is a method that operates by constructing multiple decision trees during the training phase. The decision of the majority of the trees is chosen by the random forest as the final decision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*5x1avcPsURnhhcqQ" /><figcaption>Representation of Random Forest Classifier (Image by author)</figcaption></figure><p>It comes under supervised learning and mainly used for classification but can be used for regression as well. Random forest classifier is useful because,</p><ol><li>No overfitting</li><li>High accuracy</li><li>Estimates missing data</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3dd1c13e42b9a3ecabab4142e5b9dd2/href">https://medium.com/media/b3dd1c13e42b9a3ecabab4142e5b9dd2/href</a></iframe><p>Here featuresCol is the list of features of the Data Frame, here in our case it is the features column. labelCol is the targeted feature which is labelIndex. rf.fit(train) fits the random forest model to our input dataset named train. rfModel.transform(test) transforms the test dataset. This will add new columns to the Data Frame such as prediction, rawPrediction, and probability.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_HHCU_skkwv9tRrhMfZug.png" /></figure><p>We can clearly compare the actual values and predicted values with the output below.</p><pre>predictions.select(&quot;labelIndex&quot;, &quot;prediction&quot;).show(10)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*aznUE9x569jTu-OKFCp6ww.png" /></figure><p>Now we have applied the classifier for our testing data and we got the predictions. Then we need to evaluate our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7568a87245ac095fe50fc43be309c88d/href">https://medium.com/media/7568a87245ac095fe50fc43be309c88d/href</a></iframe><p>MulticlassClassificationEvaluator is the evaluator for multi-class classifications. Since we have 3 classes (Iris-Setosa, Iris-Versicolor, Iris-Virginia) we need MulticlassClassificationEvaluator. The method evaluate() is used to evaluate the performance of the classifier.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*u94NIRMEwLw81l6XMbplZA.png" /></figure><p>Now we can see that the accuracy of our model is high and the test error is very low. It means our classifier model is performing well.</p><p>We can use a confusion matrix to compare the predicted iris species and the actual iris species.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50fb3a12ba2009405b110339fca67fcf/href">https://medium.com/media/50fb3a12ba2009405b110339fca67fcf/href</a></iframe><p>MulticlassMetrics is an evaluator for multiclass classification in the pyspark mllib library.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*ACMVXmsd1Cyz-FZ1z_AhyQ.png" /></figure><p>According to the confusion matrix, 44 (12+16+16) species are correctly classified out of 47 test data. 3 species are incorrectly classified.</p><p>I hope this article helped you learn how to use PySpark and do a classification task with the random forest classifier. I have provided the dataset and notebook links below.</p><p>Happy Coding! 😀</p><h4>Resources</h4><p>Dataset</p><p><a href="https://www.kaggle.com/arshid/iris-flower-dataset">Iris Flower Dataset</a></p><p>Colab Notebook</p><p><a href="https://colab.research.google.com/drive/1en1X946wqbv4SC_cCLmspJa7iGL8DvYo?usp=sharing">Google Colaboratory</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46d6999cb5db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-guide-to-exploit-random-forest-classifier-in-pyspark-46d6999cb5db">A Guide to exploit Random Forest Classifier in PySpark</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>
        <item>
            <title><![CDATA[Understanding the Process of Building a Machine Learning Model for a Real World Scenario]]></title>
            <link>https://medium.com/data-science/understanding-the-process-of-building-a-machine-learning-model-for-a-real-world-scenario-30a50fc12f7f?source=rss-3fb0df000e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/30a50fc12f7f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[feature-extraction]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Manusha Priyanjalee]]></dc:creator>
            <pubDate>Fri, 28 May 2021 17:15:20 GMT</pubDate>
            <atom:updated>2021-06-02T18:12:36.666Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical step-by-step guide to building a Linear Regression Model to predict Apparent Temperature from Weather History Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zPAMHi6fnxuK23R1" /><figcaption>Photo by <a href="https://unsplash.com/@kmuza?utm_source=medium&amp;utm_medium=referral">Carlos Muza</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article focuses on finding the relationships between particular features and making predictions with a weather history dataset after going through all the necessary steps,</p><ul><li>Data Cleansing</li><li>Data Transformations</li><li>Feature Coding</li><li>Feature Scaling</li><li>Feature Discretization</li><li>Dimensionality Reduction</li><li>Linear Regression Model</li><li>Model Evaluation</li></ul><p>Here the goal is to find, is there a <strong>relationship between humidity and temperature</strong>, and is there a <strong>relationship between humidity and apparent temperature</strong>? And also to find whether <strong>the apparent temperature can be predicted with the given humidity.</strong></p><p>The dataset used here is the weather history dataset from Kaggle. You can find it by clicking <a href="https://www.kaggle.com/budincsevity/szeged-weather">here</a>.</p><p>First, import the required python libraries.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import scipy.stats as stats<br>import seaborn as sns<br>from sklearn import preprocessing<br>from sklearn.decomposition import PCA<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.preprocessing import KBinsDiscretizer<br>from sklearn import linear_model<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import mean_squared_error<br>from math import sqrt<br>from sklearn.model_selection import cross_val_score,     cross_val_predict<br>from sklearn import metrics</pre><p>Then import the dataset into Colab and read it.</p><pre>from google.colab import drive<br>drive.mount(&quot;/content/gdrive&quot;)</pre><pre>data_set = pd.read_csv(&#39;/content/gdrive/My Drive /data            /weatherHistory.csv&#39;)<br>data_set.tail(10)</pre><p>The last 10 rows from the dataset can be checked with <em>data_set.tail(10)</em> as below.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nv66eqfzZ_vSOw9JNq8ztA.png" /><figcaption>Dataset</figcaption></figure><p>Then a copy of the original dataset is created as X.</p><pre>X = data_set.copy()</pre><h3>1. Data Cleansing — Handling missing values, anomalies, and outliers</h3><p>The dataset should be checked for missing values and the below code will return <em>True</em> if there are any missing values otherwise, return <em>False</em>.</p><pre>X.isnull().values.any()</pre><p>The above code outputs <em>True</em> indicating that there are missing values in the dataset. So the columns that have missing values are needed to be identified.</p><pre>X.isnull().any()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*LOlmTv-NC2_0XLzJQGX33A.png" /></figure><p>This means, only the Precip Type column has missing values and all the other columns do not have any missing values.</p><p>The percentage of the missing value can be checked as below.</p><pre>print(X.isnull().sum() * 100 / len(X))</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*3UAM7LkxpAZegDXhuUxsyg.png" /></figure><p>We can see that the percentage is very low, so we can simply drop all the missing values in the dataset with the below code.</p><pre>X = X.dropna()</pre><p>Since the missing value problem is resolved, next, we should check for outliers or anomalies.</p><pre>X.boxplot(figsize=(18,8))</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVNFW71SerhlZnaRLLQLnw.png" /><figcaption>Boxplot for all the features</figcaption></figure><p>We can see that the data distribution of the Pressure feature is abnormal since Pressure has been 0. We can check how much data shows anomalies.</p><pre>X[X[&#39;Pressure (millibars)&#39;] == 0].shape[0]</pre><p>Output: 1288</p><p>So these are not outliers. Those values may be the result of some human errors or system failures. So we cannot simply accept them and we cannot drop them as well since then we will miss other features data. So we can use IQR.</p><blockquote>IQR or interquartile range is a measurement of variability based on dividing the dataset into different quantiles.</blockquote><p>We can calculate the lower limit and upper limit using quantiles. Then we replace the values that are less than the lower limit with the lower limit and the values that are greater than the upper limit with the upper limit. This will work with left-skewed or right-skewed data as well.</p><pre>fig, axes = plt.subplots(1,2)<br>plt.tight_layout(0.2)<br>print(&quot;Previous Shape With Outlier: &quot;,X.shape)<br>sns.boxplot(X[&#39;Pressure (millibars)&#39;],orient=&#39;v&#39;,ax=axes[0])<br>axes[0].title.set_text(&quot;Before&quot;)</pre><pre>Q1 = X[&quot;Pressure (millibars)&quot;].quantile(0.25)<br>Q3 = X[&quot;Pressure (millibars)&quot;].quantile(0.75)</pre><pre>print(Q1,Q3)<br>IQR = Q3-Q1<br>print(IQR)</pre><pre>lower_limit = Q1 - 1.5*IQR<br>upper_limit = Q3 + 1.5*IQR<br>print(lower_limit,upper_limit)</pre><pre>X2 = X</pre><pre>X2[&#39;Pressure (millibars)&#39;] = np.where(X2[&#39;Pressure  (millibars)&#39;]&gt;upper_limit,upper_limit,X2[&#39;Pressure (millibars)&#39;])</pre><pre>X2[&#39;Pressure (millibars)&#39;] = np.where(X2[&#39;Pressure (millibars)&#39;] &lt;lower_limit,lower_limit,X2[&#39;Pressure (millibars)&#39;])</pre><pre>print(&quot;Shape After Removing Outliers:&quot;, X2.shape)<br>sns.boxplot(X2[&#39;Pressure (millibars)&#39;],orient=&#39;v&#39;,ax=axes[1])<br>axes[1].title.set_text(&quot;After&quot;)<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*U-UFwETO6FIC8g9ROmTreA.png" /><figcaption>Boxplots before and after applying IQR for Pressure</figcaption></figure><p>Then we need to check outliers or anomalies in Humidity by plotting the box plot.</p><pre>humidity_df = pd.DataFrame(X2[&quot;Humidity&quot;])<br>humidity_df.boxplot()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*CPoc-iOVLYRHGm5GOXog9Q.png" /><figcaption>Boxplot of Humidity</figcaption></figure><p>We can see there is 0.0 humidity. So we should check how many data values are 0.0.</p><pre>X2[X2[&#39;Humidity&#39;] == 0].shape[0]</pre><p>Output: 22</p><p>Given Earth’s climate and weather conditions, it’s impossible for humidity to be zero. And the number of data points with this anomaly is also very less so we can simply drop them.</p><pre>X2 = X2.drop(X2[X2[&#39;Humidity&#39;] == 0].index)</pre><p>Now we complete cleansing our data.</p><p>Usually, after data cleansing, you can move on to data transformations. But here I have done feature coding before splitting the data as it will remove the need to do feature coding separately for training and testing data. The reason for splitting the dataset before applying any transformations is explained later.</p><h3>2. Feature Coding — Handling categorical features</h3><p>Categorical features are data that can be grouped into categories. As an example, we can take gender, color, etc. We need to convert those non-numerical values into numerical values in order to train the machine learning model. There are 2 traditional techniques to handle categorical data.</p><ol><li>One-hot Encoding</li><li>Label(Integer) Encoding</li></ol><p>I will explain these 2 with examples from our weather history dataset. We have 2 categorical columns in our dataset, Precip Type and Summary. Let’s take the feature ‘Precip Type’.</p><pre>X2[&#39;Precip Type&#39;].value_counts()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*cfv6BwQJED-r1-PW8LRiwQ.png" /></figure><p>We can see that the data values in ‘Precip Type’ are either rain or snow. So ‘Precip Type’ is a categorical feature.</p><h4>One-hot Encoding</h4><p>In this technique, the categorical feature is replaced with new features that have values 0 or 1. Precip Type is replaced with new features rain and snow like the below representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*mnzTeuhearJkEhr4x5I3gA.png" /></figure><h4>Label Encoding</h4><p>In this technique, each categorical value is converted to a numeric value. It is represented below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*NDNOLxkdSQQiTnEPkcH_mg.png" /></figure><p>For linear models, One-hot Encoding is more suitable. If we apply Lable Encoding for such a situation then the model will try to identify an order since the feature values are like 0,1,2,3, etc. But if it is a binary category we can use Label Encoding.</p><p>Here since Precip Type has only 2 values I can use Label Encoding.</p><pre>X2[&#39;Precip Type&#39;]=X2[&#39;Precip Type&#39;].astype(&#39;category&#39;)<br>X2[&#39;Precip Type&#39;]=X2[&#39;Precip Type&#39;].cat.codes</pre><p>But as shown below summary has many categories.</p><pre>final[&#39;Summary&#39;].value_counts()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*PeFvbch_01uqH58zO1BIPw.png" /></figure><p>So we need to do One-hot Encoding for the Summary column. <em>pd.get_dummies</em> will make new feature columns according to each category and then we need to merge new feature columns and drop the Summary column as shown in the below code.</p><pre>dummies_summary = pd.get_dummies(X2[&#39;Summary&#39;])<br>merged_summary = pd.concat([X2,dummies_summary],axis=&#39;columns&#39;)<br>X2 = merged_summary.drop([&#39;Summary&#39;], axis=&#39;columns&#39;)<br>X2</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8wvBqHrmnAkqKQcmv4dDQ.png" /><figcaption>Dataset after applying feature coding</figcaption></figure><h3>3. Splitting the dataset</h3><blockquote>Data leakage refers to a mistake make by the creator of a machine learning model in which they accidentally share information between the test and training data-sets.</blockquote><p>When we apply transformations, discretization, and scaling, etc to the train and test dataset together (for the whole dataset) it may cause data leakage. To mitigate this problem I split the dataset before transformations to avoid model overfitting.</p><p>Apparent Temperature is the target feature. So we need to separate it and remove it from the feature dataset. Here dataset is split into 80% for training and 20% for testing.</p><pre>target_column = pd.DataFrame(final_summary[&#39;Apparent Temperature (C)&#39;])</pre><pre>final_summary = final_summary.drop([&#39;Apparent Temperature (C)&#39;], axis=&#39;columns&#39;)</pre><pre>X_train, X_test, y_train, y_test = train_test_split(final_summary, target_column, test_size=0.2)</pre><p>After splitting dataset indexes are need to be reset.</p><pre>X_train=X_train.reset_index(drop=True)<br>X_test=X_test.reset_index(drop=True)<br>y_train=y_train.reset_index(drop=True)<br>y_test=y_test.reset_index(drop=True)</pre><p>Now we can apply transformations to the training and testing datasets separately.</p><h3>4. Data Transformation</h3><p>Variables in real datasets will follow more a skewed distribution. But if the data comes from normal distribution then machine learning models can learn well. So we should check how those variables are distributed using histograms and Q-Q plots. Here I am explaining only the transformations of the training dataset. The same process should be applied to the testing dataset as well.</p><pre>X3 = X_train.copy() #copy of the training dataset <br>Y3 = X_test.copy() #copy of the testing dataset </pre><pre>stats.probplot(X3[&quot;Temperature (C)&quot;], dist=&quot;norm&quot;, plot=plt)plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*TJ3GFNwNWL2j6Rpdist7dQ.png" /><figcaption>Q-Q plot for Temperature</figcaption></figure><p>Likewise, for all the features we can analyze data distribution with Q-Q plots to see whether how data varies from the desired distribution(red line). Here we can see Temperature has a normal distribution.</p><p>But when we see the Q-Q plot for Wind Speed we can see data is skewed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*7DkNddAMEqeJfHLV4L0MPQ.png" /><figcaption>Q-Q plot for Wind Speed</figcaption></figure><p>Then we can plot histograms as well.</p><pre>X3.hist(figsize=(15,10))</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TVjsVpuMhDV2pK0eVbQfmA.png" /><figcaption>Histograms for training data</figcaption></figure><p>We can see that Humidity is left-skewed and Wind Speed is right-skewed. Visibility also shows some left-skewness but after applying transformations, it did not show a normal distribution. So I did not apply transformations for Visibility.</p><p>For right-skewed data, we apply logarithmic transformations and for left-skewed data, we can apply exponential transformations.</p><pre>logarithm_transformer = FunctionTransformer(np.log1p)<br>data_new1 = logarithm_transformer.transform(X3[&#39;Wind Speed (km/h)&#39;])<br>X3[&#39;Wind Speed (km/h)&#39;]=data_new1<br>X3[&#39;Wind Speed (km/h)&#39;].hist()</pre><p>Here I have used <em>np.log1p</em> since Wind Speed has 0.0 values, and <em>np.log</em> is only for positive numbers.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*57BLGnD1PGPeMAMJh_3OTA.png" /><figcaption>Histogram for Wind Speed after applying logarithm transformations</figcaption></figure><p>Now we can see Wind Speed has a normal distribution.</p><p>Since Humidity is left-skewed we apply exponential transformations.</p><pre>exp_transformer = FunctionTransformer(np.exp)<br>data_new2 = exp_transformer.transform(X3[&#39;Humidity&#39;])<br>X3[&#39;Humidity&#39;]=data_new2<br>X3[&#39;Humidity&#39;].hist()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*RdekQpvCKdDQmoAoAyzEVg.png" /><figcaption>Histogram for Humidity after applying exponential transformations</figcaption></figure><p>Here I have represented how the histograms have been changed after transformations.</p><p>Wind Speed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*eJccPU-uMskSo-P_kATl4g.png" /></figure><p>Humidity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*4Uyqr9V63IuoPf_QxuCzZw.png" /></figure><p>We can see with Q-Q plots and histograms Loud Cover is always 0.0. So since it has no effect we need to drop Loud Cover in both training and testing data.</p><pre>X3 = X3.drop([&#39;Loud Cover&#39;], axis=&#39;columns&#39;)<br>Y3 = Y3.drop([&#39;Loud Cover&#39;], axis=&#39;columns&#39;)</pre><p>Since Formatted Date is a unique value and Daily Summary is not a numerical value and it has so many different values we can drop them both.</p><pre>X3 = X3.drop(columns=[&#39;Daily Summary&#39;,&#39;Formatted Date&#39;])<br>Y3 = Y3.drop(columns=[&#39;Daily Summary&#39;,&#39;Formatted Date&#39;])</pre><h3>5. Feature Scaling — Standardization</h3><blockquote>Feature scaling refers to the methods used to normalize the range of values of independent variables.</blockquote><p>Here I have used Standardization for scaling. Standardization transforms the data to make the mean value 0 and unit standard deviation. This step is critical since it avoids the chance of the model being significantly affected by a variable with a large magnitude.</p><p>Standardization is not applied to categorical variables. So they should be kept aside before doing standardization for numeric features. Standardization should also be applied to both training and testing data separately.</p><p>Here, note that I have used <em>scaler.fit()</em> only for training data since we need the same parameters (mean and standard deviation) used for the training dataset to be applied for the training dataset as well.</p><pre>X4 = X3.copy()<br>Y4 = Y3.copy()</pre><pre>to_std_train = X4[[&#39;Temperature (C)&#39;, &#39;Humidity&#39;,&#39;Wind Speed (km/h)&#39;, &#39;Wind Bearing (degrees)&#39;, &#39;Visibility (km)&#39;,&#39;Pressure (millibars)&#39;]].copy()<br>to_std_test = Y4[[&#39;Temperature (C)&#39;, &#39;Humidity&#39;,&#39;Wind Speed (km/h)&#39;, &#39;Wind Bearing (degrees)&#39;, &#39;Visibility (km)&#39;,&#39;Pressure (millibars)&#39;]].copy()</pre><pre>scaler = StandardScaler()<br>scaler.fit(to_std_train)</pre><pre>train_scaled = scaler.transform(to_std_train)<br>test_scaled = scaler.transform(to_std_test)</pre><pre>std_df_train = pd.DataFrame(train_scaled, columns = to_std_train.columns)<br>std_df_test = pd.DataFrame(test_scaled, columns = to_std_test.columns)</pre><pre>X4[[&#39;Temperature (C)&#39;, &#39;Humidity&#39;,&#39;Wind Speed (km/h)&#39;,&#39;Wind Bearing (degrees)&#39;,&#39;Visibility (km)&#39;,&#39;Pressure (millibars)&#39;]]=std_df_train<br>Y4[[&#39;Temperature (C)&#39;, &#39;Humidity&#39;,&#39;Wind Speed (km/h)&#39;,&#39;Wind Bearing (degrees)&#39;,&#39;Visibility (km)&#39;,&#39;Pressure (millibars)&#39;]]=std_df_test</pre><p>After standardizing data, we can use a correlation matrix for correlation analysis.</p><pre>sns.heatmap(std_df_train.corr(),annot=True);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*KL50uDOxzlJhXSYwyTmEEQ.png" /><figcaption>Correlation matrix</figcaption></figure><p>We can that there is a negative correlation between Humidity and Temperature. So to answer the question <strong>is there a</strong> <strong>relationship between humidity and temperature? Yes. There is a negative correlation between humidity and temperature.</strong></p><h3>6. Discretization</h3><p>Discretization is used to transform a continuous variable into a discrete variable. Here we can see when plotting the histogram for Wind Bearing, it does not fit to a normal distribution. Machine learning models can perform better when numerical variables with non-standard probability distributions are made discrete. I have used K-means discretization for Wind Bearing.</p><pre>X5 = X4.copy()<br>Y5 = Y4.copy()</pre><pre>data1 = pd.DataFrame(X5, columns=[&#39;Wind Bearing (degrees)&#39;])<br>data1 = data1.dropna()<br>data2 = pd.DataFrame(Y5, columns=[&#39;Wind Bearing (degrees)&#39;])<br>data2 = data2.dropna()</pre><pre>discretizer = KBinsDiscretizer(n_bins=8, encode=&#39;ordinal&#39;, strategy=&#39;uniform&#39;)</pre><pre>discretizer.fit(data1)<br>_discretize1 = discretizer.transform(data1)<br>_discretize2 = discretizer.transform(data2)<br>X_dis = pd.DataFrame(_discretize1)<br>Y_dis = pd.DataFrame(_discretize2)<br>X_dis.hist()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*LcOcJVdcFGgLC7jcFdZH1A.png" /><figcaption>Histogram for Wind Bearing after discretization</figcaption></figure><p>We can plot a co-relation matrix to identify the significance of features for the target column which is Apparent Temperature.</p><blockquote>Correlation is a statistical measure that indicates the extent to which two or more variables fluctuate together.</blockquote><pre>X5[&#39;Wind Bearing (degrees)&#39;] = X_dis</pre><pre>d_data = X5[[&#39;Temperature (C)&#39;, &#39;Humidity&#39;,&#39;Wind Speed (km/h)&#39;,&#39;Wind Bearing (degrees)&#39;,&#39;Visibility (km)&#39;,&#39;Pressure (millibars)&#39;]].copy()</pre><pre>d_data[&#39;Apparent Temperature (C)&#39;] = y_train<br>d_data.head(10)<br>print(d_data.corr())<br>sns.heatmap(d_data.corr(),annot=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*AZDoiXq5mmX6nuHzaqTNzg.png" /><figcaption>Correlation matrix</figcaption></figure><p>We can see that Humidity and target variable Apparent Temperature has a significantly high correlation. So to answer the question <strong>is there a</strong> <strong>relationship between humidity and apparent temperature? Yes. There is a negative correlation between humidity and apparent temperature.</strong></p><h3>7. Dimensionality Reduction — Principal Component Analysis</h3><p>The importance of dimensionality reduction is that we can compress the dataset by removing redundancy and retaining only useful information. Too many input variables can lead to the curse of dimensionality and then the model will not be able to perform well because the model will also learn from noise in the training dataset and be overfitted.</p><p>Principal Component Analysis is a powerful technique used for dimensionality reduction, increasing interpretability but at the same time minimizing information loss.</p><pre>pca = PCA(n_components=12)<br>pca.fit(X5)<br>X_train_pca = pca.transform(X5)<br>X_test_pca = pca.transform(Y5)<br>principalDf = pd.DataFrame(data = X_train_pca)<br>principalDf.head(20)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XF6LKG-Js8PfdCTWzyAgw.png" /></figure><p>The value of the parameter <em>n_components</em> is decided by analyzing the <em>explained_component_ratio_</em> as below.</p><pre>pca.explained_variance_ratio_</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*IqXmrYwNqWBW6_XcFycSIg.png" /><figcaption>PCA explained variance ratio</figcaption></figure><p>When deciding the number of principal components to use we should consider the above values. The first elements of the array are the high variance dimensions and we should consider the sum of the high variance dimensions to be around 0.95. Here I have used 12 principal components.</p><h3>8. Linear Regression Model</h3><p>After completing all the above-discussed steps, a Linear regression model is applied to the dataset.</p><pre>lm = linear_model.LinearRegression()<br>model = lm.fit(X_train_pca,y_train)</pre><h3>9. Model Evaluation</h3><p>When we evaluate our model, an accuracy of 0.990223 can be seen.</p><pre>accuracy = model.score(X_test_pca, y_test)<br>print(&quot;Accuracy:&quot;, accuracy)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*SsQNn8Wmv0L_LkBnglwt-w.png" /></figure><p>To further evaluate the model we use mean squared error (MSE).</p><pre>predictions = lm.predict(X_test_pca)<br>y_hat = pd.DataFrame(predictions, columns=[&quot;predicted&quot;])<br>mse = mean_squared_error(y_test, y_hat)<br>print(&#39;Test MSE: %.3f&#39; % mse)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*kWVvfbTTg9A4afLT_ZxL0w.png" /></figure><p>And we have used calculated root mean squared error (RMSE) as well.</p><pre>rmse = sqrt(mean_squared_error(y_test, y_hat))<br>print(&#39;Test RMSE: %.3f&#39; % rmse)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*k7vrUoYqMRJBIHxhVGqX5w.png" /></figure><p>We can perform 6-fold cross-validation.</p><pre>scores = cross_val_score(model, X_test_pca, y_test, cv=6)<br>print(&quot;Cross-validated scores:&quot;, scores)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*2wBYpoHY1u4O26mny8SuJQ.png" /></figure><p>With the below code, I calculated cross-predicted accuracy.</p><pre>predictions = cross_val_predict(model, X_test_pca, y_test, cv=6)<br>accuracy = metrics.r2_score(y_test, predictions)<br>print(&quot;Cross-Predicted Accuracy:&quot;, accuracy)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*2zGswLTgUd1hqBzjAjPrkQ.png" /></figure><p>The accuracy of the model is good. But it is important to check the weight parameters also.</p><p>Weight parameters are an important indicator of the model performing well with the new data. If the weight parameters are less then it means your model is pretty good and will perform better with unseen data.</p><pre>#W parameters of the model<br>print(lm.coef_)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*5weN1oXdlQMBBhL6s1q3Iw.png" /></figure><p>Here, the weight parameters are not very low. But we can further reduce them by identifying and changing some steps we did while preprocessing, transformations, etc.</p><p>We can visualize the predictions of the model as below. Here I have plotted the graph only for 100 data points.</p><pre>plt.figure(figsize=(15, 7))<br>plt.plot(y_hat[:100], label = &quot;Predicted&quot;)<br>plt.plot(y_test[:100], label = &quot;Actual&quot;)<br>plt.title(&#39;Predictions Vs Actual&#39;)<br>plt.legend()<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UgTodn_p9dA6dtxRZf-qA.png" /><figcaption>Predictions vs Actual data graph</figcaption></figure><h3>10. Conclusion</h3><p>In this article, I gave you a step-by-step guide on how to build a machine learning model by applying data cleansing, data transformations, feature coding, feature scaling, discretization, dimensionality reduction and I have also evaluated the linear regression model.</p><p>I hope this article helped you to gain a good understanding of the important steps we should follow and the main concepts behind them to build a good machine learning model.</p><p>Happy Coding!</p><h3>11. Colab Code</h3><p><a href="https://colab.research.google.com/drive/1C4GlUeLKhiC-1aX0D63M88_Rw-K7nCTc?usp=sharing">Google Colaboratory</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30a50fc12f7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/understanding-the-process-of-building-a-machine-learning-model-for-a-real-world-scenario-30a50fc12f7f">Understanding the Process of Building a Machine Learning Model for a Real World Scenario</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>
        <item>
            <title><![CDATA[How to import Kaggle Datasets into Google Colab]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-import-kaggle-datasets-into-google-colab-fb23c1566be3?source=rss-3fb0df000e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb23c1566be3</guid>
            <category><![CDATA[google-colab]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[dataset]]></category>
            <dc:creator><![CDATA[Manusha Priyanjalee]]></dc:creator>
            <pubDate>Fri, 12 Mar 2021 13:05:43 GMT</pubDate>
            <atom:updated>2021-06-28T16:34:44.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L6YBDmK1ujHZURgV" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Kaggle is a great place for those who are trying to improve their data science/analytics skills. It has a huge number of public datasets you can download and use. You can use these Kaggle datasets without downloading them to your PC but by importing them to Google Colaboratory. Colab is a free Jupyter notebook environment and it runs entirely in the cloud. It allows you to write and execute Python code through the browser.</p><p>So, let’s see how you can easily import a Kaggle dataset to Colab and I will also provide some useful Python code to analyze the dataset you imported.</p><ol><li>Create a Kaggle account. You already have a Google account right?</li><li>Copy the Kaggle API token</li></ol><p>Go to your account and click on Create New API Token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ClCpuxsoe4X_WI77ehA9fA.png" /></figure><p>A kaggle.json file will be downloaded.</p><p>3. Upload the kaggle.json file into your Google drive inside a folder. I named mine Kaggle. This is the folder where we are going to store our dataset.</p><p>4. Create a new Colab notebook.</p><p>Now we have to write some code in our Colab notebook.</p><pre>from google.colab import drive<br>drive.mount(&#39;/content/gdrive&#39;)</pre><p>This will mount the drive to Colab. You will be asked to provide an authorization code.</p><pre>import os<br>os.environ[&#39;KAGGLE_CONFIG_DIR&#39;] = &quot;/content/gdrive/My Drive/Kaggle&quot;</pre><p>This provides the config path to the kaggle.json file inside my Kaggle folder.</p><pre>%cd /content/gdrive/My Drive/Kaggle</pre><p>Change the present working directory as shown above.</p><p>Now go to your Kaggle dataset and copy the API command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RReLJ8VQthEdvvZjCuuiEw.png" /></figure><p>Now in your Colab notebook run the below command. kaggle datasets download -d new-york-city/nyc-parking-tickets is the API command I copied for my dataset.</p><pre>!kaggle datasets download -d new-york-city/nyc-parking-tickets</pre><p>You will have the result as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*JQuw3Zh5wb0YesaAltCEdg.png" /></figure><p>Use the below command to unzip and delete the zip file.</p><pre>!unzip \*.zip  &amp;&amp; rm *.zip</pre><p>You will have the output as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*48ro6c9X6mWM973qwOTzYA.png" /></figure><p>That’s it. You have successfully imported your Kaggle dataset into Colabs. 😀</p><p>I hope this article helped you to work on your data science projects easier by importing Kaggle datasets into Colab.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb23c1566be3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-import-kaggle-datasets-into-google-colab-fb23c1566be3">How to import Kaggle Datasets into Google Colab</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[What is JSON? It is a lightweight format for data interchange.]]></title>
            <link>https://medium.com/analytics-vidhya/what-is-json-it-is-a-lightweight-format-for-data-interchange-7b8ad8732b62?source=rss-3fb0df000e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b8ad8732b62</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Manusha Priyanjalee]]></dc:creator>
            <pubDate>Fri, 30 Oct 2020 18:47:00 GMT</pubDate>
            <atom:updated>2021-06-28T16:35:40.342Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s see how JSON is capable of improving the interactivity on the web.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mty2FBFQK9EfiVgJ" /><figcaption>Photo by <a href="https://unsplash.com/@vmxhu?utm_source=medium&amp;utm_medium=referral">Szabo Viktor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is JSON?</h3><p><strong>JSON</strong> stands for <strong>J</strong>ava<strong>S</strong>cript <strong>O</strong>bject <strong>N</strong>otation. It is a lightweight text-based format used for interchanging data. It is very commonly used in web applications. It resembles JavaScript object literal syntax, but many other programming environments other than JavaScript possess the ability to work with JSON which makes it programming language independent. With ‘work’, it means to generate and read JSON data.</p><p>JSON is built on 2 structures; a collection of name/value pairs and an ordered list of values such as an array, list, etc. We can include objects, strings, numbers, booleans, arrays, and null inside JSON.</p><p>Let’s get a JSON object for an example. A JSON object means an unordered list of name/value pairs. { “name” : “value” }</p><pre>{ &quot;name&quot; : &quot;Kavindya&quot;,<br>  &quot;age&quot; : 25,<br>  &quot;address&quot; : {<br>        &quot;city&quot; : &quot;Galle&quot;,<br>        &quot;country&quot;: &quot;Sri Lanka&quot;<br>  },<br>  &quot;hobbies&quot; : [ &quot;watching movies&quot;, &quot;reading books&quot; ],<br>  &quot;isStudent&quot; : true<br>}</pre><p>We can assign this data into a variable called personDetails. Then we can access this data with personDetails.name, personDetails.address, personDetails.address.country, personDetails.hobbies etc.</p><p>Then let’s take an array. It is an ordered list of values. [ value1, value2 ] This value can be a string, number, array, object, boolean or null.</p><pre>[<br>  { &quot;name&quot; : &quot;Kavindya&quot;,<br>    &quot;age&quot; : 25,<br>    &quot;address&quot; : {<br>          &quot;city&quot; : &quot;Galle&quot;,<br>          &quot;country&quot;: &quot;Sri Lanka&quot;<br>    },<br>    &quot;hobbies&quot; : [ &quot;watching movies&quot;, &quot;reading books&quot; ],<br>    &quot;isStudent&quot; : true<br>  },<br>  { &quot;name&quot; : &quot;Dakota&quot;,<br>    &quot;age&quot; : 24,<br>    &quot;address&quot; : {<br>          &quot;city&quot; : &quot;Colombo&quot;,<br>          &quot;country&quot;: &quot;Sri Lanka&quot;<br>    },<br>    &quot;hobbies&quot; : [ &quot;gardening&quot;, &quot;playing tennis&quot; ],<br>    &quot;isStudent&quot; : false<br>  }<br>]</pre><p>Let’s assign this array to variable personDetails. Then we can access data in the array using the array index. As an example use personDetails[0].name to get the value “Kavindya”. When you use index 1 you will get details about Dakota because it is the second record in the array.</p><p>JSON ignores whitespace between JSON elements so we can organize our data in JSON giving enough spaces between name/value pairs since then it is easier for us to read.</p><h3>Why JSON is important?</h3><p>With the arrival of AJAX, we could</p><blockquote>Read data from a web server — after a web page has loaded</blockquote><blockquote>Update a web page without reloading the page</blockquote><blockquote>Send data to a web server — in the background</blockquote><p>So it became important for websites to load data more quickly and asynchronously, without delaying page rendering. JSON enables faster accessibility and memory optimization than XML (<strong>E</strong>xtensible <strong>M</strong>arkup <strong>L</strong>anguage). So that JSON is often used with AJAX.</p><h3>How to work with JSON strings in JavaScript</h3><p>We make JavaScript variables. But often we need to convert JavaScript variables into JSON data and convert JSON data into JavaScript.</p><p>JavaScript built-in method, JSON.stringify() can be used to output a JSON string from a JavaScript variable.</p><pre>var data = {<br>    &quot;id&quot; : 1,<br>    &quot;username&quot; : &quot;Alice&quot;,<br>    &quot;subjects&quot; : [ &quot;Maths&quot;, &quot;Science&quot; ]<br>} </pre><p>With JSON.stringify(data) we can produce the below output.</p><pre>{ &quot;id&quot;: 1, &quot;username&quot;: &quot;Alice&quot;, &quot;subjects&quot;: [ &quot;Maths&quot;, &quot;Science&quot; ] }</pre><p>To parse a JSON string to JavaScript we can use the built-in method JSON.parse(). It outputs a JavaScript object or array from a JSON string.</p><pre>var jsonData = { &quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25 };</pre><pre>var obj = JSON.parse(jsonData);</pre><p>Now we can access name and age values with obj.name and obj.age in JavaScript.</p><h3>How to work with JSON in Java</h3><p>JSON-Java which is also known as org.json is one of the Java libraries that allows JSON data processing. This library provides various classes that can be used for parsing, manipulating, and converting JSON data.</p><p>You can find a complete introduction to JSON-Java from Baeldung here. <a href="https://www.baeldung.com/java-org-json"><em>https://www.baeldung.com/java-org-json</em></a></p><p>I hope this article helped you to get a basic understanding of JSON.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b8ad8732b62" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/what-is-json-it-is-a-lightweight-format-for-data-interchange-7b8ad8732b62">What is JSON? It is a lightweight format for data interchange.</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[Getting started with React Hooks]]></title>
            <link>https://medium.com/analytics-vidhya/getting-started-with-react-hooks-a21cfb09dc5d?source=rss-3fb0df000e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21cfb09dc5d</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Manusha Priyanjalee]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 20:26:14 GMT</pubDate>
            <atom:updated>2021-06-28T16:33:54.187Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to use useState(), useEffect() and useContext()</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*40Onpelhaj1Rmv1N" /><figcaption>Photo by <a href="https://unsplash.com/@goshua13?utm_source=medium&amp;utm_medium=referral">Joshua Aragon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hooks are special functions that allow us to do various things without writing a class. Before hooks come into play, we could use state and life cycle methods only inside class components. But with React hooks, now we can use functional components for almost everything from rendering UI to handling state and logic in a pretty neat way.</p><p>We should also keep in mind that hooks are not to be used inside loops, conditions, or nested functions. Hooks should be used at the top-level inside your functional components.</p><p>In this blog post, I am going to guide you through how to use 3 of the most frequently used React hooks.</p><p>Let’s dive right in.</p><h3>1. useState()</h3><p>useState() hook lets you add and manipulate state in your functional component. In order to use it in the component, you need to import it.</p><pre>import {useState} from &#39;react&#39;</pre><p>Then with the use of array destructuring, we can simply write the code as below.</p><pre>const [state, setState] = useState(initialState)</pre><p>You can pass the initial state to the useState() and it returns the state variable which holds the current state value and a setState function to handle that state value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86c314a5ad78bb51e45fcaede445ebe9/href">https://medium.com/media/86c314a5ad78bb51e45fcaede445ebe9/href</a></iframe><h3>2. useEffect()</h3><p>useEffect() hook let us handle the logic in lifecycle methods. It means that whenever something affects your component useEffect() hook will be called. Those effects are referred to as side effects in React hooks documentation.</p><p>First, you need to import is as below.</p><pre>import {useEffect} from &#39;react&#39;</pre><p>For useEffect() we should pass a function and we call it as the effect. We can provide an array as the second argument. But if we do not pass an array into useEffect() , the component will repeatedly reload.</p><pre>useEffect(() =&gt; {<br>    console.log(&quot;Function is being called repeatedly.&quot;);<br>})</pre><p>When you pass an empty array as the second argument, then the arrow function will only be called at the first render.</p><pre>useEffect(() =&gt; {<br>    console.log(&quot;Function has been called only once.&quot;);<br>},[])</pre><p>When we pass an array for the second argument, useEffect() checks whether the array values have been changed. So only if the values are different, the arrow function will be called.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25154aa9f77c44a41fb3943b432b1cfa/href">https://medium.com/media/25154aa9f77c44a41fb3943b432b1cfa/href</a></iframe><h3>3. useContext()</h3><p>useContext() hook gives easy access to your context in functional components.</p><p>useContext() hook works with Context API. Context API is used for state management in React. It has been designed to use when we have to deal with data that required to be used globally in our application such as theme and preferred language. With the use of Context API, we can avoid prop drilling when sharing data among components.</p><p>Creation of context can be done with React.createContext .</p><pre>const MyContext = React.createContext(defaultValue)</pre><p>A provider component is used to allow consuming components to subscribe to the changes in the context. Consuming components should be wrapped by the provider component.</p><pre>&lt;MyContext.Provider value = {anyValue}&gt;&lt;/MyContext.Provider&gt;</pre><p>Then in the consumer components useContext() is used. useContext() can be imported as below.</p><pre>import {useContext} from &#39;react&#39;</pre><p>useContext() accepts a context object and returns the context value of that object. So as the argument, pass the context object to useContext() and, then we can use the value in the component.</p><pre>const value = useContext(MyContext)</pre><p>Now let’s try using useContext() with a simple example of how to apply a color theme to an application. First, let’s create the context file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e32d54b3c0031a91fc978f3747929a5f/href">https://medium.com/media/e32d54b3c0031a91fc978f3747929a5f/href</a></iframe><p>Then as we want to add the color theme for the entire app, we should use the context provider in our App component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe237ce523359ad2af4bc2788dea905f/href">https://medium.com/media/fe237ce523359ad2af4bc2788dea905f/href</a></iframe><p>Here we can change the theme by providing it as the value of the ThemeContext.Provider . If you want the dark theme, you can apply value={themes.dark} .</p><p>Finally, we can consume the context using useContext() in our component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1749317f8c54d919d0ba1df6b8758f61/href">https://medium.com/media/1749317f8c54d919d0ba1df6b8758f61/href</a></iframe><p>I hope you could get a good understanding of how to use useState() , useEffect() , and useContext() hooks in React.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21cfb09dc5d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/getting-started-with-react-hooks-a21cfb09dc5d">Getting started with React Hooks</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[Understanding the map() function in React.js]]></title>
            <link>https://medium.com/analytics-vidhya/understanding-the-map-function-in-react-js-1d211916fea7?source=rss-3fb0df000e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d211916fea7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Manusha Priyanjalee]]></dc:creator>
            <pubDate>Sun, 31 May 2020 11:18:10 GMT</pubDate>
            <atom:updated>2022-01-22T04:34:26.010Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s learn how to transform one array into another array.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gy5l2uYJJjxZbREe" /><figcaption>Photo by <a href="https://unsplash.com/@christinhumephoto?utm_source=medium&amp;utm_medium=referral">Christin Hume</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Array map() function in JavaScript is used to create a new array with a given array, by executing a function for all the elements in the given array. Consider the below illustration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*_yztWB1qf8SOIJmTy9Hfcw.png" /></figure><p>Here we have an array of objects called PersonDetails array. For example, suppose you want to get an array of person names like the PersonNames array. For this purpose, we can use the map() function in JavaScript. It will convert the PersonDetails array into PersonNames array.</p><p>Below is the PersonDetails array.</p><pre>const PersonDetails = [<br>           {id: 1, name: &quot;Kyle&quot;, age: 23},<br>           {id: 2, name: &quot;Taylor&quot;, age: 45},<br>           {id: 3, name: &quot;Anna&quot;, age: 30}<br>]</pre><p>Now let’s convert this array into PersonNames array.</p><pre>const PersonNames = PersonDetails.map(person =&gt; person.name);</pre><p>That’s a basic overview of how the map() function can be used in JavaScript. Now let’s move on to learn how it can be used in React.js.</p><pre>import React from &#39;react&#39;;</pre><pre>function Details() {<br>   const PersonDetails = [<br>            {id: 1, name: &quot;Kyle&quot;, age: 23},<br>            {id: 2, name: &quot;Taylor&quot;, age: 45},<br>            {id: 3, name: &quot;Anna&quot;, age: 30}<br>   ]</pre><pre>   const PersonNames = PersonDetails.map(person =&gt; <br>                         &lt;li key={person.id}&gt;{person.name}&lt;/li&gt;)</pre><pre>   return(<br>      &lt;div&gt;<br>         &lt;ul&gt;{PersonNames}&lt;/ul&gt;<br>      &lt;/div&gt;<br>   )<br>}</pre><pre>export default Details;</pre><p>Here the attribute key should be provided to give elements of the array a stable identity. Keys are important because it lets React identify the changed, newly added or removed items.</p><p>When data is in another js file, you need to export PersonDetails array in your js file.</p><pre>export const PersonDetails = [<br>          {id: 1, name: &quot;Kyle&quot;, age: 23},<br>          {id: 2, name: &quot;Taylor&quot;, age: 45},<br>          {id: 3, name: &quot;Anna&quot;, age: 30}<br>]</pre><p>Then you can import the array in your component like below.</p><pre>import {PersonDetails} from &#39;./PersonDetails&#39;</pre><p>If you want to export your data file as default, then you can do it as follows.</p><pre>const PersonDetails = [ <br>          {id: 1, name: &quot;Kyle&quot;, age: 23},<br>          {id: 2, name: &quot;Taylor&quot;, age: 45},<br>          {id: 3, name: &quot;Anna&quot;, age: 30}<br>]</pre><pre>export default PersonDetails;</pre><p>Then you can import the data file in your component.</p><pre>import PersonDetails from &#39;./PersonDetails&#39;</pre><p>Now let’s try another way of doing this.</p><p>We can even return components in the map() function. Consider data is in another file as explained before.</p><p>Below is the component file. You need to pass props to your component. Here I have passed down person details as one object (p), rather than passing down each individual property of person details. Now I can access the property through props.p.{name of the property}.</p><pre>import React from &#39;react&#39;;</pre><pre>function Details(props) {<br>   return(<br>      &lt;div&gt;<br>         &lt;ul&gt;<br>            &lt;li&gt;{props.p.name}&lt;/li&gt;<br>         &lt;/ul&gt;<br>      &lt;/div&gt;<br>   )<br>}</pre><pre>export default Details;</pre><p>In App.js file let’s return the Details component with map() function.</p><pre>import React from &#39;react&#39;;<br>import Details from &#39;./Details&#39;;<br>import PersonDetails from &#39;./PersonDetails&#39;<br>import &#39;./App.css&#39;;</pre><pre>function App() {<br>   const PersonNames = PersonDetails.map(person =&gt; <br>                          &lt;Details key={person.id} p={person} /&gt;)</pre><pre>   return (<br>      &lt;div&gt;<br>         {PersonNames}<br>      &lt;/div&gt;<br>   )<br>}</pre><pre>export default App;</pre><p>I hope you could get a good understanding of the map() function in React.js from this article.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d211916fea7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/understanding-the-map-function-in-react-js-1d211916fea7">Understanding the map() function in React.js</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[Understanding RxJS Observables]]></title>
            <link>https://medium.com/analytics-vidhya/understanding-rxjs-observables-ad5b34d9607f?source=rss-3fb0df000e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad5b34d9607f</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[observables]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Manusha Priyanjalee]]></dc:creator>
            <pubDate>Tue, 26 May 2020 11:37:05 GMT</pubDate>
            <atom:updated>2021-06-28T16:36:41.664Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s look into Reactive Programming with RxJS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GeVNGDXTBjt8M9sU" /><figcaption>Photo by <a href="https://unsplash.com/@jeffreyp?utm_source=medium&amp;utm_medium=referral">Jeffrey Workman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this blog post I am going to give you a basic understanding of RxJS observables and how to use them in Angular.</p><p>First, let me mitigate the confusion by simplifying the terms in the topic of the article.</p><h3>What’s Reactive Programming?</h3><p>Reactive programming means programming with asynchronous data streams. A stream is a sequence of data ordered in time. Data streams can be created with anything like variables, changes on a variable, properties, user inputs, data structures, click events, HTTP requests, etc. So with reactive programming, you can observe data streams and when you observe that a value is emitted you can react accordingly.</p><h4>A little bit more about data streams.</h4><p>A stream does not emit only the values as stated above. During its timeline a stream can also emit an error when some unexpected event occurred causing the stream to end, or a complete signal as the stream may complete when the user closes the window. So we can catch these streams to execute functions according to them.</p><h3>What’s RxJS?</h3><p>RxJS is a JavaScript library that allows us to work with reactive programming. RxJS uses observables to compose asynchronous code and provides functions to work with observables.</p><h3>The Big Topic: Observables</h3><h4>What’s an observable?</h4><p>An observable is a function that acts as a wrapper for a data stream. They support to pass messages inside your application. An observable is useless until an observer subscribes to it. An observer is an object which consumes the data emitted by the observable. An observer keeps receiving data values from the observable until the observable is completed, or the observer unsubscribes from the observable. Otherwise observers can receive data values from the observable continuously and asynchronously. So we can perform various operations such as updating the user interface, or passing the JSON response.</p><p>There are 4 stages for a life cycle of an observable.</p><ol><li>Creation</li><li>Subscription</li><li>Execution</li><li>Destruction</li></ol><h4>Let’s understand these 4 stages with Angular.</h4><p>You need to import the RxJS library to create an observable.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Observable } from &#39;rxjs&#39;;</pre><pre>@Component({<br>   selector: &#39;app-root&#39;,<br>   templateUrl: &#39;./app.component.html&#39;,<br>   styleUrls: [&#39;./app.component.scss&#39;]<br>})</pre><pre>export class AppComponent {<br>   title = &#39;observable&#39;;</pre><pre>ngOnInit() {<br>   var observable = Observable.create()<br>}<br>}</pre><p>This is how you can create an observable. But observables are useless until you subscribe to them. The below code shows how you can subscribe to an observable.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Observable } from &#39;rxjs&#39;;</pre><pre>@Component({<br>selector: &#39;app-root&#39;,<br>templateUrl: &#39;./app.component.html&#39;,<br>styleUrls: [&#39;./app.component.scss&#39;]<br>})</pre><pre>export class AppComponent {<br>   title = &#39;observable&#39;;</pre><pre>ngOnInit() {<br>   var observable = Observable.create((observer: any) =&gt; {<br>      observer.next(&#39;Hello world!&#39;)<br>   })</pre><pre>observable.subscribe(function showMessage(msg: any) {<br>      console.log(msg)<br>   })<br>}<br>}</pre><p>When you check the console, observer.next() value can be seen there.</p><p>Now let’s try executing observables.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Observable } from &#39;rxjs&#39;;</pre><pre>@Component({<br>   selector: &#39;app-root&#39;,<br>   templateUrl: &#39;./app.component.html&#39;,<br>   styleUrls: [&#39;./app.component.scss&#39;]<br>})</pre><pre>export class AppComponent {<br>   title = &#39;observable&#39;;</pre><pre>ngOnInit() {<br>   var observable = Observable.create((observer: any) =&gt; {<br>      observer.next(&#39;A&#39;)<br>      observer.next(&#39;B&#39;)<br>      observer.error(&#39;Error occured.&#39;)<br>      observer.complete(&#39;Data stream is over.&#39;)<br>      observer.next(&#39;C&#39;)<br>   })</pre><pre>observable.subscribe(function showMessage(msg: any) {<br>      console.log(msg)<br>   })<br>}<br>}</pre><p>If an error or completion occurred it will automatically stop the execution. You can only see ‘A’ and ‘B’ printed in the console.</p><p>Let’s try making this asynchronous with the help of the setInterval() method.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Observable } from &#39;rxjs&#39;;</pre><pre>@Component({<br>   selector: &#39;app-root&#39;,<br>   templateUrl: &#39;./app.component.html&#39;,<br>   styleUrls: [&#39;./app.component.scss&#39;]<br>})</pre><pre>export class AppComponent {<br>   title = &#39;observable&#39;;</pre><pre>ngOnInit() {<br>   var observable = Observable.create((observer: any) =&gt; {<br>      observer.next(&#39;A&#39;)<br>      observer.next(&#39;B&#39;)</pre><pre>setInterval(() =&gt; {<br>         observer.next(&quot;This is a random message.&quot;)<br>      }, 2000)</pre><pre>observer.next(&#39;C&#39;)<br>      observer.next(&#39;D&#39;)</pre><pre>setInterval(() =&gt; {<br>         observer.error(&quot;Error occured.&quot;)<br>      }, 4001)</pre><pre>observer.next(&#39;E&#39;)<br>   })</pre><pre>observable.subscribe(function showMessage(msg: any) {<br>      console.log(msg)<br>   })<br>}<br>}</pre><p>Your console will look like below. Here we the display of the values is done asynchronously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*TdGOox_21vfieUeqIMgQtQ.png" /></figure><p>Destroying an observable means removing it from the DOM by unsubscribing to it. Normally RxJS takes care of destroying an observable by unsubscribing to it after an error or a completion occurred.</p><h4>Importance of Observables</h4><p>Observables are lazy. It means that if it is not subscribed then it will not emit data. And also, handling asynchronous data emitting that has multiple data values is easier with observables.</p><p>So this is a basic introduction to RxJS observables with Angular and hope it helped you to understand what observables are.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad5b34d9607f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/understanding-rxjs-observables-ad5b34d9607f">Understanding RxJS Observables</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[Socket Programming in Java]]></title>
            <link>https://medium.com/analytics-vidhya/socket-programming-in-java-75918f7e99bf?source=rss-3fb0df000e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/75918f7e99bf</guid>
            <category><![CDATA[socket-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clients]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[servers]]></category>
            <dc:creator><![CDATA[Manusha Priyanjalee]]></dc:creator>
            <pubDate>Mon, 30 Mar 2020 16:45:57 GMT</pubDate>
            <atom:updated>2021-06-28T16:37:45.440Z</atom:updated>
            <content:encoded><![CDATA[<h4>Make a connection with the outside world with your java application.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*waSwMn_v_mzAFEAn" /><figcaption>Photo by <a href="https://unsplash.com/@christianw?utm_source=medium&amp;utm_medium=referral">Christian Wiediger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello there, in this blog post I’m gonna explain how can a java program in your machine can reach out and touch a program running on another machine.</p><p>To get you through this I’m gonna develop simple client and server programs. And I will make them talk to each other. For all these client-server connections I need sockets. So that’s a quick overview to give you a brief idea. Let’s get started.</p><p>First let’s consider clients. There are 3 things we have to do with client programs.</p><ol><li>How to establish the initial <strong>connection</strong> between the client and the server.</li><li>How to <strong>send</strong> messages to the server.</li><li>How to <strong>receive</strong> messages from the server.</li></ol><p>To make the connection with a server we need a Socket connection. A Socket means an object that comes with java.net.Socket class. It is used to represent a network connection between 2 machines. To make this Socket object we need the IP address of the machine and TCP port number. An IP address identifies a host/computer on a computer network that uses the Internet Protocol for communication and a port is a communication endpoint. There is a specific port number for each process in an operating system. As port numbers from 0 to 1023 are reserved for well-known services such as HTTP, FTP, POP3, Telnet, etc we can use any other port number for our programs between 1024 and 65535.</p><p><strong><em>Socket clientSocket = new Socket(“127.0.0.1”, 5000);</em></strong></p><p>To send data to the server, the client has to give an output to the server. We use PrintWriter to write data to a Socket.</p><p><strong><em>PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());</em></strong></p><p><strong><em>writer.println(“Hello Server !”);</em></strong></p><p><strong><em>writer.print(“Hello!”);</em></strong></p><p>To receive data from a Socket a BufferedReader is used. Data is an input to the client.</p><p><strong><em>InputStreamReader stream = new InputStreamReader(clientSocket.getInputStream());</em></strong></p><p><strong><em>BufferedReader reader = new BufferedReader(stream);</em></strong></p><p><strong><em>String message = reader.readLine();</em></strong></p><p>Now let’s consider servers.</p><p>Above 3 tasks are applicable to servers as well. But there is a difference when we consider the server socket. When a client makes a connection request to the server, the server accepts the connection. Upon acceptance, the server gets a new socket bound to a different port. It needs a new socket (it means a different port number) as the server needs the original socket with the original port number to listen to new client requests while providing the service to the already connected client. The accept() method in the ServerSocket class in Java is used for this purpose. It returns a new Socket on a different port to communicate with the already connected client.</p><p><strong><em>ServerSocket server = new ServerSocket(5000);</em></strong></p><p><strong><em>Socket newSocket = server.accept();</em></strong></p><p>So let’s code a simple server and a simple client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*doNpL_xLqsXAswR6WMh4iA.png" /><figcaption>Server program in Java</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*5HF_e4rBg8nOnlhWsMPE-Q.png" /><figcaption>Client program in Java</figcaption></figure><p>First run server program and then run client program. Here the server program can serve not only one client because I have included the code in a permanent loop. If not, the server will not create a new Socket after one client is connected to the server. You can get the output as below after servicing 2 clients by the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*ZXyLomFyaeL_79g7pT2Biw.png" /><figcaption>Output of the server program</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*R2m69ZwH9vf1eBCAEEDnlA.png" /><figcaption>Output of the client program</figcaption></figure><p>This blog post covers the basics of socket programming in Java and I hope this article helped you to get a good understanding of it.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75918f7e99bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/socket-programming-in-java-75918f7e99bf">Socket Programming in Java</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[OOP Concepts: Encapsulation]]></title>
            <link>https://manushapriyanjalee.medium.com/oop-concepts-encapsulation-3363ce14ef56?source=rss-3fb0df000e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3363ce14ef56</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[encapsulation]]></category>
            <dc:creator><![CDATA[Manusha Priyanjalee]]></dc:creator>
            <pubDate>Wed, 01 Jan 2020 10:01:08 GMT</pubDate>
            <atom:updated>2021-06-28T16:39:32.000Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical guide with Java</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iM9tM3FQNbiDYU2g" /><figcaption>Photo by <a href="https://unsplash.com/@anshu18?utm_source=medium&amp;utm_medium=referral">Anshu A</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Encapsulation is one of the four pillars of object-oriented programming. It describes the idea of wrapping of data (variables) and code acting on the data (methods) together as one single unit.</p><p>Consider a program like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ZI4U0KnsI4qW-tDrzYgE5Q.jpeg" /><figcaption>A program without using the encapsulation concept</figcaption></figure><p>In this program the instance variables are exposed. Exposed means you can reach the variable with the dot operator, as in: <em>r.marks = 80</em>. Think about the idea of anyone using the reference variable to make a direct change to the marks instance variable like: <em>r.marks = -10</em>. This can destroy your whole effort because you are leaving your data out there for anyone to see and change.</p><p>To avoid such vulnerabilities we need to create setter and getter methods for all the instance variables. So we can deny marks variable having unacceptable values assigned for it. For example marks cannot be negative.</p><p>For this we need <strong>private </strong>and <strong>public</strong> access modifiers. Make the <strong>instance variables private</strong> and <strong>setter and getter methods public</strong>. But for this situation we also need to include some conditions in setter methods to avoid instance variables being assigned unacceptable values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*t0ZNueiKp1NIs7nyxbD9rw.jpeg" /><figcaption>Record class using encapsulation concept</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*y5844sQZCVZd3KUyX7QY4A.jpeg" /><figcaption>Class with the main method</figcaption></figure><p>Now no one can give an unacceptable value for both marks and rank variables. The output is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*qMEhNpSrNz_pUlDZaafJrA.jpeg" /><figcaption>Output of the above program</figcaption></figure><p>Now you may have the question that some setter methods simply set the value without checking any condition. Let’s take <em>setStudent()</em> method. It simply set the name of the student. We can do the same with the reference variable and dot operation if we make the student variable public.</p><p>But what if you had to change the code later and many other people are already using your Record class with public instance variable student. Everyone’s code has to change according to the changes you are adding. But if you have created a setter method for it then you can change your code anytime without breaking anyone else’s code. This is the main point of using setter and getter methods.</p><p>I hope this article helped you to get a clear understanding of encapsulation.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3363ce14ef56" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>