<?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 Aryan Jain on Medium]]></title>
        <description><![CDATA[Stories by Aryan Jain on Medium]]></description>
        <link>https://medium.com/@aryanjain_34085?source=rss-6541cba06d5f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rAsRwrXtlzK_K49x.</url>
            <title>Stories by Aryan Jain on Medium</title>
            <link>https://medium.com/@aryanjain_34085?source=rss-6541cba06d5f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:29:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aryanjain_34085/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[Machine Learning]]></title>
            <link>https://medium.com/@aryanjain_34085/machine-learning-dca1c849ffd8?source=rss-6541cba06d5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dca1c849ffd8</guid>
            <dc:creator><![CDATA[Aryan Jain]]></dc:creator>
            <pubDate>Sat, 12 Oct 2019 15:57:04 GMT</pubDate>
            <atom:updated>2019-11-01T20:08:53.377Z</atom:updated>
            <content:encoded><![CDATA[<h3>Divorce Prediction using Machine Learning Algorithms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*yCrFCAmgOukq6SKrO-dBJw.png" /><figcaption>“Machine learning is the new electricity”- Andrew Ng, Chief Scientist Baidu</figcaption></figure><p>Machine learning as described by Tom Mitchell is the study of algorithms that</p><ul><li>improve their performance P</li><li>at some task T</li><li>with experience E.</li></ul><p>A well-defined learning task is given by &lt;P, T, E&gt;.</p><p>To give a suitable analogy, consider how you were taught to recognize shapes, animals as a child by providing you with tons of examples. The same way we feed <strong>training data </strong>(examples) into machine learning model of our choice to make it learn and then we test it using unseen <strong>test data</strong>. This is what machine learning is all about — making computers “learn” by providing them with examples and then making them analyze new unseen data and predict something that is of some interest to us. For example, we can make computers predict the type of animal in an image, house prices based on some information about related attributes.</p><h3><strong>Types of Machine Leaning</strong></h3><p>Machine learning can be broadly categorized into 3 types:-</p><h4>1. Supervised Learning</h4><ul><li>Learning a function that maps an input to an output based on example input-output pairs.</li></ul><h4>2. Unsupervised Learning</h4><ul><li>Finding patterns in given data without pre-defined set of labels</li></ul><h4>3. Reinforcement Learning</h4><ul><li>It is all about taking certain actions in an environment to maximize reward</li></ul><h3><strong>Terminology</strong></h3><h4>1. Features</h4><ul><li>Input data that we feed into the model based on which certain predictions are made.</li></ul><h4>2. Target</h4><ul><li>It is what we are trying to predict (label in <strong>classification</strong> and some real value in <strong>regression</strong>).</li></ul><h3><strong>Attribute Information and Dataset Description</strong></h3><p><strong>DATASET LINK: </strong><a href="https://archive.ics.uci.edu/ml/datasets/Divorce+Predictors+data+set">https://archive.ics.uci.edu/ml/datasets/Divorce+Predictors+data+set</a></p><p>I am going to take a classification dataset (divorce) and going to predict whether the couple will get divorced or not using certain classification algorithms explaining what each one does in brief along the way. The performance of the model will be judged on the basis of accuracy ((no of times it was correct/Total no of predictions made)* 100). The features in this dataset are as follows:-</p><p>1. When one of our apologies apologizes when our discussions go in a bad direction, the issue does not extend. <br>2. I know we can ignore our differences, even if things get hard sometimes. <br>3. When we need it, we can take our discussions with my wife from the beginning and correct it. <br>4. When I argue with my wife, it will eventually work for me to contact him. <br>5. The time I spent with my wife is special for us. <br>6. We don’t have time at home as partners. <br>7. We are like two strangers who share the same environment at home rather than family. <br>8. I enjoy our holidays with my wife. <br>9. I enjoy traveling with my wife. <br>10. My wife and most of our goals are common. <br>11. I think that one day in the future, when I look back, I see that my wife and I are in harmony with each other. <br>12. My wife and I have similar values in terms of personal freedom. <br>13. My husband and I have similar entertainment. <br>14. Most of our goals for people (children, friends, etc.) are the same. <br>15. Our dreams of living with my wife are similar and harmonious <br>16. We’re compatible with my wife about what love should be <br>17. We share the same views with my wife about being happy in your life <br>18. My wife and I have similar ideas about how marriage should be <br>19. My wife and I have similar ideas about how roles should be in marriage <br>20. My wife and I have similar values in trust <br>21. I know exactly what my wife likes. <br>22. I know how my wife wants to be taken care of when she’s sick. <br>23. I know my wife’s favorite food. <br>24. I can tell you what kind of stress my wife is facing in her life. <br>25. I have knowledge of my wife’s inner world. <br>26. I know my wife’s basic concerns. <br>27. I know what my wife’s current sources of stress are. <br>28. I know my wife’s hopes and wishes. <br>29. I know my wife very well. <br>30. I know my wife’s friends and their social relationships. <br>31. I feel aggressive when I argue with my wife. <br>32. When discussing with my wife, I usually use expressions such as â€œyou alwaysâ€œ or â€œyou neverâ€. <br>33. I can use negative statements about my wife’s personality during our discussions. <br>34. I can use offensive expressions during our discussions. <br>35. I can insult our discussions. <br>36. I can be humiliating when we argue. <br>37. My argument with my wife is not calm. <br>38. I hate my wife’s way of bringing it up. <br>39. Fights often occur suddenly. <br>40. We’re just starting a fight before I know what’s going on. <br>41. When I talk to my wife about something, my calm suddenly breaks. <br>42. When I argue with my wife, it only snaps in and I don’t say a word. <br>43. I’m mostly thirsty to calm the environment a little bit. <br>44. Sometimes I think it’s good for me to leave home for a while. <br>45. I’d rather stay silent than argue with my wife. <br>46. Even if I’m right in the argument, I’m thirsty not to upset the other side. <br>47. When I argue with my wife, I remain silent because I am afraid of not being able to control my anger. <br>48. I feel right in our discussions. <br>49. I have nothing to do with what I’ve been accused of. <br>50. I’m not actually the one who’s guilty about what I’m accused of. <br>51. I’m not the one who’s wrong about problems at home. <br>52. I wouldn’t hesitate to tell her about my wife’s inadequacy. <br>53. When I discuss it, I remind her of my wife’s inadequate issues. <br>54. I’m not afraid to tell her about my wife’s incompetence.</p><p>All of these have numerical values.</p><h3>Code</h3><h4>1. Importing the dataset</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e820d9a8577864971b99d5f704f0ac95/href">https://medium.com/media/e820d9a8577864971b99d5f704f0ac95/href</a></iframe><p>First of all we are going to import some libraries that are going to provide us with certain functionalities to deal with our dataset the way we want to.</p><p>Pandas — It is used to create a DataFrame and perform certain operations on it such as add, drop columns change values etc.</p><p>Numpy — It is used for providing us a special multi dimensional array object so that we can perform certain mathematical operations on it.</p><p>Xlrd — It is used to import dataset present in excel format(.xlsx).</p><p>We are reading our divorce dataset using “<strong>pd.read_csv”</strong> function and storing it in df variable.</p><h4><strong>2. Normalizing Dataset</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b433c607c081530071c949905c2c2bc0/href">https://medium.com/media/b433c607c081530071c949905c2c2bc0/href</a></iframe><p>Here we are normalizing our dataset columns. Now what does normalize mean and why do we do it? It is basically done to bring all your values to same scale of (0,1) so that large values aren’t given more significance in predicting labels over small values. It also allows us to converge to optimal weights faster than we would be able to without normalization. Weights are the parameters you learn that basically define how much importance should be given to a particular feature while predicting labels.</p><p>In first and second lines, we are slicing DataFrame into features and labels.</p><p>“<strong>df.values[rows,columns]</strong>” first converts df into numpy array using “<strong>.values</strong>”, then we are slicing it specifying rows we want first and then the columns. “<strong>:</strong>” selects all rows,“<strong>0:54</strong>” selects first 54 columns and “<strong>54</strong>” selects 54th column in which all labels are placed. Now that we have seperated our labels and input features let us normalize them. “<strong>std_dev”</strong> is used to store standard deviation and “<strong>mean”</strong> is used to store mean of each and every column as an array specified by the “<strong>axis=0</strong>” parameter in “<strong>np.mean</strong>” and “<strong>np.std</strong>” functions. Then we are deducting mean of each column from the values present inside that column and subsequently dividing each value by the standard deviation of that column. That is done using broadcasting as you can see we are not using for loops here but just the variables for dataset, labels and features.</p><h4><strong>3. Splitting Into Training And Testing Datasets</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b1b80b3925fffaa53958aaae744d5e6/href">https://medium.com/media/5b1b80b3925fffaa53958aaae744d5e6/href</a></iframe><p>Here we are splitting dataset into training and testing sets using “<strong>train_test_split”</strong> function from “<strong>sklearn.model_selection”</strong> module. It will return training input, training labels, testing input and testing labels in the specified order which are then assigned to the respective variables. Here we have taken 25% of dataset for testing and 75% for training as is specified by the “<strong>test_size”</strong> parameter. “<strong>random_state</strong>” can be used to generate same sets. For example if you and I both keep random_state as 42 or any other number we would get same aforementioned sets.</p><h4><strong>4. Logistic Regression</strong></h4><p>The first model we are going to train is logistic regression. It is a probabilistic model that determines probability of a particular instance occurring in given class. The hypothesis function is as follows:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*z0AVbdFsaiMqKl_3.png" /><figcaption>Hypothesis function</figcaption></figure><p>Hypothesis function is nothing but the prediction function. Here B0 is bias and B1 represents weights and X represents features values for each example. This function is <strong>sigmoid function</strong>.<strong> </strong>It has a graph that looks like this:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/0*hjeUS3DPCCISOjFP.png" /><figcaption>Sigmoid function</figcaption></figure><p>Large negative values tend to go towards 0 and large positive values give 1 as output whereas for 0 we have 0.5 as output. Now we don’t know the values of B0 and B1 right off the bat. We start off with random values and tend to adjust them so that we can minimize the loss. Loss is defined as follows:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g1WgZcX4SZHN0vtF.png" /><figcaption>Log Loss for Logistic Regression</figcaption></figure><p>We will minimize it using gradient descent. In fact gradient descent is the backbone of many machine learning algorithms that is used to obtain minimum loss. Logistic Regressions creates a boundary on basis of which an example can be assigned a class(0 or 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*jCmOKZQq4F-myyVl.png" /><figcaption>Hypothesis boundary</figcaption></figure><p>Now let us discuss the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b05cd197dc5077d2a94904a9faa63f5/href">https://medium.com/media/8b05cd197dc5077d2a94904a9faa63f5/href</a></iframe><p>We will import Logistic Regression from “<strong>sklearn.linear_model</strong>”. We will create an object of Logistic Regression called “<strong>lg</strong>”. “<strong>Solver”</strong> is set as “<strong>liblinear” </strong>which is basically an algorithm to be used in optimization problem<strong>. </strong>It is a good choice for small datasets. Then we fit training example into the algorithm in the next line. Then we predict the labels for testing data and store the results in “<strong>y_pred</strong>”. Then we will print the accuracy. Here we are checking which values of “<strong>y_pred</strong>” were equal to corresponding values of “<strong>y_test</strong>” and then adding 1 for equal ones and 0 for unequal ones and then dividing the whole thing by number of examples and multiplying it with 100 to get percentage of examples that were identified correctly.</p><h4><strong>5. Naive Bayes</strong></h4><p>It is family of classification algorithms that are based on Bayes’ Theorem. Each of them follow one fundamental rule — no pair of features are dependent on each other.</p><p>Bayes’ Theorem:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/0*PmZs-_1okkJ45d0N.jpg" /><figcaption>Bayes’ Theorem</figcaption></figure><p>Now we will find probability of ‘<strong>c given x</strong>’ for each class where ‘<strong>c</strong>’ is one particular class and ‘<strong>x</strong>’ represents features values for an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/0*CKcvDWnxaD5BYwPC.png" /></figure><p>Like in the image above, we will assume features to be independent and calculate ‘<strong>x given c</strong>’ as product of ‘<strong>x(i) given c</strong>’ where ‘<strong>x(i)</strong>’ is one feature value. Here we dropped the P(x) component as it will be same for each class being considered. We are going to compare posterior probabilities of each class and choose the class with maximum posterior probability as our prediction. Now let us jump to the code:-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fca4013536c187e88325eea94732965/href">https://medium.com/media/0fca4013536c187e88325eea94732965/href</a></iframe><p>In the code above, first we have imported Gaussian Naive Bayes from sklearn. In Gaussian Naive Bayes continuous values associated with each feature are assumed to be distributed according to a <strong>Gaussian distribution</strong>. A Gaussian distribution is also called Normal distribution. When plotted, it gives a bell shaped curve which is symmetric about the mean of the feature values as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*kgLX2tQRAfQO1c6I.png" /><figcaption>Bell curve</figcaption></figure><p>The conditional probability is calculated as follows:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*JV7CRDkQVxvJB2aA.png" /><figcaption>Gaussian Naive Bayes Conditional Probability</figcaption></figure><p>We then make an object called “<strong>nb</strong>”. We fit training examples into the model in the next line and train the model. Then predictions are calculated and stored and accuracy is calculated the same way as before.</p><h4><strong>6. K-Nearest Neighbors (KNN)</strong></h4><p>In KNN, we calculated distance of testing point from each training point and choose K nearest neighbors with minimum distance and which class has most votes in those neighbors is chosen as prediction. It is perhaps the simplest algorithm in machine learning world. There is nothing more to it. Now let us jump straight to the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8b2b5116371f77e546c296acebb87e0/href">https://medium.com/media/c8b2b5116371f77e546c296acebb87e0/href</a></iframe><p>We will import K Neighbors Classifier from sklearn first. Then we will make an object of it. Here “<strong>n_neighbors</strong>” means the number of nearest neighbors you are going to consider for prediction. Here we chosen 15 as the value for it. We will then fit training examples and train the model and make predictions on testing data and store those predictions. Accuracy is calculated the same way as before.</p><h4><strong>7. Decision Tree</strong></h4><p>Decision Tree, as the name suggests, is a tree which can be used for classification. We traverse down the tree based on the conditions present in each node and arrive at prediction for the given testing example at a leaf node. Here is what a decision tree looks like!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*dhWFRt6aKTIJZsSJ" /><figcaption>Decision Tree</figcaption></figure><p>Now how do we build such a tree ? We at each point select the best possible feature that can be used to separate examples into two different groups with minimum “impurity”. By minimum impurity I mean that when we divide based on a feature we should be able to segregate examples with different labels as much as possible by keeping them on different children nodes. Now how should we select an attribute and measure its usefulness ? There are two methods for attribute selection:-</p><ol><li>Information Gain</li><li>Gini Index</li></ol><p>Since we have implemented Gini Index in our code we are going to talk about it. Gini Index is a metric to measure how often a randomly chosen element would be incorrectly identified. It means we should select an attribute with minimum gini index. The formula for gini index is given below:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*-84on3J3seyChDFY.png" /><figcaption>Gini Index</figcaption></figure><p>where i is used to represent current class. After calculating gini index for each children node, overall gini index is calculated as the weighted sum of each gini index. Now let us jump to the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/817034dc6e51a05beba73afb64b5fe74/href">https://medium.com/media/817034dc6e51a05beba73afb64b5fe74/href</a></iframe><p>First we will import Decision Tree Classifier from sklearn. Then we will make an object with the specified parameters. “<strong>max_depth</strong>” is the maximum depth the tree can have, “<strong>max_features</strong>” is the number of features considered when looking for a split and “<strong>min_samples_leaf</strong>” is the minimum number of samples required at each leaf node. We then fit the training examples, predict and print accuracy as usual.</p><h4>-Visualizing the Decision Tree</h4><p>We can visualize the tree as well using the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/588bd5934833da07b097b7b9367ffba5/href">https://medium.com/media/588bd5934833da07b097b7b9367ffba5/href</a></iframe><p>I got a decision tree for my dataset looking like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*FK2F19R4TckxvYZzW3UE0Q.png" /><figcaption>Decision Tree Visualized</figcaption></figure><h4>8. Random Forest</h4><p>You can’t complete a discussion on decision trees without talking about random forests. It consists of a large number of decision trees. Each individual tree gives us a prediction and the class with most votes is given out as the final prediction. It performs incredibly well because of one simple reason — taking knowledge of all members into account; which gives out a better generalized prediction. Now let us jump to the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef582e2720fbb8e6dd85c4bf255c5361/href">https://medium.com/media/ef582e2720fbb8e6dd85c4bf255c5361/href</a></iframe><p>First, the Random Forest Classifier is imported from sklearn.</p><p>Then an object is mode with the specified parameters. “<strong>n_estimators</strong>” corresponds to number of trees in the forest, “<strong>oob_score</strong>” decides whether to estimate accuracy using out-of-bag samples (samples not used to train the tree), “<strong>n_jobs</strong>” specifies number of jobs to run in parallel (-1 uses all processors), “<strong>max_features</strong>” and “<strong>min_samples_leaf</strong>” mean the same as what was discussed in decision trees. Then, again we fit,predict and print the accuracy.</p><h4>9. Support Vector Machine (SVM)</h4><p>It is kinda similar to logistic regression; here we are trying to create a hyperplane to separate the two classes while also trying to maximize distance between closest points of two classes and the hyperplane. Here is an example of how a hyperplane is going to separate the two classes:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/0*ufcIPJJ2_AIDZ6ir.png" /></figure><p>Now let us jump to the code:-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71cd48f372df0f2849b6343faeb7331a/href">https://medium.com/media/71cd48f372df0f2849b6343faeb7331a/href</a></iframe><p>We will import SVC first. Then we will make an object with the specified parameters. “<strong>kernel</strong>” is used to transform input data to make it linearly separable and “<strong>C</strong>” is penalty — making it high gives you large margins (less penalty for misclassification) and making it low gives you small margin(more penalty for misclassification). Then we train using fit, get predictions and print the accuracy as usual.</p><h4>10. Neural Networks</h4><p>Neural networks try to mimic the function of biological neurons. It is a network of artificial neurons. A typical example of what a neural network looks like is given below:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/0*evt4PZ_XcVqGxsRa.png" /><figcaption>Neural Network</figcaption></figure><p>Here the input layer consists of n nodes with each one representing a feature. Each neuron in this network has its own bias and weights. We start off with random weights and biases and fine tune them to get optimal ones using a process known as back propagation. The output layer consists of a single neuron representing the probability of the sample belonging to a class. The hidden layers are used to add complexity to the model and capture the relationship between features and output. Now let us jump straight to the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5d24181b4db90fa7c1f110e23d88992/href">https://medium.com/media/e5d24181b4db90fa7c1f110e23d88992/href</a></iframe><p>First of all from “<strong>keras.models</strong>” we will import “<strong>Sequential</strong>”. Sequential just specifies that whatever is the output of previous layer will now be used as input to the current layer. Then we will import “<strong>Dense</strong>” layer from “<strong>keras.layers</strong>”. Dense layers are just fully connected layers. Now we will make a sequential model. Then, one by one, we will add Dense layers with specified activation functions. First parameter in “<strong>Dense</strong>” corresponds to number of neurons in that layer. Activation functions are just normal output yielding a value in a given range. Sigmoid is one we have discussed already which gives a value in the interval (0,1). “<strong>relu</strong>” is used to add non-linearity to our model and it is just the maximum(0,x). After addition of layers we print out the summary using “<strong>nn.summary</strong>” which gives details about each layer, number of trainable parameters etc. We compile the model using “<strong>nn.compile</strong>” with the specified parameters. “<strong>optimizer</strong>” is used to minimize the loss, loss specifies the loss function which we are trying to minimize and “<strong>metrics</strong>” specify the measures we want. Now we train the model and evaluate it using test data. We can get accuracy using “<strong>nn.evaluate</strong>” which returns two values — loss and metrics(accuracy in our case). ”<strong>epochs</strong>” is the number of iterations for which neural network is trained.</p><h3>Confusion Matrix</h3><p>We can print the confusion matrix for any given model. Confusion matrix specifies number of true_positive, true_negative, false_negative and false_positive values. We can get it using the code below:-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf409ed18a9350c87df898055e3a784d/href">https://medium.com/media/cf409ed18a9350c87df898055e3a784d/href</a></iframe><p>We import the required libraries. We then feed actual and predicted values to “<strong>confusion_matrix</strong>” and store it in variable “<strong>results</strong>”. We then print confusion matrix, accuracy score and classification report as given above.</p><p><strong>THAT IS ALL THERE IS TO IT. HAPPY CODING.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dca1c849ffd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>