<?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 Sisi (Rachel) Chen on Medium]]></title>
        <description><![CDATA[Stories by Sisi (Rachel) Chen on Medium]]></description>
        <link>https://medium.com/@rachelchen0104?source=rss-9c7e43b06849------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*opbvnFNnS-UL-F-DYwTx2A.jpeg</url>
            <title>Stories by Sisi (Rachel) Chen on Medium</title>
            <link>https://medium.com/@rachelchen0104?source=rss-9c7e43b06849------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:27:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rachelchen0104/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[Hands-On ML Chapter 4]]></title>
            <link>https://rachelchen0104.medium.com/hands-on-ml-chapter-4-ddae31f44112?source=rss-9c7e43b06849------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddae31f44112</guid>
            <dc:creator><![CDATA[Sisi (Rachel) Chen]]></dc:creator>
            <pubDate>Sat, 21 Nov 2020 04:56:50 GMT</pubDate>
            <atom:updated>2020-11-22T04:08:59.301Z</atom:updated>
            <content:encoded><![CDATA[<h4>Training Models</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*ssihLq9PFJI2RytaMKdXMQ.png" /></figure><p>In this chapter, we will start by looking at the Linear Regression model, one of the simplest models there is. We will discuss two very different ways to train it:</p><ul><li>Using a direct “closed-form” equation that directly computes the model parameters that best fit the model to the training set (i.e., the model parameters that minimize the cost function over the training set).</li><li>Using an iterative optimization approach, called Gradient Descent (GD), that gradually tweaks the model parameters to minimize the cost function over the training set, eventually converging to the same set of parameters as the first method. We will look at a few variants of Gradient Descent that we will use again and again when we study neural networks in Part II: Batch GD, Mini-batch GD, and Stochastic GD.</li><li>Next we will look at Polynomial Regression, a more complex model that can fit nonlinear datasets. Since this model has more parameters than Linear Regression, it is more prone to overfitting the training data, so we will look at how to detect whether or not this is the case, using learning curves, and then we will look at several regularization techniques that can reduce the risk of overfitting the training set.</li><li>Finally, we will look at two more models that are commonly used for classification tasks: Logistic Regression and Softmax Regression.</li></ul><p><strong>The Normal Equation</strong></p><p>Given a matrix equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/48/0*27W8WR-m65GDtjBE.gif" /></figure><p>the normal equation is that which minimizes the sum of the square differences between the left and right sides:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/86/0*NLl7WmUoN5c0RPmw.gif" /></figure><p>It is called a normal equation because b-Ax is normal to the range of A.</p><p>On the positive side, this equation is linear with regards to the number of instances in the training set (it is <em>O</em>(<em>m</em>)), so it handles large training sets efficiently, provided they can fit in memory.</p><p>Also, once you have trained your Linear Regression model (using the Normal Equation or any other algorithm), predictions are very fast: the computational complexity is linear with regards to both the number of instances you want to make predictions on and the number of features. In other words, making predictions on twice as many instances (or twice as many features) will just take roughly twice as much time.</p><p>Now we will look at very different ways to train a Linear Regression model, better suited for cases where there are a large number of features, or too many training instances to fit in memory.</p><p><strong>Gradient Descent</strong></p><ul><li>Batch GD</li></ul><p><strong>Batch gradient descent</strong> refers to calculating the derivative from all training data before calculating an update. Thus, it becomes very computationally expensive to do Batch GD. It makes smooth updates in the model parameters.</p><ul><li>Mini-batch GD</li></ul><p>Parameters are updated after computing the gradient of the error with respect to a subset of the training set. Since a subset of training examples is considered, it can make quick updates in the model parameters and can also exploit the speed associated with vectorizing the code. Depending upon the batch size, the updates can be made less noisy — the greater the batch size less noisy is the update.</p><ul><li>Stochastic GD</li></ul><p>SGD tries to solve the main problem in Batch Gradient descent which is the usage of whole training data to calculate gradients at each step. SGD is stochastic in nature i.e it picks up a “random” instance of training data at each step and then computes the gradient making it much faster as there are much fewer data to manipulate at a single time, unlike Batch GD. It makes very noisy updates in the parameters.</p><p><strong>Polynomial Regression</strong></p><p>What if your data is actually more complex than a simple straight line? Surprisingly, you can actually use a linear model to fit nonlinear data. A simple way to do this is to add powers of each feature as new features, then train a linear model on this extended set of features. This technique is called <em>Polynomial Regression</em>.</p><p>This function fits a polynomial regression model to powers of a single predictor by the method of linear least squares. Interpolation and calculation of areas under the curve are also given.</p><p>If a polynomial model is appropriate for your study then you may use this function to fit a k order/degree polynomial to your data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*GIV5KY_Ge_pte8XR4XXYSA.png" /></figure><p>where Y caret is the predicted outcome value for the polynomial model with regression coefficients b1 to k for each degree and Y intercept b0. The model is simply a general linear regression model with k predictors raised to the power of i where i=1 to k. A second-order (k=2) polynomial forms a quadratic expression (parabolic curve), a third-order (k=3) polynomial forms a cubic expression and a fourth-order (k=4) polynomial forms a quartic expression.</p><p>Some general principles:</p><p>a. the fitted model is more reliable when it is built on large numbers of observations.<br>b. do not extrapolate beyond the limits of observed values.<br>c. choose values for the predictor (x) that are not too large as they will cause overflow with higher degree polynomials; scale x down if necessary.<br>d. do not draw false confidence from low P values, use these to support your model only if the plot looks reasonable.</p><p>More complex expressions involving polynomials of more than one predictor can be achieved by using the general linear regression function. For more detail from the regression, such as analysis of residuals, use the general linear regression function. To achieve a polynomial fit using general linear regression you must first create new workbook columns that contain the predictor (x) variable raised to powers up to the order of polynomial that you want. For example, a second-order fit requires input data of Y, x, and x².</p><p>Model fit and intervals</p><p>Subjective goodness of fit may be assessed by plotting the data and the fitted curve. An analysis of variance is given via the analysis option; this reflects the overall fit of the model. Try to use as few degrees as possible for a model that achieves significance at each degree.</p><p>The plot function supplies a basic plot of the fitted curve and a plot with confidence bands and prediction bands. You can save the fitted Y values with their standard errors, confidence intervals, and prediction intervals to a workbook.</p><p>Area under curve</p><p>The option to calculate the area under the fitted curve employs two different methods. The first method integrates the fitted polynomial function from the lowest to the highest observed predictor (x) value using Romberg’s integration. The second method uses the trapezoidal rule directly on the data to provide a crude estimate.</p><p><strong>Learning Curves</strong></p><p>Learning curves are widely used in machine learning for algorithms that learn (optimize their internal parameters) incrementally over time, such as deep learning neural networks.</p><p>The metric used to evaluate learning could be maximizing, meaning that better scores (larger numbers) indicate more learning. An example would be classification accuracy.</p><p>It is more common to use a score that is minimizing, such as loss or error whereby better scores (smaller numbers) indicate more learning and a value of 0.0 indicates that the training dataset was learned perfectly and no mistakes were made.</p><p>During the training of a machine learning model, the current state of the model at each step of the training algorithm can be evaluated. It can be evaluated on the training dataset to give an idea of how well the model is “<em>learning</em>.” It can also be evaluated on a hold-out validation dataset that is not part of the training dataset. Evaluation of the validation dataset gives an idea of how well the model is “<em>generalizing</em>.”</p><ul><li><strong>Train Learning Curve</strong>: Learning curve calculated from the training dataset that gives an idea of how well the model is learning.</li><li><strong>Validation Learning Curve</strong>: Learning curve calculated from a hold-out validation dataset that gives an idea of how well the model is generalizing.</li></ul><p>It is common to create dual learning curves for a machine learning model during training on both the training and validation datasets.</p><p>In some cases, it is also common to create learning curves for multiple metrics, such as in the case of classification predictive modeling problems, where the model may be optimized according to cross-entropy loss and model performance is evaluated using classification accuracy. In this case, two plots are created, one for the learning curves of each metric, and each plot can show two learning curves, one for each of the train and validation datasets.</p><ul><li><strong>Optimization Learning Curves</strong>: Learning curves calculated on the metric by which the parameters of the model are being optimized, e.g. loss.</li><li><strong>Performance Learning Curves</strong>: Learning curves calculated on the metric by which the model will be evaluated and selected, e.g. accuracy.</li></ul><p><strong>Regularized Linear Models</strong></p><p>A good way to reduce overfitting is to regularize the model (i.e., to constrain it): the fewer degrees of freedom it has, the harder it will be for it to overfit the data. For example, a simple way to regularize a polynomial model is to reduce the number of polynomial degrees.</p><p>For a linear model, regularization is typically achieved by constraining the weights of the model. We will now look at Ridge Regression, Lasso Regression, and Elastic Net, which implement three different ways to constrain the weights.</p><p>Ridge Regression</p><p><strong>Ridge regression</strong> is a way to create a parsimonious model when the number of predictor variables in a set exceeds the number of observations, or when a data set has multicollinearity (correlations between predictor variables).</p><p>Lasso Regression</p><p><strong>Lasso regression</strong> is a type of linear <strong>regression</strong> that uses shrinkage. Shrinkage is where data values are shrunk towards a central point, like the mean. The <strong>lasso</strong> procedure encourages simple, sparse models (i.e. models with fewer parameters).</p><p>Elastic Net</p><p>In statistics and, in particular, in the fitting of linear or logistic regression models, the elastic net is a regularized regression method that linearly combines the L1 and L2 penalties of the lasso and ridge methods.</p><p>Early Stopping</p><p>In machine learning, early stopping is a form of regularization used to avoid overfitting when training a learner with an iterative method, such as gradient descent. Such methods update the learner so as to make it better fit the training data with each iteration. Up to a point, this improves the learner’s performance on data outside of the training set. Past that point, however, improving the learner’s fit to the training data comes at the expense of increased generalization error. Early stopping rules provide guidance as to how many iterations can be run before the learner begins to over-fit. Early stopping rules have been employed in many different machine learning methods, with varying amounts of theoretical foundation.</p><p><strong>Logistic Regression</strong></p><p><em>Logistic Regression </em>(also called <em>Logit Regression</em>) is commonly used to estimate the probability that an instance belongs to a particular class (e.g., what is the probability that this email is spam?). If the estimated probability is greater than 50%, then the model predicts that the instance belongs to that class (called the positive class, labeled “1”), or else it predicts that it does not (i.e., it belongs to the negative class, labeled “0”). This makes it a binary classifier.</p><p>Just like a Linear Regression model, a Logistic Regression model computes a weighted sum of the input features (plus a bias term), but instead of outputting the result directly like the Linear Regression model does, it outputs the <em>logistic </em>of this result.</p><p><strong>Softmax Regression</strong></p><p>The Logistic Regression model can be generalized to support multiple classes directly, without having to train and combine multiple binary classifiers (as discussed in Chapter 3). This is called <em>Softmax Regression</em>, or <em>Multinomial Logistic Regression.</em></p><p><strong>Cross-Entropy</strong></p><p>In information theory, the cross-entropy between two probability distributions p and q over the same underlying set of events measures the average number of bits needed to identify an event drawn from the set if a coding scheme used for the set is optimized for an estimated probability distribution q, rather than the true distribution p.</p><ol><li>What Linear Regression training algorithm can you use if you have a training set with millions of features?</li></ol><p>If you have a training set with millions of features you can use <strong>Stochastic Gradient Descent</strong> or<strong> Mini-batch Gradient Descent</strong>, and perhaps <strong>Batch Gradient Descent</strong> if the training set fits in memory. But you cannot use the Normal Equation because the computational complexity grows quickly (more than quadratically) with the number of features.</p><p>2. Suppose the features in your training set have very different scales. What algorithms might suffer from this, and how? What can you do about it?</p><p>If the features in your training set have very different scales, the cost function will have the shape of an elongated bowl, so the Gradient Descent algorithms will take a long time to converge. To solve this you should scale the data before training the model. Note that the Normal Equation will work just fine without scaling.</p><p>3. Can Gradient Descent get stuck in a local minimum when training a Logistic<br>Regression model?</p><p>Gradient Descent cannot get stuck in a local minimum when training a Logistic Regression model because the cost function is convex.</p><p>4. Do all Gradient Descent algorithms lead to the same model provided you let<br>they run long enough?</p><p>If the optimization problem is convex (such as Linear Regression or Logistic<br>Regression), and assuming the learning rate is not too high, then all Gradient<br>Descent algorithms will approach the global optimum and end up producing<br>fairly similar models. However, unless you gradually reduce the learning rate,<br>Stochastic GD and Mini-batch GD will never truly converge; instead, they will<br>keep jumping back and forth around the global optimum. This means that even if you let them run for a very long time, these Gradient Descent algorithms will produce slightly different models.</p><p>5. Suppose you use Batch Gradient Descent and you plot the validation error at every epoch. If you notice that the validation error consistently goes up, what is likely going on? How can you fix this?</p><p>If the validation error consistently goes up after every epoch, then one possibility is that the<strong> learning rate is too high and the algorithm is diverging</strong>. If the training error also goes up, then this is clearly the problem and you should reduce the learning rate. However, if the training error is not going up, then your model is overfitting the training set and you should stop training.</p><p>6. Is it a good idea to stop Mini-batch Gradient Descent immediately when the validation error goes up?</p><p>Due to their random nature, neither<strong> Stochastic Gradient Descent </strong>nor <strong>Mini-batch Gradient Descent</strong> is guaranteed to make progress at every single training iteration. So if you immediately stop training when the validation error goes up, you may stop much too early, before the optimum is reached. A better option is to save the model at regular intervals, and when it has not improved for a long time(meaning it will probably never beat the record), you can revert to the best-saved model.</p><p>7. Which Gradient Descent algorithm (among those we discussed) will reach the vicinity of the optimal solution the fastest? Which will actually converge? How can you make the others converge as well?</p><p>Stochastic Gradient Descent has the fastest training iteration since it considers<br>only one training instance at a time, so it is generally the first to reach the vicinity of the global optimum (or Mini-batch GD with a very small mini-batch size).<br>However, only Batch Gradient Descent will actually converge, given enough<br>training time. As mentioned, Stochastic GD and Mini-batch GD will bounce<br>around the optimum, unless you gradually reduce the learning rate.</p><p>8. Suppose you are using Polynomial Regression. You plot the learning curves and you notice that there is a large gap between the training error and the validation error. What is happening? What are the three ways to solve this?</p><p>If the validation error is much higher than the training error, this is likely because your model is overfitting the training set. One way to try to fix this is to reduce the polynomial degree: a model with fewer degrees of freedom is less likely to overfit. Another thing you can try is to regularize the model — for example, by adding an ℓ2 penalty (Ridge) or an ℓ1 penalty (Lasso) to the cost function. This will also reduce the degrees of freedom of the model. Lastly, you can try to increase the size of the training set.</p><p>9. Suppose you are using Ridge Regression and you notice that the training error and the validation error are almost equal and fairly high. Would you say that the model suffers from high bias or high variance? Should you increase the regularization hyperparameter α or reduce it?</p><p>If both the training error and the validation error are almost equal and fairly<br>high, the model is likely underfitting the training set, which means it has high bias. You should try reducing the regularization hyperparameter α.</p><p>10. Why would you want to use:<br>• Ridge Regression instead of Linear Regression?<br>• Lasso instead of Ridge Regression?<br>• Elastic Net instead of Lasso?</p><p>Let’s see:<br>• A model with some regularization typically performs better than a model<br>without any regularization, so you should generally prefer Ridge Regression<br>over plain Linear Regression.<br>• Lasso Regression uses an ℓ1 penalty, which tends to push the weights down to exactly zero. This leads to sparse models, where all weights are zero except for the most important weights. This is a way to perform feature selection automatically, which is good if you suspect that only a few features actually matter. When you are not sure, you should prefer Ridge Regression.<br>• Elastic Net is generally preferred over Lasso since Lasso may behave erratically in some cases (when several features are strongly correlated or when there are more features than training instances). However, it does add an extra hyperparameter to tune. If you just want Lasso without the erratic behavior, you can just use Elastic Net with an l1_ratio close to 1.</p><p>11. Suppose you want to classify pictures as outdoor/indoor and daytime/nighttime. Should you implement two Logistic Regression classifiers or one Softmax Regression classifier?</p><p>If you want to classify pictures as outdoor/indoor and daytime/nighttime, since these are not exclusive classes (i.e., all four combinations are possible) you should train two Logistic Regression classifiers.</p><p>12. Implement Batch Gradient Descent with early stopping for Softmax Regression (without using Scikit-Learn).</p><p>The code is in my github.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddae31f44112" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ch1.The Machine Learning Landscape- Hands-On ML]]></title>
            <link>https://rachelchen0104.medium.com/ch1-the-machine-learning-landscape-hands-on-ml-a78218128351?source=rss-9c7e43b06849------2</link>
            <guid isPermaLink="false">https://medium.com/p/a78218128351</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sisi (Rachel) Chen]]></dc:creator>
            <pubDate>Fri, 21 Aug 2020 03:07:03 GMT</pubDate>
            <atom:updated>2020-11-15T06:50:42.576Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hands-On ML Chapter 1</h3><h3>The Machine Learning Landscape Reading Note</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*N6DyIN-ZTMThOBg21WTcfA.jpeg" /></figure><p><strong>Machine Learning</strong></p><p>Machine Learning is the field of study that gives computers the ability to learn without being explicitly programmed.</p><p><strong>Types of Machine Learning</strong></p><p>Based on the amount and type of supervision they get during the training, there are four categories: supervised, unsupervised, semi-supervised, and reinforcement learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*zGsmng7UhJeW5rximGKiUg.png" /></figure><p>Based on whether or not the system can learn incrementally from a stream of incoming data, there are batch learning and online learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*joaXssgS7hCHWi8A3guAaA.png" /></figure><p>Based on how the systems generalized, there are instance-based and model based learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*vYVsVpkUSt5qVRhuM_JghQ.png" /></figure><p>Challenges of Machine Learning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*lb7h1mg1xv281342mwEQsw.png" /></figure><p><em>Exercise:</em></p><ol><li>How would you define Machine Learning?</li></ol><p><em>Machine Learning is about building systems that can learn from data. Learning means getting better at some task, given some performance measures.</em></p><p>2. Can you name four types of problems where it shines?</p><p><em>Machine Learning is great for complex problems for which we have no algorithmic solution, to replace long lists of hand-tuned rules, to build systems that adapt to fluctuating environments, and finally to help humans learn.</em></p><p>3. What is a labeled training set?</p><p><em>A labeled training set is a training set that contains the desired solution(a label) for each instance.</em></p><p>4. What are the two most common supervised tasks?</p><p><em>Regression and classification.</em></p><p>5. Can you name four common unsupervised tasks?</p><p><em>Common unsupervised tasks include clustering, visualization, dimensionality reduction, and association rule learning.</em></p><p>6. What type of Machine Learning algorithm would you use to allow a robot to walk in various unknown terrains?</p><p><em>Reinforcement Learning is likely to perform best if we want a robot to learn to walk in various unknown terrains since this is typically the type of problem that Reinforcement Learning tackles. It might be possible to express the problem as a supervised or semisupervised learning problem, but it would be less natural.</em></p><p>7. What type of algorithm would you use to segment your customers into multiple groups?</p><p><em>If you don’t know how to define the groups, then you can use a clustering algorithm (unsupervised learning) to segment your customers into clusters of similar customers. However, if you know what groups you would like to have, then you can feed many examples of each group to a classification algorithm (supervised learning), and it will classify all your customers into these groups.</em></p><p>8. Would you frame the problem of spam detection as a supervised learning problem or an unsupervised learning problem?</p><p><em>Spam detection is a typical supervised learning problem: the algorithm is fed many emails along with their label (spam or not spam).</em></p><p>9. What is an online learning system?</p><p><em>An online learning system can learn incrementally, as opposed to a batch learn‐ ing system. This makes it capable of adapting rapidly to both changing data and autonomous systems, and of training on very large quantities of data.</em></p><p>10. What is out-of-core learning?</p><p><em>Out-of-core algorithms can handle vast quantities of data that cannot fit in a computer’s main memory. An out-of-core learning algorithm chops the data into mini-batches and uses online learning techniques to learn from these mini-batches.</em></p><p>11. What type of learning algorithm relies on a similarity measure to make predictions?</p><p><em>An instance-based learning system learns the training data by heart; then, when given a new instance, it uses a similarity measure to find the most similar learned instances and uses them to make predictions.</em></p><p>12. What is the difference between a model parameter and a learning algorithm’s hyperparameter?</p><p><em>A model has one or more model parameters that determine what it will predict given a new instance (e.g., the slope of a linear model). A learning algorithm tries to find optimal values for these parameters such that the model generalizes well to new instances. A hyperparameter is a parameter of the learning algorithm itself, not of the model (e.g., the amount of regularization to apply).</em></p><p>13. What do model-based learning algorithms search for? What is the most common strategy they use to succeed? How do they make predictions?</p><p><em>Model-based learning algorithms search for an optimal value for the model parameters such that the model will generalize well to new instances. We usually train such systems by minimizing a cost function that measures how bad the system is at making predictions on the training data, plus a penalty for model complexity if the model is regularized. To make predictions, we feed the new instance’s features into the model’s prediction function, using the parameter values found by the learning algorithm.</em></p><p>14. Can you name four of the main challenges in Machine Learning?</p><p><em>Some of the main challenges in Machine Learning are the lack of data, poor data quality, nonrepresentative data, uninformative features, excessively simple models that underfit the training data, and excessively complex models that overfit the data.</em></p><p>15. If your model performs great on the training data but generalizes poorly to new instances, what is happening? Can you name three possible solutions?</p><p><em>If a model performs great on the training data but generalizes poorly to new instances, the model is likely overfitting the training data (or we got extremely lucky on the training data). Possible solutions to overfitting are getting more data, simplifying the model (selecting a simpler algorithm, reducing the number of parameters or features used, or regularizing the model), or reducing the noise in the training data.</em></p><p>16. What is a test set and why would you want to use it?</p><p><em>A test set is used to estimate the generalization error that a model will make on new instances before the model is launched in production.</em></p><p>17. What is the purpose of a validation set?</p><p>A validation set is used to compare models. After training, the fitted model is used to predict the responses for the observations in the <strong>validation dataset</strong>. It makes it possible to select the best model and tune the hyperparameters. Validation datasets can be used for regularization by early stopping (stopping training when the error on the validation dataset increases, as this is a sign of overfitting to the training dataset). The <strong>test dataset</strong> is a dataset used to provide an unbiased evaluation of a <em>final</em> model fit on the training dataset.</p><p>18. What can go wrong if you tune hyperparameters using the test set?</p><p><em>If you tune hyperparameters using the test set, you risk overfitting the test set, and the generalization error you measure will be optimistic.</em></p><p>19. What is cross-validation and why would you prefer it to a validation set?</p><p><em>Cross-validation is a technique that makes it possible to compare models (for model selection and hyperparameter tuning) without the need for a separate validation set. This saves precious training data.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a78218128351" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6. Decision Trees- Hands-On-ML]]></title>
            <link>https://rachelchen0104.medium.com/6-decision-trees-hands-on-ml-f0822ee43219?source=rss-9c7e43b06849------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0822ee43219</guid>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Sisi (Rachel) Chen]]></dc:creator>
            <pubDate>Thu, 20 Aug 2020 02:36:32 GMT</pubDate>
            <atom:updated>2020-11-30T15:49:08.715Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hands-On ML Chapter 6</h3><h4>Decision Trees</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*BEH9fghOd9iYeGu8obk3PQ.png" /></figure><p>Like SVMs, <em>Decision Trees </em>are versatile Machine Learning algorithms that can perform both classification and regression tasks, and even multioutput tasks. They are very powerful algorithms, capable of fitting complex datasets.</p><p><strong>Training and Visualizing a Decision Tree</strong><br>To understand Decision Trees, let’s just build one and take a look at how it makes predictions. The following code trains a DecisionTreeClassifier on the iris dataset:</p><p>Making Predictions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*wFt86uy-rLMTF67iG7zo1w.png" /></figure><p>If an iris flower’s petal length is less than or equal to 2.45 cm, then the iris is Setosa. If not, you can check its petal width. If the petal width is less than or equal to 1.75, the iris is Versicolor. If not, the iris is Virginica. It’s really that simple.</p><p>A node’s samples attribute counts how many training instances it applies to. For example, 100 training instances have a petal length greater than 2.45 cm (depth 1, right), among which 54 have a petal width smaller than 1.75 cm (depth 2, left). A node’s value attribute tells you how many training instances of each class this node applies to: for example, the bottom-right node applies to 0 Iris-Setosa, 1 Iris- Versicolor, and 45 Iris-Virginica.</p><p>Finally, a node’s gini attribute measures its <em>impurity</em>: a node is “pure” (gini=0) if all training instances it applies to belong to the same class. For example, since the depth-1 left node applies only to Iris-Setosa training instances, it is pure and its gini score is 0. Equation 6–1 shows how the training algorithm computes the gini score <em>Gi </em>of the ith node. For example, the depth-2 left node has a gini score equal to 1 — (0/54)^2 — (49/54)^2 — (5/54)^2 ≈ 0.168.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*SBOdO81_ckPUP3VPBCKd9A.png" /></figure><p>The figure below shows this Decision Tree’s decision boundaries. The thick vertical line represents the decision boundary of the root node (depth 0): petal length = 2.45 cm. Since the left area is pure (only Iris-Setosa), it cannot be split any further. However, the right area is impure, so the depth-1 right node splits it at petal width = 1.75 cm (represented by the dashed line). Since max_depth was set to 2, the Decision Tree stops right there. However, if you set max_depth to 3, then the two depth-2 nodes would each add another decision boundary (represented by the dotted lines).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*WjkcEbwoW5QSnGKApsaycQ.png" /></figure><p><strong>Estimating Class Probabilities</strong></p><p>A Decision Tree can also estimate the probability that an instance belongs to a particular class <em>k</em>: first, it traverses the tree to find the leaf node for this instance, and then it returns the ratio of training instances of class <em>k </em>in this node. For example, suppose you have found a flower whose petals are 5 cm long and 1.5 cm wide. The corresponding leaf node is the depth-2 left node, so the Decision Tree should output the following probabilities: 0% for Iris-Setosa (0/54), 90.7% for Iris-Versicolor (49/54), and 9.3% for Iris-Virginica (5/54). And of course, if you ask it to predict the class, it should output Iris-Versicolor (class 1) since it has the highest probability. Let’s check this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*QuNa9JKz95TOIzfAVouMtg.png" /></figure><p><strong>The CART Training Algorithm</strong></p><p>Scikit-Learn uses the <em>Classification And Regression Tree </em>(CART) algorithm to train Decision Trees (also called “growing” trees). The idea is really quite simple: the algorithm first splits the training set in two subsets using a single feature <em>k </em>and a threshold <em>tk </em>(e.g., “petal length ≤ 2.45 cm”). How does it choose <em>k </em>and <em>tk</em>? It searches for the pair (<em>k</em>, <em>tk</em>) that produces the purest subsets (weighted by their size). The cost function that the algorithm tries to minimize is given by Equation 6–2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*xC69ZSOwhO2PdG0JDRiSnw.png" /></figure><p>Once it has successfully split the training set in two, it splits the subsets using the same logic, then the sub-subsets, and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the max_depth hyperparameter), or if it cannot find a split that will reduce impurity. A few other hyperparameters (described in a moment) control additional stopping conditions (min_samples_split, min_sam ples_leaf, min_weight_fraction_leaf, and max_leaf_nodes).</p><p>Unfortunately, finding the optimal tree is known to be an <em>NP-Complete </em>problem: it requires <em>O</em>(exp(<em>m</em>)) time, making the problem intractable even for fairly small training sets. This is why we must settle for a “reasonably good” solution.</p><p><strong>Computational Complexity</strong></p><p>Making predictions requires traversing the Decision Tree from the root to a leaf. Decision Trees are generally approximately balanced, so traversing the Decision Tree requires going through roughly <em>O</em>(<em>log</em>2(<em>m</em>)) nodes.3 Since each node only requires checking the value of one feature, the overall prediction complexity is just <em>O</em>(<em>log</em>2(<em>m</em>)), independent of the number of features. So predictions are very fast, even when dealing with large training sets.</p><p>However, the training algorithm compares all features (or less if max_features is set) on all samples at each node. This results in a training complexity of <em>O</em>(<em>n </em>× <em>m log</em>(<em>m</em>)). For small training sets (less than a few thousand instances), Scikit-Learn can speed up training by presorting the data (set presort=True), but this slows down training considerably for larger training sets.</p><p><strong>Gini Impurity or Entropy?</strong></p><p>By default, the Gini impurity measure is used, but you can select the <em>entropy </em>impurity measure instead by setting the criterion hyperparameter to “entropy”. The concept of entropy originated in thermodynamics as a measure of molecular disorder: entropy approaches zero when molecules are still and well ordered. It later spread to a wide variety of domains, including Shannon’s <em>information theory</em>, where it measures</p><p>the average information content of a message:4 entropy is zero when all messages are identical. In Machine Learning, it is frequently used as an impurity measure: a set’s entropy is zero when it contains instances of only one class. Equation 6–3 shows the definition of the entropy of the ith node. For example, the depth-2 left node in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*sONFdCFKZGejD8d75Z_wGA.png" /></figure><p>So should you use Gini impurity or entropy? The truth is, most of the time it does not make a big difference: they lead to similar trees. Gini impurity is slightly faster to compute, so it is a good default. However, when they differ, Gini impurity tends to isolate the most frequent class in its own branch of the tree, while entropy tends to produce slightly more balanced trees.</p><p><strong>Regularization Hyperparameters</strong></p><p>Decision Trees make very few assumptions about the training data (as opposed to linear models, which obviously assume that the data is linear, for example). If left unconstrained, the tree structure will adapt itself to the training data, fitting it very closely, and most likely overfitting it. Such a model is often called a <em>nonparametric model</em>, not because it does not have any parameters (it often has a lot) but because the number of parameters is not determined prior to training, so the model structure is free to stick closely to the data. In contrast, a <em>parametric model </em>such as a linear model has a predetermined number of parameters, so its degree of freedom is limited, reducing the risk of overfitting (but increasing the risk of underfitting).</p><p>To avoid overfitting the training data, you need to restrict the Decision Tree’s freedom during training. As you know by now, this is called regularization. The regularization hyperparameters depend on the algorithm used, but generally, you can at least restrict the maximum depth of the Decision Tree. In Scikit-Learn, this is controlled by the max_depth hyperparameter (the default value is None, which means unlimited). Reducing max_depth will regularize the model and thus reduce the risk of overfitting.</p><p>The DecisionTreeClassifier class has a few other parameters that similarly restrict the shape of the Decision Tree: min_samples_split (the minimum number of samples a node must have before it can be split), min_samples_leaf (the minimum number of samples a leaf node must have), min_weight_fraction_leaf (same as min_samples_leaf but expressed as a fraction of the total number of weighted instances), max_leaf_nodes (maximum number of leaf nodes), and max_features (maximum number of features that are evaluated for splitting at each node). Increasing min_* hyperparameters or reducing max_* hyperparameters will regularize the model.</p><p>Figure 6–3 shows two Decision Trees trained on the moons dataset (introduced in Chapter 5). On the left, the Decision Tree is trained with the default hyperparameters (i.e., no restrictions), and on the right, the Decision Tree is trained with min_sam ples_leaf=4. It is quite obvious that the model on the left is overfitting, and the model on the right will probably generalize better.</p><p><strong>Regression</strong></p><p>Decision Trees are also capable of performing regression tasks. Let’s build a regression tree using Scikit-Learn’s DecisionTreeRegressor class, training it on a noisy quadratic dataset with max_depth=2:</p><pre><strong>from sklearn.tree import <br></strong>DecisionTreeRegressor tree_reg = DecisionTreeRegressor(max_depth=2)</pre><pre>tree_reg.fit(X, y)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*evHDKfTxZdtgrZP05CkDtg.png" /></figure><p>This tree looks very similar to the classification tree you built earlier. The main difference is that instead of predicting a class in each node, it predicts a value. For example, suppose you want to make a prediction for a new instance with <em>x</em>1 = 0.6. You traverse the tree starting at the root, and you eventually reach the leaf node that predicts value=0.1106. This prediction is simply the average target value of the 110 training instances associated to this leaf node. This prediction results in a Mean Squared Error (MSE) equal to 0.0151 over these 110 instances.</p><p>This model’s predictions are represented on the left of Figure 6–5. If you set max_depth=3, you get the predictions represented on the right. Notice how the predicted value for each region is always the average target value of the instances in that region. The algorithm splits each region in a way that makes most training instances as close as possible to that predicted value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*VDJchiByyQCl8bTO1WFjrg.png" /></figure><p>The CART algorithm works mostly the same way as earlier, except that instead of try‐ ing to split the training set in a way that minimizes impurity, it now tries to split the training set in a way that minimizes the MSE. Equation 6–4 shows the cost function that the algorithm tries to minimize.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*bYbisRiVSOxHPOCZCe47lQ.png" /></figure><p>Just like for classification tasks, Decision Trees are prone to overfitting when dealing with regression tasks. Without any regularization (i.e., using the default hyperparameters), you get the predictions on the left of Figure 6–6. It is obviously overfitting the training set very badly. Just setting min_samples_leaf=10 results in a much more reasonable model, represented on the right of Figure 6–6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*RPtlxs03ughoCW5iwGX5sA.png" /></figure><p><strong>Instability</strong></p><p>Hopefully by now you are convinced that Decision Trees have a lot going for them: they are simple to understand and interpret, easy to use, versatile, and powerful. However they do have a few limitations.</p><p>First, as you may have noticed, Decision Trees love orthogonal decision boundaries (all splits are perpendicular to an axis), which makes them sensitive to training set rotation. For example, Figure 6–7 shows a simple linearly separable dataset: on the left, a Decision Tree can split it easily, while on the right, after the dataset is rotated by 45°, the decision boundary looks unneces‐ sarily convoluted. Although both Decision Trees fit the training set perfectly, it is very likely that the model on the right will not generalize well. One way to limit this prob‐ lem is to use PCA (see Chapter 8), which often results in a better orientation of the training data.</p><p>More generally, the main issue with Decision Trees is that they are very sensitive to small variations in the training data. For example, if you just remove the widest Iris- Versicolor from the iris training set (the one with petals 4.8 cm long and 1.8 cm wide) and train a new Decision Tree, you may get the model represented in Figure 6–8. As you can see, it looks very different from the previous Decision Tree (Figure 6–2). Actually, since the training algorithm used by Scikit-Learn is stochastic you may get very different models even on the same training data (unless you set the random_state hyperparameter)</p><p>Decision Tree in Statquest, how to calculate the Gini index and impurity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*rzlvFnN9XaEOwj04u9AKZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*IU3f4-e7iKV7eGAbevJZAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*WdD4_wgOO87Fqf6MzXFiKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*SIWUBt3m29pAQk5Hxgggrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*19C8hEMVBgBlpO9PicDIEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*Ogr4oMtLs9WHQsXcT4ZVgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*yUKefMlvCUZljeHCViNK4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*xLuEhJREDUnyb1skStN2sA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*1at7K0_0kNnpnvd4_dTrdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*UQoxIvAyvbDQnTEM4HWsFQ.png" /></figure><ol><li>What is the approximate depth of a Decision Tree trained (without restrictions) on a training set with 1 million instances?</li></ol><p>The depth of a well-balanced binary tree containing m leaves is equal to log2(m)³, rounded up. A binary Decision Tree (one that makes only binary decisions, as is the case of all trees in Scikit-Learn) will end up more or less well balanced at the end of training, with one leaf per training instance if it is trained without restrictions. Thus, if the training set contains one million instances, the Decision Tree will have a depth of log2(10⁶) ≈ 20 (actually a bit more since the tree will generally not be perfectly well balanced).</p><p>2. Is a node’s Gini impurity generally lower or greater than its parent’s? Is it generally lower/greater, or always lower/greater?</p><p>A node’s Gini impurity is generally lower than its parent’s. This is ensured by the CART training algorithm’s cost function, which splits each node in a way that minimizes the weighted sum of its children’s Gini impurities. However, if one child is smaller than the other, it is possible for it to have a higher Gini impurity than its parent, as long as this increase is more than compensated for by a decrease of the other child’s impurity. For example, consider a node containing four instances of class A and 1 of class B. Its Gini impurity is 1 − (1/5)² − (4/5)² = 0.32.<br>Now suppose the dataset is one-dimensional and the instances are lined up in the following order: A, B, A, A, A. You can verify that the algorithm will split this node after the second instance, producing one child node with instances A, B, and the other child node with instances A, A, A. The first child node’s Gini impurity is 1 − (1/2)²− (1/2)² = 0.5, which is higher than its parent. This is compensated for by the fact that the other node is pure, so the overall weighted Gini impurity is 2/5 × 0.5 + 3/5 × 0 = 0.2, which is lower than the parent’s Gini impurity.</p><p>3. If a Decision Tree is overfitting the training set, is it a good idea to try decreasing max_depth?</p><p>If a Decision Tree is overfitting the training set, it may be a good idea to decrease max_depth, since this will constrain the model, regularizing it.</p><p>4. If a Decision Tree is underfitting the training set, is it a good idea to try scaling the input features?</p><p>Decision Trees don’t care whether or not the training data is scaled or centered; that’s one of the nice things about them. So if a Decision Tree underfits the training set, scaling the input features will just be a waste of time.</p><p>5. If it takes one hour to train a Decision Tree on a training set containing 1 million instances, roughly how much time will it take to train another Decision Tree on a training set containing 10 million instances?</p><p>The computational complexity of training a Decision Tree is O(n × m log(m)). So if you multiply the training set size by 10, the training time will be multiplied by K = (n × 10m × log(10m)) / (n × m × log(m)) = 10 × log(10m) / log(m). If m = 10⁶, then K ≈ 11.7, so you can expect the training time to be roughly 11.7 hours.</p><p>6. If your training set contains 100,000 instances, will set presort=True speed up training?</p><p>Presorting the training set speeds up training only if the dataset is smaller than a few thousand instances. If it contains 100,000 instances, setting presort=True will considerably slow down the training.</p><p>7. Train and fine-tune a Decision Tree for the moons dataset.</p><p>a. Generate a moons dataset using make_moons(n_samples=10000, noise=0.4).</p><p>b. Split it into a training set and a test set using train_test_split().</p><p>c. Use grid search with cross-validation (with the help of the GridSearchCV</p><p>class) to find good hyperparameter values for a DecisionTreeClassifier.</p><p>Hint: try various values for max_leaf_nodes.</p><p>d. Train it on the full training set using these hyperparameters, and measure</p><p>your model’s performance on the test set. You should get roughly 85% to 87%</p><p>accuracy.</p><p>8. Grow a forest.</p><p>a. Continuing the previous exercise, generate 1,000 subsets of the training set,<br>each containing 100 instances selected randomly. Hint: you can use Scikit-<br>Learn’s ShuffleSplit class for this.</p><p>b. Train one Decision Tree on each subset, using the best hyperparameter values found above. Evaluate these 1,000 Decision Trees on the test set. Since they were trained on smaller sets, these Decision Trees will likely perform worse than the first Decision Tree, achieving only about 80% accuracy.</p><p>c. Now comes the magic. For each test set instance, generate the predictions of<br>the 1,000 Decision Trees, and keep only the most frequent prediction (you can<br>use SciPy’s mode() function for this). This gives you majority-vote predictions<br>over the test set.d. Evaluate these predictions on the test set: you should obtain a slightly higher accuracy than your first model (about 0.5 to 1.5% higher). Congratulations, you have trained a Random Forest classifier!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0822ee43219" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-On Machine Learning with Scikit-Learn & TensorFlow]]></title>
            <link>https://rachelchen0104.medium.com/hands-on-machine-learning-with-scikit-learn-tensorflow-bbb1c91cb128?source=rss-9c7e43b06849------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbb1c91cb128</guid>
            <dc:creator><![CDATA[Sisi (Rachel) Chen]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 05:12:10 GMT</pubDate>
            <atom:updated>2020-11-18T05:33:43.659Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hands-On ML Chapter 3</h3><h4>Classification</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*h1kksTX93B5phPL-duSDKg.png" /></figure><p>Classification is a task that requires the use of machine learning algorithms that learn how to assign a class label. An <a href="https://en.wikipedia.org/wiki/Algorithm">algorithm</a> that implements classification, especially in a concrete implementation, is known as a <strong>classifier</strong>.</p><p>The most commonly used classifiers are as follows:</p><ul><li><a href="https://en.wikipedia.org/wiki/Fisher%27s_linear_discriminant">Fisher’s linear discriminant</a></li><li><a href="https://en.wikipedia.org/wiki/Logistic_regression">Logistic regression</a></li><li><a href="https://en.wikipedia.org/wiki/Naive_Bayes_classifier">Naive Bayes classifier</a></li><li><a href="https://en.wikipedia.org/wiki/Support_vector_machine">Support vector machines</a></li><li><a href="https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm">k-nearest neighbor</a></li><li><a href="https://en.wikipedia.org/wiki/Decision_tree_learning">Decision trees</a></li><li><a href="https://en.wikipedia.org/wiki/Random_forest">Random forests</a></li><li><a href="https://en.wikipedia.org/wiki/Artificial_neural_networks">Neural networks</a></li></ul><p><strong>Binary Classifier</strong></p><p>Binary classification is the task of classifying the elements of a set into two groups on the basis of a classification rule. Typical binary classification problems include:</p><p>Medical testing to determine if a patient has certain disease or not;<br>Quality control in industry, deciding whether a specification has been met;</p><p>In many practical binary classification problems, the two groups are not symmetric, and rather than overall accuracy, the relative proportion of different types of errors is of interest. For example, in medical testing, detecting a disease when it is not present (a false positive) is considered differently from not detecting a disease when it is present (a false negative).</p><p><strong>Performance Measures</strong></p><p>A good way to evaluate a model is to use cross-validation.</p><p>When the accuracy is high, it does not mean the model is good. This may simply because only about 10% positive values, so if you always guess negative, you will be right about 90% of the time.</p><p>This demonstrates why accuracy is generally not the preferred performance measure for classifiers, especially when you are dealing with <em>skewed datasets </em>(i.e., when some classes are much more frequent than others).</p><p><strong>Confusion Matrix</strong></p><p>A much better way to evaluate the performance of a classifier is to look at the <em>confusion matrix</em>. A <strong>confusion matrix</strong> is a table that is often used to describe the performance of a classification model (or “classifier”) on a set of test data for which the true values are known. The <strong>confusion matrix</strong> itself is relatively simple to understand, but the related terminology can be <strong>confusing. </strong>To compute the confusion matrix, you first need to have a set of predictions, so they can be compared to the actual targets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*A7xCw5WkO7ee2T_YB4IRbw.png" /></figure><p>The confusion matrix gives you a lot of information, but sometimes you may prefer a more concise metric. An interesting one to look at is the accuracy of the positive predictions; this is called the <em>precision </em>of the classifier</p><p>precision = <em>TP/(TP </em>+ <em>FP)</em></p><p>TP is the number of true positives, and FP is the number of false positives.</p><p>A trivial way to have perfect precision is to make one single positive prediction and ensure it is correct (precision = 1/1 = 100%). This would not be very useful since the classifier would ignore all but one positive instance. So precision is typically used along with another metric named <em>recall</em>, also called <em>sensitivity </em>or <em>true positive rate </em>(<em>TPR</em>): this is the ratio of positive instances that are correctly detected by the classifier</p><p>recall = <em>TP/(TP </em>+ <em>FN)</em></p><p><strong>Precision and Recall</strong></p><p>It is often convenient to combine precision and recall into a single metric called the <em>F1 score</em>, in particular if you need a simple way to compare two classifiers. The F1 score is the <em>harmonic mean </em>of precision and recall. Whereas the regular mean treats all values equally, the harmonic mean gives much more weight to low values. As a result, the classifier will only get a high F1 score if both recall and precision are high.</p><p><em>F 1</em>=2× (precision×recall)/(precision + recall)</p><p>In some contexts you mostly care about precision, and in other contexts you really care about recall. For example, if you trained a classifier to detect videos that are safe for kids, you would probably prefer a classifier that rejects many good videos (low recall) but keeps only safe ones (high precision). On the other hand, suppose you train a classifier to detect shoplifters on surveillance images: it is probably fine if your classifier has only 30% precision as long as it has 99% recall.</p><p>Increasing precision reduces recall, and vice versa. This is called the <em>precision/recall tradeoff.</em></p><p><strong>Precision/Recall Tradeoff</strong></p><p>Precision-recall tradeoff occur due to increasing one of the parameter(precision or recall) while keeping the model same. This is possible, for instance, by changing the threshold of the classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*wWPImGVLGHUBo2HCO8_SLQ.png" /></figure><p>For eg, fig 1 is a plot for the binary classifier showing how precision and recall can vary based on threshold. This threshold decides the decision boundary. When threshold is 0, both precision and recall have the same value of around 0.8. When threshold is increased to around 200000, precision reaches close to 0.95 but recall decreases drastically to around 0.4. When threshold is decreased to -200000, recall increases to 0.95 but precision decreases to 0.4. Note that increasing or decreasing threshold is similar to shifting the decision boundary.</p><p><strong>The ROC Curve</strong></p><p>The <em>receiver operating characteristic </em>(ROC) curve is another common tool used with binary classifiers. It is very similar to the precision/recall curve, but instead of plotting precision versus recall, the ROC curve plots the <em>true positive rate </em>(another name for recall) against the <em>false positive rate</em>. The FPR is the ratio of negative instances that are incorrectly classified as positive. It is equal to one minus the <em>true negative rate</em>, which is the ratio of negative instances that are correctly classified as negative. The TNR is also called <em>specificity</em>. Hence the ROC curve plots <em>sensitivity </em>(recall) versus 1 — <em>specificity</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*vxG8x6A2-EEODXiv3XVkWQ.png" /></figure><p>Once again there is a tradeoff: the higher the recall (TPR), the more false positives (FPR) the classifier produces. The dotted line represents the ROC curve of a purely random classifier; a good classifier stays as far away from that line as possible (toward the top-left corner).</p><p>One way to compare classifiers is to measure the <em>area under the curve </em>(AUC). A perfect classifier will have a <em>ROC AUC </em>equal to 1, whereas a purely random classifier will have a ROC AUC equal to 0.5</p><p>Hopefully you now know how to train binary classifiers, choose the appropriate metric for your task, evaluate your classifiers using cross-validation, select the precision/ recall tradeoff that fits your needs, and compare various models using ROC curves and ROC AUC scores.</p><p><strong>Multiclass Classification</strong></p><p>Whereas binary classifiers distinguish between two classes, <em>multiclass classifiers </em>(also called <em>multinomial classifiers</em>) can distinguish between more than two classes.</p><p>Some algorithms (such as Random Forest classifiers or naive Bayes classifiers) are capable of handling multiple classes directly. Others (such as Support Vector Machine classifiers or Linear classifiers) are strictly binary classifiers. However, there are various strategies that you can use to perform multiclass classification using multiple binary classifiers.</p><p>For example, one way to create a system that can classify the digit images into 10 classes (from 0 to 9) is to train 10 binary classifiers, one for each digit (a 0-detector, a 1-detector, a 2-detector, and so on). Then when you want to classify an image, you get the decision score from each classifier for that image and you select the class whose classifier outputs the highest score. This is called the <em>one-versus-all </em>(OvA) strategy (also called <em>one-versus-the-rest</em>).</p><p>Another strategy is to train a binary classifier for every pair of digits: one to distinguish 0s and 1s, another to distinguish 0s and 2s, another for 1s and 2s, and so on. This is called the <em>one-versus-one </em>(OvO) strategy. If there are <em>N </em>classes, you need to train <em>N </em>× (<em>N </em>— 1) / 2 classifiers. For the MNIST problem, this means training 45 binary classifiers! When you want to classify an image, you have to run the image through all 45 classifiers and see which class wins the most duels. The main advantage of OvO is that each classifier only needs to be trained on the part of the training set for the two classes that it must distinguish.</p><p>Some algorithms (such as Support Vector Machine classifiers) scale poorly with the size of the training set, so for these algorithms OvO is preferred since it is faster to train many classifiers on small training sets than training few classifiers on large training sets. For most binary classification algorithms, however, OvA is preferred.</p><p>Scikit-Learn detects when you try to use a binary classification algorithm for a multiclass classification task, and it automatically runs OvA (except for SVM classifiers for which it uses OvO).</p><p><strong>Multilabel Classification</strong></p><p>Until now each instance has always been assigned to just one class. In some cases you may want your classifier to output multiple classes for each instance. For example, consider a face-recognition classifier: what should it do if it recognizes several people on the same picture? Of course it should attach one label per person it recognizes. Say the classifier has been trained to recognize three faces, Alice, Bob, and Charlie; then when it is shown a picture of Alice and Charlie, it should output [1, 0, 1] (meaning “Alice yes, Bob no, Charlie yes”). Such a classification system that outputs multiple binary labels is called a <em>multilabel classification </em>system.</p><p>There are many ways to evaluate a multilabel classifier, and selecting the right metric really depends on your project. For example, one approach is to measure the F1 score for each individual label (or any other binary classifier metric discussed earlier), then simply compute the average score.</p><p>In particular, if you have many more pictures of Alice than of Bob or Charlie, you may want to give more weight to the classifier’s score on pictures of Alice. One simple option is to give each label a weight equal to its <em>support.</em></p><p><strong>Multioutput Classification</strong></p><p>The last type of classification task we are going to discuss here is called <em>multioutput- multiclass classification </em>(or simply <em>multioutput classification</em>). It is simply a generaliza‐ tion of multilabel classification where each label can be multiclass (i.e., it can have more than two possible values).</p><p>To illustrate this, let’s build a system that removes noise from images. It will take as input a noisy digit image, and it will (hopefully) output a clean digit image, repre‐ sented as an array of pixel intensities, just like the MNIST images. Notice that the classifier’s output is multilabel (one label per pixel) and each label can have multiple values (pixel intensity ranges from 0 to 255). It is thus an example of a multioutput classification system.</p><p>The code for this chapter’s content and exercises are in my github.</p><p><a href="https://github.com/cssamanda0104/Hands-on-ML/blob/main/Chapter%203%20Classification.ipynb">https://github.com/cssamanda0104/Hands-on-ML/blob/main/Chapter%203%20Classification.ipynbhttps://github.com/cssamanda0104/Hands-on-ML/blob/main/Chapter%203%20Classification.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbb1c91cb128" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-On Machine Learning with Scikit-Learn & TensorFlow]]></title>
            <link>https://rachelchen0104.medium.com/hands-on-machine-learning-with-scikit-learn-tensorflow-e346ecf9e85d?source=rss-9c7e43b06849------2</link>
            <guid isPermaLink="false">https://medium.com/p/e346ecf9e85d</guid>
            <dc:creator><![CDATA[Sisi (Rachel) Chen]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 03:03:39 GMT</pubDate>
            <atom:updated>2020-11-15T06:50:10.583Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hands-On ML Chapter 2</h3><h3>End-to-End Machine Learning Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*eLGB378CXZXT7ihU2Ms4bg.jpeg" /></figure><p><strong>There are eight steps to go through a house price prediction project.</strong></p><ol><li>Look at the big picture.</li><li>Get the data.</li><li>Discover and visualize the data to gain insights.</li><li>Prepare the data for Machine Learning algorithms.</li><li>Select a model and train it.</li><li>Fine-tune your model.</li><li>Present your solution.</li><li>Launch, monitor, and maintain your system</li></ol><h4><strong>1. Look at the big picture</strong></h4><p><strong>Frame the Problem</strong><br>The first question to ask your boss is what exactly is the business objective; building a model is probably not the end goal. How does the company expect to use and benefit from this model? The next question to ask is what the current solution looks like (if any). It will often give you a reference performance, as well as insights on how to solve the problem.</p><p><strong>Select a Performance Measure</strong></p><p>Regression: Root Mean Square Error (RMSE)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*yUx9ZtlL5L2EGUqGE4qt4w.png" /></figure><p>Suppose that there are many outlier districts. In that case, you may consider using the <em>Mean Absolute Error</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*WLIbJcLrHDQnSRaLy3Ptjg.png" /></figure><p>RMSE is more sensitive to outliers than the MAE. But when outliers are exponentially rare (like in a bell-shaped curve), the RMSE performs very well and is generally preferred.</p><h4><strong>2. Get the data</strong></h4><p>You will need a number of Python modules: Jupyter, NumPy, Pandas, Matplotlib, and Scikit-Learn. Create an environment to make your life easier.</p><p>After download, take a quick look at the data using the df.head(), df.info(), df.desctibe(), and value_counts().</p><p>Another quick way to get a feel of the type of data you are dealing with is to plot a histogram for each numerical attribute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*vCW4bgqQFc33rFV1t29-UQ.png" /></figure><p>Then split the data into training and test set.</p><h4>3. Discover and Visualize the Data to Gain Insights</h4><p>If the dataset is not too large, you can easily compute the <em>standard correlation coefficient </em>(also called <em>Pearson’s r</em>) between every pair of attributes using the corr() method.</p><pre>corr_matrix[&#39;median_house_value&#39;].sort_values(ascending = False)</pre><pre>median_house_value    1.000000<br>median_income         0.687160<br>income_cat            0.642274<br>total_rooms           0.135097<br>housing_median_age    0.114110<br>households            0.064506<br>total_bedrooms        0.047689<br>population           -0.026920<br>longitude            -0.047432<br>latitude             -0.142724</pre><p><strong>Experimenting with Attribute Combinations</strong></p><p>Hopefully, You identified a few data quirks that you may want to clean up before feeding the data to a Machine Learning algorithm, and you found interesting correlations between attributes, in particular with the target attribute. You also noticed that some attributes have a tail-heavy distribution, so you may want to transform them.</p><pre>df_train[“rooms_per_household”] = df_train[“total_rooms”]/df_train[“households”] <br>df_train[“bedrooms_per_room”] = df_train[“total_bedrooms”]/df_train[“total_rooms”] <br>df_train[“population_per_household”]=df_train[“population”]/df_train[“households”]</pre><h4><strong>4. Prepare the Data for Machine Learning Algorithms</strong></h4><p>Step One, deal with missing features</p><p>Step Two, convert these string labels to numbers.</p><p>Step Three, convert integer categorical values into one-hot vectors</p><p>Step Four, two common ways to get all attributes to have the same scale: <em>min-max scaling </em>and <em>standardization</em>.</p><p>You can use the transformation pipelines to execute all those steps in the right order. You can set one pipeline for numerical columns transformation. The other pipeline for categorical columns transformation. Then union these pipelines together, to finish the preparation of the data in one step.</p><h4><strong>5. Select a model and train it</strong></h4><p>The target variable is a continuous variable. You can use linear regression, decision tree regression, random forest regression, SVM regression, and so on. We can perform <em>K-fold cross-validation when we </em>train the model, then we can get the RMSE of each model and compare RMSE to see which model is the best.</p><p>Better Evaluation Using Cross-Validation</p><p><em>K-fold cross-validation </em>randomly splits the training set into 10 distinct subsets called <em>folds</em>, then it trains and evaluates the Decision Tree model 10 times, picking a different fold for evaluation every time and training on the other 9 folds. The result is an array containing the 10 evaluation scores.</p><h4><strong>6. Fine-Tune Your Model</strong></h4><p>Let’s assume that you now have a shortlist of promising models. You now need to fine-tune them.</p><p>Method One: Grid Search</p><p>One way to tune the model would be to fiddle with the hyperparameters manually until you find a great combination of hyperparameter values. This would be very tedious work, and you may not have time to explore many combinations. Instead, you should get Scikit-Learn’s GridSearchCV to search for you.</p><p>Method Two: Randomized Search</p><p>The grid search approach is fine when you are exploring relatively few combinations, like in the previous example, but when the hyperparameter <em>search space </em>is large, it is often preferable to use RandomizedSearchCV instead. This class will try out all possible combinations, it evaluates a given number of random combinations by selecting a random value for each hyperparameter at every iteration.</p><p>Method Three: Randomized Search</p><p>Another way to fine-tune your system is to try to combine the models that perform best. The group (or “ensemble”) will often perform better than the best individual model (just like Random Forests perform better than the individual Decision Trees they rely on).</p><p>Method Four:</p><p>Analyze the Best Models and Their ErrorsYou will often gain good insights into the problem by inspecting the best models. For example, the RandomForestRegressor can indicate the relative importance of each attribute for making accurate predictions. With this information, you may want to try dropping some of the less useful features (e.g., apparently only one ocean_proximity category is really useful, so you could try dropping the others).</p><h4>7. Present your solution</h4><p>You need to present your solution (high‐ lighting what you have learned, what worked and what did not, what assumptions were made, and what your system’s limitations are), document everything, and create nice presentations with clear visualizations and easy-to-remember statements (e.g., “the median income is the number one predictor of housing prices”).</p><h4>8. Launch, Monitor, and Maintain Your System</h4><p>First, Now you need to plug the production input data sources into your system and writing tests.</p><p>Second, you need to write a monitoring code to check your system’s live performance at regular intervals and trigger alerts. There may be a performance degradation problem. This is quite common because models tend to “rot” as data evolves over time unless the models are regularly trained on fresh data.</p><p>Thirdly, evaluating your system’s performance will require sampling the system’s predictions and evaluating them. This will generally require human analysis. These analysts may be field experts or workers on a crowdsourcing platform (such as Amazon Mechanical Turk or CrowdFlower).</p><p>In addition, you should also make sure you evaluate the system’s input data quality. Sometimes performance will degrade slightly because of a poor quality signal. If you monitor your system’s inputs, you may catch this earlier.</p><p>Finally, you will generally want to train your models on a regular basis using fresh data. You should automate this process as much as possible. If your system is an online learning system, you should make sure you save snapshots of its state at regular intervals so you can easily roll back to a previously working state.</p><p>Please check the Github link for the Jupyter Notebook of the housing price prediction project and the answers to the exercise.</p><p><a href="https://github.com/cssamanda0104/Hands-on-ML">https://github.com/cssamanda0104/Hands-on-ML</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e346ecf9e85d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WeRateDogs project- Part II Data cleaning and Data analysis]]></title>
            <link>https://rachelchen0104.medium.com/weratedogs-project-part-ii-data-cleaning-and-data-analysis-b1ea2811d98b?source=rss-9c7e43b06849------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1ea2811d98b</guid>
            <dc:creator><![CDATA[Sisi (Rachel) Chen]]></dc:creator>
            <pubDate>Thu, 28 May 2020 04:40:23 GMT</pubDate>
            <atom:updated>2020-11-12T03:39:32.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*hlyT3e0efialcmUznXFwmg.jpeg" /></figure><h3>Data Cleaning</h3><h4>Define</h4><p>Here is an instruction list of data cleaning, there are 9 issues I will solve during the data cleaning process.</p><ol><li>Change the datatypes of the tweet_ids in the three tables and the timestamp column in df_twitter;</li><li>Merge three tables;</li><li>Drop the retweets, reply records, drop the columns we do not need and drop the tweets without an image or with images which don’t display dogs;</li><li>Clean the wrong ratings — find out the appropriate rating from the multiple ratings;</li><li>Create new columns, one is in the df_twitter to combine “doggo”, “floorfer”, “pupper”, and “puppo” into one column, the other is changing the display_text_range column into text_length column;</li><li>Extract the source from Html code;</li><li>Replace the wrong names of name column;</li><li>Reduce the prediction columns into two — breed and confidence;</li><li>Clean the new breed column by replacing the “_” and making them all lowercase.</li></ol><h4>Code</h4><p>The following are the code that these issues converted. Firstly, the copies of the original pieces of data should be made prior to cleaning.</p><pre># I add the &quot;_fc&quot; at the end of the dataframe name. The &quot;_fc&quot; means &quot;for cleaning&quot;<br>df_twitter_fc = df_twitter.copy()<br>df_predict_fc = df_predict.copy()<br>df_api_fc = df_api.copy()</pre><ol><li><strong>Change the datatypes of the tweet_ids in the three tables and the timestamp column in df_twitter;</strong></li></ol><pre>df_twitter_fc.tweet_id = df_twitter_fc.tweet_id.astype(str)<br>df_predict_fc.tweet_id = df_predict_fc.tweet_id.astype(str)<br>df_api_fc.tweet_id = df_api_fc.tweet_id.astype(str)<br>df_twitter_fc.timestamp = pd.to_datetime(df_twitter.timestamp)</pre><p><strong>2. Merge three tables;</strong></p><pre>#use the outer join to make sure the twitter_id in all the informaiton can be showed in the joined table<br>df_master = pd.merge(df_twitter_fc, df_api_fc, on = “tweet_id”, how = “outer”)<br>df_master = pd.merge(df_master, df_predict_fc, on = “tweet_id”, how = “outer”)</pre><pre># create the copy of the merged dataframe for cleaning<br>df_master_fc = df_master.copy()</pre><p>The columns and data types of the df_master_fc are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*8UMJmu-LlJiAkUESJhrh9w.png" /></figure><p><strong>3. Drop the retweets, reply records, drop the columns we do not need and drop the tweets without an image or with images which don’t display dogs;</strong></p><pre>#check with the column from the api table, the number of the no retweets records<br>df_master_fc.dropna(subset = [“retweeted”], inplace = True)</pre><pre>#We only want the rows without an entry in “retweeted_status_id”<br>df_master_fc = df_master_fc[df_master_fc[“retweeted_status_id”].isnull()]</pre><pre>#We only want the rows without an entry in “in_reply_to_status_id”<br>df_master_fc = df_master_fc[df_master_fc.in_reply_to_status_id.isnull()]</pre><pre># The rows without an image are the ones that the “jpg_url” column is not null<br>df_master_fc.dropna(subset = [“jpg_url”], inplace = True)</pre><pre># The images which do not display dogs are the ones without a dog breed identification in the df_api<br>df_master_fc.drop(df_master_fc.query(“p1_dog == False and p2_dog == False and p3_dog == False”).index, inplace = True)</pre><pre>#drop the unneeded columns<br>df_master_fc.drop([&quot;in_reply_to_status_id&quot;, &quot;in_reply_to_user_id&quot;,<br>                      &quot;retweeted_status_id&quot;, &quot;retweeted_status_user_id&quot;, <br>                      &quot;retweeted_status_timestamp&quot;, &quot;retweeted&quot;], inplace=True, axis = 1)</pre><p>Then the columns and data types of the df_master_fc are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*PN32yLJ9iTBB8Ah9Fo38Nw.png" /></figure><p><strong>4. Clean the wrong ratings — find out the appropriate rating from the multiple ratings;</strong></p><pre># Some of the rows contain two or more rating numbers, I want to find these rows out to check why they have multiple ratings. <br>df_duplicate_ratings = df_master_fc.copy()<br>pattern = “\d+\/\d+” <br>df_duplicate_ratings[‘all_patterns’] = df_duplicate_ratings.text.str.findall(pattern)<br>df_duplicate_ratings[‘patterns_count’] = df_duplicate_ratings[‘all_patterns’].apply(lambda x: len(x))</pre><pre># find out all the index <br>duplicate_rating_index = df_duplicate_ratings.index[df_duplicate_ratings[&#39;patterns_count&#39;] != 1].tolist()</pre><pre>#remove the rows with multiple ratings<br>df_master_fc = df_master_fc.loc[~df_master_fc.index.isin(duplicate_rating_index)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*kap0_ofZhTURF56wIkJL2w.png" /></figure><p><strong>5. Create new columns, one is in the df_twitter to combine “doggo”, “floorfer”, “pupper”, and “puppo” into one column, the other is changing the display_text_range column into text_length column;</strong></p><pre># replace “None” with “” in each column<br>for x in [“doggo”, “floofer”, “pupper”, “puppo”]:<br> df_master_fc[x].replace(“None”, “”, inplace = True)</pre><pre>#Add the four string columns together to create one column called dog_type<br>df_master_fc[‘dog_type’] = df_master_fc[‘doggo’] + df_master_fc[<br> ‘floofer’]+ df_master_fc[‘pupper’] + df_master_fc[‘puppo’]</pre><pre>df_master_fc.dog_type.value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*Zu47TTOKuE1MxJGNeezZVg.png" /></figure><p>The dog_type column still has a lot of blank values. We can drop “doggo”, “floofer”, “pupper”, and “puppo” columns.</p><p>Now let us change the display_text_range column into text_length column;</p><pre>def length(value):<br>    return(value[1] - value[0])<br>   <br>df_master_fc[&#39;display_text_length&#39;] = df_master_fc[&#39;display_text_range&#39;].apply(length)</pre><pre># Check the result<br>df_master_fc[[&#39;display_text_range&#39;,&#39;display_text_length&#39;]].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*HOchjDM1hTyNWxLfy0bkgQ.png" /></figure><p><strong>6. Extract the source from .html format;</strong></p><pre># Apparently, we can not use the original source data<br>df_master_fc[‘extracted_source’] = df_master_fc.source.str.extract(“\&gt;(.*)\&lt;”)</pre><pre>df_master_fc.drop(‘source’, axis = 1, inplace = True)</pre><p><strong>7. Replace the wrong names of name column;</strong></p><p>In the data assessment part, we have found a list of stopwords in the “name” column</p><p>[‘None’, ‘a’, ‘all’, ‘an’, ‘by’, ‘his’, ‘just’, ‘my’, ‘not’, ‘such’, ‘the’, ‘this’, ‘very’]</p><pre># replace the stopwords into nan<br>for x in tokens_without_sw:<br> df_master_fc[“name”].replace(x, np.nan, inplace = True)</pre><pre>df_master_fc.name.value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/1*wcg3CI6GbQxZBzEKmwt0VA.png" /></figure><p>Now there are no stopwords in the ‘name’ column.</p><p><strong>8. Reduce the prediction columns into two — breed and confidence, only use the breed with the highest confidence.</strong></p><p>We know that some of the pictures are identified as other species, but we only want the tweets that are identified as dogs.</p><pre>#extract the most likely prediction which is a dog</pre><pre>def get_attr(x):<br> “””<br> input: <br> Columns: p1_dog, p1/p1_conf, p2_dog, p2/p2_conf, p3_conf<br> output:<br> Results after checking the true/false of the p1_dog and p2_dog   columns<br> “””<br> if x[0] == True:<br> return x[1]<br> elif x[2] == True:<br> return x[3]<br> else:<br> return x[4]<br> <br>df_master_fc[“breed”] = df_master_fc[[“p1_dog”, “p1”, “p2_dog”, “p2”, “p3”]].apply(get_attr, axis = 1)<br>df_master_fc[“confidence”] = df_master_fc[[“p1_dog”, “p1_conf”, “p2_dog”, “p2_conf”, “p3_conf”]].apply(get_attr, axis = 1)</pre><pre>df_master_fc.iloc[:,13:].head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*Eo3gCCR1aZf6OZ9b24yuQw.png" /></figure><p>Drop the breed and confidence columns we do not need.</p><pre>df_master_fc.drop([‘p1’,’p1_conf’, ‘p1_dog’, ‘p2’, ‘p2_conf’, ‘p2_dog’, ‘p3’, ‘p3_conf’,’p3_dog’],axis = 1, inplace = True)</pre><p><strong>9. Clean the new breed column by replacing the “_” and making them all lowercase.</strong></p><pre>df_master_fc.breed = df_master_fc.breed.str.replace(“_”,” “)<br>df_master_fc.breed = df_master_fc.breed.str.lower()<br>df_master_fc.breed.value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*GR5MOcMIp1DPgrVCSzf3HA.png" /></figure><p>After the cleaning, we can check whether there are null values in each column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*1I3CFeiBaf29QAXljWxGIg.png" /></figure><p>Only the name column has lots of NA values, so we may do not use it for further data analysis.</p><h3>Test</h3><p>I will test the “df_master_fc” to make sure my cleaning operations worked.</p><p><em>Test 1: The data type of the tweet_id is String and that of the timestamp column is DateTime.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*ANQSzZNEU0FWbet0OkOavw.png" /></figure><p><em>Test 2</em>: two new columns, one is the combination of “doggo”, “floorfer”, “pupper”, and “puppo”, the other is changing the display_text_range column into text_length column;</p><pre>df_master_fc[&#39;dog_type&#39;].value_counts()<br>Out:<br>pupper           164<br>doggo             54<br>puppo             21<br>doggopupper        7<br>floofer            7<br>doggopuppo         1<br>doggofloofer       1<br>Name: dog_type, dtype: int64</pre><p><em>Test 3</em>: extract the source from the .html format;</p><pre>df_master_fc[‘extracted_source’].value_counts()<br>Out:<br>Twitter for iPhone    1610<br>Twitter Web Client      20<br>TweetDeck                8</pre><p><em>Test 4</em>: Replace the wrong names of name column;</p><pre>df_master_fc[‘name’].unique().tolist()</pre><pre>Out: <br>[&#39;Tilly&#39;,<br> &#39;Archie&#39;,<br> &#39;Darla&#39;,<br> &#39;Franklin&#39;,<br> nan,<br> &#39;Jax&#39;,<br> &#39;Zoey&#39;,<br> &#39;Cassie&#39;,<br> &#39;Koda&#39;,<br> &#39;Bruno&#39;,<br> &#39;Ted&#39;,<br> &#39;Stuart&#39;,<br> &#39;Oliver&#39;,<br> &#39;Jim&#39;,<br> &#39;Zeke&#39;,<br> &#39;Ralphus&#39;,<br> &#39;Gerald&#39;,<br> &#39;Jeffrey&#39;,<br>...]</pre><p><em>Test 5</em>: Reduce the prediction columns into two — breed and confidence</p><pre>Index([&#39;tweet_id&#39;, &#39;timestamp&#39;, &#39;text&#39;, &#39;expanded_urls&#39;, &#39;rating_numerator&#39;,<br>       &#39;rating_denominator&#39;, &#39;name&#39;, &#39;retweet_count&#39;, &#39;favorite_count&#39;,<br>       &#39;display_text_range&#39;, &#39;jpg_url&#39;, &#39;img_num&#39;, &#39;dog_type&#39;,<br>       &#39;display_text_length&#39;, &#39;extracted_source&#39;, &#39;breed&#39;, &#39;confidence&#39;],<br>      dtype=&#39;object&#39;)</pre><p><em>Test 6:</em> clean the new breed column by replace the “_” and making them all lowercase.</p><pre>df_master_fc[‘breed’].unique()<br>Out: array([&#39;chihuahua&#39;, &#39;labrador retriever&#39;, &#39;basset&#39;,<br>       &#39;chesapeake bay retriever&#39;, &#39;appenzeller&#39;, &#39;pomeranian&#39;,<br>       &#39;irish terrier&#39;, &#39;pembroke&#39;, &#39;samoyed&#39;, &#39;french bulldog&#39;,<br>       &#39;golden retriever&#39;, &#39;whippet&#39;, &#39;siberian husky&#39;, &#39;mexican hairless&#39;,<br>       &#39;kuvasz&#39;, &#39;pug&#39;, &#39;blenheim spaniel&#39;, &#39;malamute&#39;,<br>       &#39;italian greyhound&#39;, &#39;chow&#39;, &#39;german shepherd&#39;, &#39;doberman&#39;,<br>       &#39;eskimo dog&#39;, &#39;weimaraner&#39;, &#39;saluki&#39;, &#39;miniature pinscher&#39;,<br>       &#39;german short-haired pointer&#39;, &#39;english springer&#39;, &#39;vizsla&#39;,<br>       &#39;bloodhound&#39;, &#39;bernese mountain dog&#39;, &#39;west highland white, ...]</pre><h3>Data Analysis</h3><p><strong>Questions:</strong></p><ol><li>Which dog breed has the largest number of retweet count, favorite count, and rating?</li><li>During which time the users would like to rate the dogs the most?</li></ol><p>3. Which time period in a day is the one with the highest retweet count and favorite count?</p><pre>df_master_fc.to_csv(‘twitter_archive_master.csv’, index = False)<br>df_analysis = pd.read_csv(‘twitter_archive_master.csv’)<br>df_breed = df_analysis.copy()</pre><pre># The rating is equal to its numerator divided by its denominator<br>df_breed[‘rating’] = df_breed[‘rating_numerator’]/df_breed[‘rating_denominator’]</pre><pre>df_breed[&#39;rating&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*hbes3wL_OCuDx-Nwv7bwdg.png" /></figure><h4>1. Which dog breed has the largest number of retweet count, favorite count, and rating?</h4><p>Calculate the total number of retweet and favorite count.</p><pre>df_breed_total = df_breed.groupby(‘breed’).agg({‘retweet_count’: “sum”, ‘favorite_count’: “sum”}).reset_index()</pre><pre># Check the top 5 breeds<br>for i in [‘retweet_count’, ‘favorite_count’]:<br> print(i)<br> print(df_breed_total.sort_values(by = i, ascending = False).head())<br> fig, ax = plt.subplots(figsize = (15,6))<br> ax = sns.barplot(x = “breed”, y = i, data = df_breed_total.sort_values(i, \<br> ascending = False).iloc[:10], palette = “magma”)<br> ax.set_title(“Total “ + i + “ per breed”)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*d7T9QnALv797q93ErpreYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*qXI5nbnq6t2zxe0LOykpqw.png" /></figure><p>We can see that the most liked and retweeted tweets are the images of a Golden Retriever. The second and third breeds are Labrador Retriever and Pembroke Welsh Corgi.</p><p>If the tweets we extract are mainly the tweets about Golden Retriever, Golden Retriever will surely be the breed with most retweet count and most favorite count. To decrease the bias of our sample selection, we can use the mean retweet count, mean favorite count, and mean rating score to check which breed is the most popular one.</p><pre># Calculate the mean metrics.<br>df_breed_mean = df_breed.groupby(‘breed’).agg({‘retweet_count’: “mean”, ‘favorite_count’: “mean”,’rating’:’mean’,}).reset_index()<br>df_breed_mean.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*Fq_pB2G7KtYytU9WkKclNw.png" /></figure><pre># Change the column names<br>df_breed_mean.columns = [&#39;breed&#39;, &#39;avg_retweet_count&#39;, &#39;avg_favorite_count&#39;, &#39;avg_rating&#39;]</pre><pre># Check the top 5 of the average metrics:<br>for i in [&#39;avg_retweet_count&#39;, &#39;avg_favorite_count&#39;, &#39;avg_rating&#39;]:<br>    print(i)<br>    print(df_breed_mean.sort_values(by = i, ascending = False).head())<br>    fig, ax = plt.subplots(figsize = (15,6))<br>    ax = sns.barplot(x = &quot;breed&quot;, y = i, data = df_breed_mean.sort_values(i, \<br>                    ascending = False).iloc[:10], palette = &quot;magma&quot;)<br>    ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha=&#39;right&#39;)<br>    ax.set_title(&quot;Total &quot; + i + &quot; per breed&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*tORF5WoV2KFY0ka0Z2Shzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*CXu-S-lGdTObfgnXMQktmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*FM3CXiU7BetLvR9gKZM9tg.png" /></figure><p>When we look at the average metrics, we can see that the most popular breeds are not Golden Retriever, Labrador Retriever, and Pembroke Welsh Corgi. Australian Terrier and Dumber are the ones with the highest average retweet count, average favorite count, and the average rating.</p><h4>2. Which day in a week is the one with the highest retweet count and favorite count?</h4><pre>df_time = df_analysis.copy()<br>df_time[&#39;timestamp&#39;] = df_time[&#39;timestamp&#39;].apply(lambda x : pd.to_datetime(str(x)))</pre><pre># get the weekday column from the timestamp column<br>def retweet_favorited_period(time_format,aggr):<br>    &quot;&quot;&quot;args:<br>       this function can create a dataframe to calculate the sum or the mean of the retweet count and favorite count <br>       by different time format.<br>       input:<br>          - time_format: an integer that is the time format you want to check, for example &quot;year&quot;, &quot;month&quot;, &quot;weekday&quot;, &quot;day&quot;, &quot;hour&quot;.<br>          - aggr: an integer which is the aggregation function you want to apply on the retweet count and favorite count<br>       output:<br>           - a dataframe shows the aggregation results of retweet count and favorite count by the time format<br>           - a multiple lines plot shows the aggregation results by the time format<br>     &quot;&quot;&quot;<br>    if time_format == &#39;weekday&#39;:<br>        df_time[time_format] = df_time[&#39;timestamp&#39;].dt.weekday<br>        period_length = 7<br>    elif time_format == &#39;hour&#39;:<br>        df_time[time_format] = df_time[&#39;timestamp&#39;].dt.hour<br>        period_length = 24<br>    elif time_format == &#39;month&#39;:<br>        df_time[time_format] = df_time[&#39;timestamp&#39;].dt.month<br>        period_length = 12<br>    # calculate the average metrics by weekday<br>    df_time_aggr = df_time.groupby(time_format).agg({&#39;retweet_count&#39;: aggr, &#39;favorite_count&#39;: aggr}).reset_index()<br>    print(df_time_aggr)<br>    # multiple lines plot<br>    plt.figure(figsize=(15,6))<br>    plt.plot(time_format, &#39;retweet_count&#39;, data=df_time_aggr, marker=&#39;o&#39;, markerfacecolor=&#39;blue&#39;, markersize=12, color=&#39;skyblue&#39;, linewidth=4)<br>    plt.plot(time_format, &#39;favorite_count&#39;, data=df_time_aggr, marker=&#39;&#39;, color=&#39;olive&#39;, linewidth=2)<br>    plt.title(aggr + &quot; retweet and favorite count &quot; + time_format)<br>    plt.xticks(np.arange(0, period_length ))<br>    plt.legend()<br>    plt.show()</pre><p>Then I change the inputs of the function to get the total retweet count and favorite count by weekday.</p><pre>retweet_favorited_period(‘weekday’,’sum’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*atPkEhE4mkd-3C19qL0tDA.png" /></figure><p>The day of the week starts with Monday(0) and Sunday(6). From the line chart above we know that the total retweet and favorite count numbers have two peaks on Monday and Wednesday.</p><pre>retweet_favorited_period(‘weekday’,’mean’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*OPeQiN8Gw9KVfCNDh-mwOg.png" /></figure><p>From the line chart above we know that the average retweet count and favorite count have two peaks on Wednesday and Saturday.</p><h4>3. Which time period in a day is the one with the highest retweet count and favorite count?</h4><pre>retweet_favorited_period(‘hour’,’sum’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*89iFB-suShRIKwCkMX5leA.png" /></figure><pre>retweet_favorited_period(&#39;hour&#39;,&#39;mean&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*YItmP1QgHDpDQGgBH1KpnQ.png" /></figure><p>When checking the total number of retweet and favorite, there are no tweets during the 7:00 to 13:00. The two peaks of total retweet and favorite count happen at 0:00 to 1:00 and 16:00 to 17:00 in a day.</p><p>When checking the average number of retweet and favorite, there are no tweets from 7:00 to 13:00. The two peaks of mean favorite count happen at 6:00 to 7:00 and 16:00 to 17:00 in a day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1ea2811d98b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WeRateDogs project- Part I Data assessment]]></title>
            <link>https://rachelchen0104.medium.com/weratedogs-project-part-i-data-assessment-7bf5f59b0b5e?source=rss-9c7e43b06849------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bf5f59b0b5e</guid>
            <dc:creator><![CDATA[Sisi (Rachel) Chen]]></dc:creator>
            <pubDate>Thu, 28 May 2020 03:52:06 GMT</pubDate>
            <atom:updated>2020-05-28T03:52:48.322Z</atom:updated>
            <content:encoded><![CDATA[<h3>DSND Udacity P3</h3><p>Introduction:</p><p>Real-world data rarely come clean. Gathering data from a variety of sources and in a variety of formats, assessing its quality and tidiness, cleaning it is called data wrangling.</p><p>The datasets that I will wrangle are as follows:</p><h3>Data Sources</h3><ol><li>Name: WeRateDogs Twitter Archive (twitter-archive-enhanced.csv)</li></ol><p>Data Content: Basic tweet data for all 5000+ of their tweets, but not everything. One column the archive does contain though: each tweet’s text, which I used to extract rating, dog name, and dog “stage” (i.e. doggo, floofer, pupper, and puppo) to make this Twitter archive “enhanced.” Of the 5000+ tweets, I have filtered for tweets with ratings only (there are 2356).</p><p>How to gather: Download this file manually in the “Project Details” part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*kNxdD1CEsmq0WjnuCQiX3w.png" /></figure><p>2. Name: Tweet image predictions (image_predictions.tsv)</p><p>Data Content: what breed of dog (or other objects, animal, etc.) is present in each tweet according to a neural network.</p><p>How to gather: Download the data programmatically using the Requests library and the following URL: <a href="https://d17h27t6h515a5.cloudfront.net/topher/2017/August/599fd2ad_image-predictions/image-predictions.tsv">https://d17h27t6h515a5.cloudfront.net/topher/2017/August/599fd2ad_image-predictions/image-predictions.tsv</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*SnC-bx2A7UkF3ZVokZzi8w.png" /></figure><p>3. Name: WeRateDogs™</p><p>Data Content: Each tweet’s retweet count and favorite (“like”) count at minimum, and any additional data you find interesting.</p><p>How to gather: Using the tweet IDs in the WeRateDogs Twitter archive, query the Twitter API for each tweet’s JSON data using Python’s Tweepy library and store each tweet’s entire set of JSON data in a file called tweet_json.txt file.</p><pre>#keys and token to access the API<br>api_key = my_key<br>api_secret_key = my_secret_key<br>access_token = my_access_token<br>access_secret = my_access_secret</pre><pre>#access the API<br>auth = tweepy.OAuthHandler(api_key, api_secret_key)<br>auth.set_access_token(access_token, access_secret)</pre><pre>#Setting the wait_on_rate_limit and wait_on_rate_limit_notify parameters to True in the tweepy.api class to control #the rate of traffic sent or received by a server<br>api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)</pre><p>We read one tweet_id to see what kind of data I can get from the api</p><pre>tweet_id_list = df_twitter.tweet_id.tolist()<br>tweet_id = tweet_id_list[0]<br>print(tweet_id)<br>tweet = api.get_status(tweet_id)<br>print(tweet._json)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*41lI8ZXPwvrNb8ca4rm3Nw.png" /></figure><h3>Data Assessing</h3><p><strong>WeRateDogs Twitter Archive (twitter-archive-enhanced.csv)</strong></p><ol><li>Missing value check and visual check</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*6DP4_gnYduSmrMBcTlPp6A.png" /></figure><p>There are a lot of missing data in the columns about the reply and the retweeted status. There are also lots of “None” in the “doggo”, “floorfer”, “pupper”, and “puppo” columns, so I want to return true if there is no dog classification in any of the columns.</p><p>2. check what are the values in the “source” column</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*0qUuwe3P0yi6hQs4xypqdQ.png" /></figure><p>We only want to extract the information we need in this column. For example, we do not need the “&lt;a href=”https:” part in the source descriptions.</p><p>3. datatype</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*ePm72rBrBiEoWoffS1W4wA.png" /></figure><p>From the information of the dataset, we find two datatype problems need to be dealt with:<br>a. The datatype of the tweet_id column should be String<br>b. The datatype of the timestamp column should be Datetime</p><p>Let us continue to look at the “tweet_id”, “name”, “rating_numerator” and “rating_denominator” columns.</p><p>4. Check if the tweet_id is unique</p><pre>len(df_twitter[‘tweet_id’].unique()) == df_twitter.shape[0]<br>Output: True</pre><p>5. Check the value counts in “name” column</p><pre>df_twitter[‘name’].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*XEVrl4SeBlCvq2IHNcQ5rg.png" /></figure><p>We can see that the “None”, “a”, and “an” can not be the correct name.</p><pre># check what stopwords are there in the name list.<br>name_list = sorted(df_twitter[‘name’].unique().tolist())<br>all_stopwords = stopwords.words(‘english’)<br>all_stopwords.append(“None”)<br>tokens_without_sw = [word for word in name_list if word in all_stopwords]</pre><p>As we can see, the name column contains wrong names like ‘None’, ‘a’, ‘all’, ‘an’, ‘by’, ‘his’, ‘just’, ‘my’, ‘not’, ‘such’, ‘the’, ‘this’, and ‘very’. These names should be removed or replace with other things in further analysis.</p><p>6. Now we can check the “rating_numerator” and “rating_numerator” columns.</p><p><strong>rating_denominator column</strong></p><pre>The unique values are:<br>[0, 2, 7, 10, 11, 15, 16, 20, 40, 50, 70, 80, 90, 110, 120, 130, 150, 170]</pre><p>Count how many tweets under each unique value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/101/1*QD3R1Qri5vRRyqPg3BVKAQ.png" /></figure><p>The range of denominator is large, which is from 0 to 170. Let us check what happened with the rows with large denominator values.</p><pre>print(df_twitter.query(&quot;rating_denominator &gt; 100&quot;).text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*nIMZuU3JzajH_nwlsKuF3Q.png" /></figure><p>The rows with large denominators seem to have no problems, so we check the ones with really small denominators.</p><pre>print(df_twitter.query(&quot;rating_denominator == 0&quot;).text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*89E5GreJeHgDZAaHlRbB5A.png" /></figure><p>There are two numbers in this tweet, but I do not think “960/00” is the right rating, “13/10” is the correct rating.</p><p><strong>rating_numerator column</strong></p><pre>The unique values:<br>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 20, 24, 26, 27, 44, 45, 50, 60, 75, 80, 84, 88, 99, 121, 143, 144, 165, 182, 204, 420, 666, 960, 1776]</pre><p>Count of how many tweets under each unique value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*cx28HiiTBI72Cn5p7NgXMw.png" /></figure><p>The range of numerator is large, which is from 0 to 1776. We can check what happened with the rows with large numerator values.</p><pre>print(df_twitter.query(&quot;rating_numerator &gt; 150 &quot;).text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*wvK0xwpOjDPdcMiQPVaDaQ.png" /></figure><p>The rows with large denominators seem to have no problems, so we check the ones with really small denominators.</p><pre>print(df_twitter.query(“rating_numerator == 0”).text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*Rw5mvLJaQRpu0X6hO2NCeg.png" /></figure><p>The entry 1016 shows that the tweet contains pictures that don’t contain any dogs.</p><p>In conclusion, the rating numerator and denominator columns are invalid when the tweet contains a picture that does not contain any dog, and when there are two ratings in the tweet text.</p><p>Let us check the tweets with two ratings in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*hlCGvTHaPrbbyzkKE7TYLw.png" /></figure><p>From the columns above we can tell that the multiple ratings in a text are caused by the reasons as follows:</p><p>a. There are retweet records, so more than 2 people have rated the dog image.</p><p>b. There are multiple dogs in one picture, so the users will rate all the dogs.</p><p>c. Some of the extracting ratings are actually the numbers of dog legs or represent the convenient store “7/11”.</p><p><strong>Tweet image predictions (image_predictions.tsv)</strong></p><ol><li>Missing value</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*CSWtXx8aYROyDYZHReNd9g.png" /></figure><p>There seem no NA values in each column. Let us check the rows in the dataset. The dataset sample is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*lPYdebtrUd0VnhcAOdOERA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*gxV8Kcg5FsNC1njsYuPjnQ.png" /></figure><p>From the samples above we can tell that:</p><p>a. There are rows without any predictions of the dog</p><p>b. There are both uppercase and lowercase characters in the p1, p2, p3 results columns. Also, the prediction result in these three columns also shows that there are lots of other species’ pictures, not just dog pictures.</p><p>2. Data type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*d-180uTwI3GXgWGsTJWCKQ.png" /></figure><p>The tweet_id column’s datatype should be a string. The other columns’ data types are correct.</p><p>3. Unique tweet_id or not</p><pre>len(df_predict[&#39;tweet_id&#39;].unique()) == df_predict.shape[0]</pre><pre>Output: True</pre><p>4. Duplicate images</p><p>An image may be uploaded by different users. The 66 duplicate images show that in the df_predict dataset, there are retweet records or repeated image upload. I wonder how many images are not to be identified as a dog breed.</p><pre>df_predict[[&quot;p1_dog&quot;,&quot;p2_dog&quot;,&quot;p3_dog&quot;]].apply(lambda x:<br>    (x[0] == False and x[1] == False and x[2] == False) <br>    , axis = 1).value_counts()</pre><pre>Output: False    1751<br>        True      324</pre><p>There are 324 records without the prediction of the dog breed. Let us check some samples of the images that can not be identified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*OewRmaQg3iryRRmoowUXcA.png" /></figure><p>I find that some pictures do not contain any dogs, and some of them only contain vague dog images.</p><p><strong>Name: WeRateDogs™</strong></p><ol><li>Missing value</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*PxcZLjd1sQVjFBOVnso60A.png" /></figure><p>The data sample is as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*ADlBPgktetrSkEOIOTZ5Vw.png" /></figure><p>2. Check the data types</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*nHMVB-qqPphENiqJBRh9PA.png" /></figure><p>The tweet_id datatype should be changed into String.</p><p>The df_api data looks pretty good. There are no NA values in each column, but in the display_text_range column, the value is a list with two numbers.</p><h3>Data assessment overview</h3><h4>Data quality issues:</h4><p>df_twitter</p><ul><li>The datatype of tweet_id should be string, not Integer.</li><li>The datatype of the timestamp should be DateTime not Object.</li><li>The columns “in_reply_to_status_id”, “in_reply_to_user_id”, “retweeted_status_id”, “retweeted_status_user_id”, and “retweeted_status_timestamp” have lots of NA values.</li><li>The “doggo”, “floorfer”, “pupper”, and “puppo” columns have lots of “None” values.</li><li>some of the dog names are not correct (None, an, by, a, …)</li><li>In the “source” column, we only want to extract the information we need. For example, we do not need the “&lt;a href=”https:” part.</li><li>The rating columns are incorrect because there are multiple ratings in the text. The reasons are as follows:</li></ul><ol><li>There are retweet records, so more than 2 people have rated the dog image.</li><li>There are multiple dogs in one picture, so the users will rate them all.</li><li>Some of the extracting ratings are the numbers of dog legs or represent the convenient store “7/11”.</li></ol><p>df_predict</p><ul><li>The prediction is an uppercase and lowercase mix, also there are “_” in the breed name.</li><li>The datatype of tweet_id should be string, not Integer</li><li>The dataset contains duplicate images.</li><li>There are pictures in this table that are not dogs</li></ul><p>df_api</p><ul><li>The datatype of tweet_id should be String, not Integer</li></ul><h4>Data tidiness issues:</h4><p>df_twitter</p><p>The “doggo”, “floorfer”, “pupper”, and “puppo” columns have lots of “None” values, we can combine them into one column.</p><p>df_predict</p><p>There are three predictive results with probabilities, only the prediction result with the highest probabilities is the one we need.</p><p>df_api</p><p>In the display_text_range column, the value is a list with two numbers. The column can change into display_text_length to represent the length of the text.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bf5f59b0b5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A/B tests project — Udacity DAND P2]]></title>
            <link>https://rachelchen0104.medium.com/a-b-tests-project-udacity-dand-p2-55faddd4d5e0?source=rss-9c7e43b06849------2</link>
            <guid isPermaLink="false">https://medium.com/p/55faddd4d5e0</guid>
            <category><![CDATA[a-b-testing]]></category>
            <dc:creator><![CDATA[Sisi (Rachel) Chen]]></dc:creator>
            <pubDate>Thu, 28 May 2020 00:25:18 GMT</pubDate>
            <atom:updated>2020-05-28T00:25:18.218Z</atom:updated>
            <content:encoded><![CDATA[<h3>A/B tests project — Udacity DAND P2</h3><p><strong>Introduction</strong></p><p>This is a project in the Practical Statistics part in Udacity Data Analyst Nanodegree. A/B tests are very commonly performed by data analysts and data scientists. Therefore, this project is a practical work for me to know more about how to implement A/B test in the real business.</p><p><strong>Business Understanding</strong></p><p>An e-commerce company has developed a new web page in order to try and increase the number of users who “convert,” meaning the number of users who decide to pay for the company’s product. I will work through this notebook to help the company understand if they should implement this new page, keep the old page, or perhaps run the experiment longer to make their decision.</p><p><strong>Data Understanding</strong></p><pre># import all packages I need<br>import pandas as pd<br>import numpy as np<br>import random<br>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><pre># read the dataset and check the top few rows<br>df = pd.read_csv(&quot;ab_data.csv&quot;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*MROcQ4zO7X-nGbSpzzD9Gg.png" /></figure><p>There are 5 columns in the dataset, and 294,478 rows in this dataset. The number of unique users in the dataset is 290,584. It means there are duplicate users’ records.</p><pre># The proportion of users converted.<br>user_converted_per = round(df.converted.mean()*100,2)</pre><pre>#The number of times the new_page and treatment don&#39;t match</pre><pre>no_match = df[~((df[&#39;group&#39;] == &#39;treatment&#39;) == (df[&#39;landing_page&#39;] == &#39;new_page&#39;))].shape[0]</pre><p>In the 294,478 records, the proportion of users converted is 11.97%. Meanwhile, the number of times the new_page and treatment don’t match is 3893.</p><pre>#Do any of the rows have missing values?<br>df.isnull().sum()</pre><p>There is no row that has null values, which is a great thing. But remember we have the rows where the landing_page and group columns don’t match. We can delete those rows. And then save the result to a new dataset.</p><p><strong>Updated Dataframe</strong></p><p>In the new dataset df2, there are 290585 rows. The number of unique ids in df2 is 290,584. There is only one duplicate user in df2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*RtiiDf2o7-HjhFdO_sLgpg.png" /></figure><p>The landing_page for the non-unique id is new_page, the group is “treatment” and the converted is 0. The records for this user is reasonable because users in the treatment group will load to the new page. As the converted of two rows are the same, we can drop any one of these two rows.</p><p><strong>Probability</strong></p><p>the probability of an individual converting regardless of the page they receive is 11.97% as we calculated before. We would like to know when given that an individual was in the <strong>control</strong> group, the probability of converting, and when given that an individual was in the <strong>treatment</strong> group, the probability of converting. These two conversion rates can show us how many users decide to pay for the company’s product in both groups.</p><pre><br>control_converted_per = round((len(df2[(df2.converted == 1)&amp;(df2.group == ‘control’)])/len(df2[df2.group == ‘control’]))*100,2)</pre><pre>treat_converted_per = round((len(df2[(df2.converted == 1)&amp;(df2.group == ‘treatment’)])/len(df2[df2.group == ‘treatment’]))*100,2)<br></pre><p>The proportion of the control group converted is 12.04%. The proportion of treatment group converted is 11.88%. we can see that the proportion in the control group is 12.04%, which is larger than that of the treatment group. Can we make a conclusion that the control group performs better than the treatment group? This small difference could appear by chance, therefore we don’t have sufficient evidence to conclude that the new treatment page leads to more conversions.</p><p>Let us check if we divide the treatment and control group evenly.</p><pre>new_page_per = round(len(df2[df2.landing_page == &#39;new_page&#39;])/df2.shape[0]*100,2)</pre><p>The probability of receiving the new page is 50.01%. It shows that the users received the new or the old page in a ration very close to 50:50, which is a good thing.</p><p><strong>Hypothesis Testing</strong></p><p>Method one: simulate by ourselves</p><p>I want to assume that the old page is better unless the new page proves to be definitely better at a Type I error rate of 5%. My null hypothesis and alternative hypothesis are as follows:</p><p>H0: p_new − p_old &lt;= 0</p><p>H1: p_new − p_old &gt; 0</p><p>Assume under the null hypothesis, 𝑝_𝑛𝑒𝑤 and 𝑝_𝑜𝑙𝑑 both have &quot;true&quot; success rates equal to the <strong>converted</strong> success rate regardless of the page. Use a sample size for each page equal to the ones in <strong>ab_data.csv</strong>.</p><p>Perform the sampling distribution for the difference in <strong>converted</strong> between the two pages over 10,000 iterations of calculating an estimate from the null.</p><pre>p_new = df2.converted.mean()<br>p_old = df2.converted.mean()<br></pre><p>The p_new and p_old are both 12.0%. The number of individuals in the control group and treatment group are as follows:</p><pre>n_new = df2.query(“group == ‘treatment’”).user_id.nunique()<br>n_old = df2.query(“group == ‘control’”).user_id.nunique()</pre><p>There are 145,310 users are in the treatment group and 145,273 are in the control group.</p><p>Simulate 𝑛_𝑛𝑒𝑤 transactions with a conversion rate of 𝑝_𝑛𝑒𝑤 under the null. Store these 𝑛_𝑛𝑒𝑤 1’s and 0’s in <strong>new_page_converted</strong>.</p><pre>new_page_converted = np.random.choice([1,0], size = n_new, replace = True, p = (p_new, 1-p_new))</pre><p>The result is an array with values 0 or1 and a length of 145,310. The conversion rate of this array is a number fluctuate around 12%.</p><p>Create 10,000 𝑝_𝑛𝑒𝑤 — 𝑝_𝑜𝑙𝑑 values using the same simulation process you used in parts (a) through (g) above. Store all 10,000 values in a NumPy array called <strong>p_diffs</strong>.</p><pre>p_diffs = []<br>for _ in range(1,10000):<br> <br> new_page_converted = np.random.choice([1,0], size = n_new, replace = True, p = (p_new, 1-p_new))<br> old_page_converted = np.random.choice([1,0], size = n_old, replace = True, p = (p_old, 1-p_old))<br> <br> p_diff = new_page_converted.mean() — old_page_converted.mean()<br> p_diffs.append(p_diff)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*lrtycrZNPghfFHFQuEkbTQ.png" /></figure><p>The proportion of the <strong>p_diffs</strong> are greater than the actual difference observed in <strong>ab_data.csv can be identified as follow:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*ZrjXSfOCnvoqnFN2BFskgA.png" /></figure><p># I wonder what is the proportion of the values in null_vals are larger than the actual difference.</p><pre><br>(null_vals &gt; actual_diff).mean()</pre><p>The number is 89.65%.</p><p>The overview of the whole process is as follows:</p><p>First, I assume that the null hypothesis is true. With that, I assume that p_old is equal to p_new. Therefore, the old page and new page have the same conversion rate which is equal to the conversion rate without considering the new and old page. The number is 0.119597.</p><p>Secondly, I bootstrap a sampling distribution for old and new pages and calculated the differences in the conversion rate of the new page and old page. In the bootstrap formula, I set the n as the number of people who received each page and a conversion rate which is 0.119597.</p><p>Thirdly, there are 10000 conversion rate differences in the p_diffs list. Then I calculate the standard deviation of the 10000 differences. Then I calculate values coming from a normal distribution around 0.</p><p>Lastly, I calculate the proportion of values that are bigger than the observed difference. The p-value is 0.8965. It shows that 89.65% of the conversion rate difference is larger than the actual conversion rate difference. With a Type-I-Error-Rate of 0.05, 0.8965 is much bigger than 0.05, therefore there is no enough evidence to reject the null hypothesis.</p><p><strong>Method 2 — built-in simulation</strong></p><p>We could also use a built-in to achieve similar results.</p><pre>from pandas.core import datetools<br>import statsmodels.api as sm<br>from scipy.stats import norm</pre><pre>#calculate z-test<br>z_score, p_value = sm.stats.proportions_ztest([convert_old, convert_new], [n_old, n_new], alternative=”smaller”)</pre><pre>#calculate the critical z_term<br>z_critical = norm.ppf(1-(0.05))</pre><pre>print(“Z-Score: “, z_score, “\nCritical Z-Score: “, z_critical, “\nP-Value: “, p_value)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*246G3peh_4MuIGiowcutaQ.png" /></figure><p>The p-value is 0.9052 which is so much larger than 0.05. Also, the Z-Score is smaller than the Critical Z-Score, so we can not reject the null hypothesis.</p><p>There is no evidence to reject the null hypothesis. The conclusion is that the conversion rates of the new page are not larger than that of the old page.</p><p><strong>A regression approach</strong></p><p>Since each row is either a conversion or no conversion, so I will use logistic regression. The goal is to use <strong>statsmodels</strong> to fit the regression model to see if there is a significant difference in conversion based on which page a customer receives. I create a column for the intercept and create a dummy variable column for which page each user received. Add an <strong>intercept</strong> column, as well as an <strong>ab_page</strong> column, which is 1 when an individual receives the <strong>treatment</strong> and 0 if <strong>control</strong>.</p><pre>df_reg = df2.copy()<br>df_reg.head()</pre><pre>#add intercept<br>df_reg[“intercept”] = 1</pre><pre>#get dummies and rename<br>df_reg = df_reg.join(pd.get_dummies(df_reg[‘group’]))<br>df_reg.rename(columns = {“treatment”: “ab_page”}, inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*R7R8-rNrHkhZk93NIFczdw.png" /></figure><p>Instantiate your regression model on the two columns I created to predict whether or not an individual converts.</p><pre>y = df_reg[“converted”]<br>x = df_reg[[“intercept”, “ab_page”]]</pre><pre>#load model<br>log_mod = sm.Logit(y,x)</pre><pre>#fit model<br>result = log_mod.fit()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*bja_7LYTGg38gNJ794LaDQ.png" /></figure><p>The result is not that good. So I will consider other things that might influence whether or not an individual converts. Now along with testing if the conversion rate changes for different pages, also add an effect based on which country a user lives in.</p><pre>df_countries = pd.read_csv(“countries.csv”)<br>df_countries.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/113/1*0LfctZ1l48VJ6K-zibf7Ig.png" /></figure><p>After merging the df_countries, the dataset is as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*3VWDDU1ffpfJ_7AvYnySvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*xwrrqT3s35Li3cgiKD2v4A.png" /></figure><p>Tune the model by creating interactions between page and country.</p><pre># Create the variables show the interactions between page and country. <br>df_reg_country[&quot;CA_page&quot;] = df_reg_country[&quot;CA&quot;] * df_reg_country[&quot;ab_page&quot;]<br>df_reg_country[&quot;UK_page&quot;] = df_reg_country[&quot;UK&quot;] * df_reg_country[&quot;ab_page&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*Nr_v3bpd2iAfE58IYxGvzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*TtVNeAGIJn3iRFYbcr8zTg.png" /></figure><p>The results show that p_values are all larger than 0.05. These new variables that show the interactions between page and country even decrease the significance of the original “CA” and “UK” columns. Therefore these new interaction variables should not be added to this model.</p><p><strong>Limitation</strong></p><p>Notice that because of the time stamp associated with each event, we could technically run a hypothesis test continuously as each observation was observed. However, then the hard question is do you stop as soon as one page is considered significantly better than another, or does it need to happen consistently for a certain amount of time? How long do you run to render a decision that neither page is better than another?</p><p>These questions are the difficult parts associated with A/B tests in general.</p><p><strong>Conclusion</strong></p><p>A/B testing does not get a winning result. The conversion rate of the new page is not significantly bigger than that of the old page. But we can do something to make the test better with a much greater chance of succeeding.</p><ol><li>Maybe we can collect at least 7 days of data. If we wait at least one week to reduce the impact of differences in traffic by day. Then we may get a different result.</li><li>We can also check the modification we make can be noticed by the users.</li><li>Segment our A/B test results just for the loyal user’s group will also have different A/B test results.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55faddd4d5e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What kind of dog do you most look like?]]></title>
            <link>https://rachelchen0104.medium.com/what-kind-of-dog-do-you-most-look-like-ab8b235d01c8?source=rss-9c7e43b06849------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab8b235d01c8</guid>
            <dc:creator><![CDATA[Sisi (Rachel) Chen]]></dc:creator>
            <pubDate>Tue, 26 May 2020 01:01:07 GMT</pubDate>
            <atom:updated>2020-06-08T16:01:11.626Z</atom:updated>
            <content:encoded><![CDATA[<h3>Which kind of dog do you most look like?</h3><p>Udacity Data Scientist Nanodegree Capstone — Dog App</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*FGzJGweiUo1zthIXY7vs5Q.png" /><figcaption><a href="https://www.buzzfeed.com/annakopsky/does-your-dog-have-a-celebrity-doppelganger">https://www.buzzfeed.com/annakopsky/does-your-dog-have-a-celebrity-doppelganger</a></figcaption></figure><h4><strong>Introduction</strong></h4><p>This blog post shows every step of the dog breed classification project built with CNN (Convolutional Neural Network) and Transfer Learning technique. At the end of the classifier project, the code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog’s breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. Therefore, I will know which dog breed I look like if I upload my image to the check.</p><h4>Problem statement:</h4><p>There are three problems I will solve in this project:</p><p><em>(1)Humans detection (2) Dogs detection, and (3) create a CNN to classify dog breeds using Transfer Learning.</em></p><p>Let us start to investigate the data and build the classifier.</p><h4><strong>Data</strong></h4><p>The datasets are dog images and human images. Dog images data including 133 dog categories, and 8351 dog images. We split the images into three parts: 6680 training dog images, 835 validation dog images, and 836 test dog images. In the human images data, there are 13233 total human images.</p><h4><strong>Problem Solutions</strong></h4><p><strong>(1) Humans detection</strong></p><p>OpenCV provides many pre-trained face detectors, Haar feature-based cascade classifier is one of them, I use it to detect the human faces in images. This cascade function trains the pictures with human faces with positive labels Before applying this classifier, convert the images to grayscale is a standard procedure. The detectMultiScale executes the classifier stored in the feature-based cascade classifier and takes the grayscale image as a parameter.</p><p>Therefore, we write a function that takes a string-valued file path to an image as input and appears in the code block below.</p><pre># returns &quot;True&quot; if face is detected in image stored at img_path<br>def face_detector(img_path):<br>    img = cv2.imread(img_path)<br>    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)<br>    faces = face_cascade.detectMultiScale(gray)<br>    return len(faces) &gt; 0</pre><p>We extract the file paths for the first 100 images in the human face dataset and dog face dataset. The detector’s Feedback is not that ideal but acceptable. 100% of human faces are detected as human faces, but 11% of dog faces are detected as human faces, which is also an 11% false-positive rate.</p><p><strong>(2) Dogs detection</strong></p><p>To detect a dog, I use a pre-trained ResNet-50 model along with weights that have been trained on ImageNet. ImageNet contains over 10 million images with 1000 categories. The code for the dog detector is as follow:</p><pre>#the categories corresponding to dogs are in the dictionary keys #151-268, the function returns “True” if a dog is detected in the <br>#image stored at img_path</pre><pre>def dog_detector(img_path):<br> prediction = ResNet50_predict_labels(img_path)<br> return ((prediction &lt;= 268) &amp; (prediction &gt;= 151))</pre><p>The percentage of the dog faces detected in humans is 0% and the percentage of the dog faces detected in dogs is 100%. The dog detector performs very well and no human faces are detected as dog faces. To detect a dog’s breed is so much harder that is because sometimes the differences between the dog breeds are subtle. In the following part I will use CNN to classify dog breeds.</p><h4><strong>(3) create a CNN to classify dog breeds using Transfer Learning</strong></h4><p>step 1: Create a CNN to Classify Dog Breeds (from Scratch)</p><p>I create a CNN <em>from scratch</em> to classify dog breeds at first and used an architecture which is a modification of the hinted architecture. In addition to the layer with 64 filters, I added 128 and 256 conv and maxpooling layers to increase the depth and expect better accuracy. I also used BatchNormalization at the end of every conv and maxpooling layers.</p><p>Through the use of batch normalization and additional layers based on the provided architecture, I believe the model will work well on the image classification tasks. Because the several convolutional layers are good enough to detect breed-specific features. And the GAP layer before the last layer significantly reduces the number of parameters to be trained. My layer is as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*sIsiogp1_zutn05qlm9GCA.png" /></figure><p>This model is only trained for 5 epochs and the batch size is 30. At 5 epoch, the test accuracy is 19.61%. The result does not look very well. To reduce training time without sacrificing accuracy, it is time to use transfer learning pre-trained networks to create a CNN breed classifierThese networks are trained on large amounts of data, so they can even reach 90% accuracy. For example, ImageNet has been trained with 10 million images.</p><p>step 2: Create a CNN to Classify Dog Breeds (from Transfer Learning)</p><p>I implemented the pre-trained models like pre-trained VGG19model, and ResNet50 in Keras and compared these model’s accuracy.</p><p>VGG19model:</p><p>In the model uses the pre-trained VGG-16 model as a fixed feature extractor, the last convolutional output of VGG-16 is fed as input to our model. Therefore, only a global average pooling layer and a fully connected layer will be added. The layer is as follow and the test accuracy is only 37.32%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*pJrNmfPdhsPaXIhBXJbVfw.png" /></figure><p>ResNet50</p><p>In this model, the first layer is an average pooling layer, which could reduce the dimension in order to get faster training. In the second layer, I reduce the number of nodes into 512. The dropout layer prevents the model from overfishing. The softmax layer will predict the probability of each breed. It extracts numbers of breeds for outputting the most possible breed.</p><p>This architecture leverages transfer learning from a similar network Resnet50. A good result is obtained since both of the two data have similar features and our data is smaller. For transfer learning, I only need to feed the network with our target 133 classes. And to avoid overfitting, I added the Dropout layer before the last layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*nkINgIdHjkj66e6n5y6m_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*sQUWK4N2cfKSAdS7w-ZSVg.png" /></figure><p>The model ResNet50 outperforms the VGG19 model. The test accuracy is 80.38%.</p><h3><strong>Result</strong></h3><p>We have the human detector, dog detector, and dog breed classifier. We put them together to check whether an image contains a dog or not. If it is a dog, then what the breed it will be. If it is not, then what kind of dog the person looks like. Once all these three detectors are put together, I upload 3 dog images and 3 human images to test the result. The outputs are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*xj7eFdEDOojO9WmrOlIaqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*lNnY_XnYYgofc9Kjb58BjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*Zn-0pdgW8F3Y3kgjkuo_0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*d0qcnwmgPUwFMtHjccEUqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*qgMwX_MQ2qTJzh7tG5xhVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*f4JfbICbaXR06onfg8Mrvg.png" /></figure><p><strong>Potential improvements</strong></p><p>I think the output is a bit better than my expectations for the dogs. However, I need many more samples to know the accuracy and get a relatively precise answer.</p><p>Possible points of improvement:<br>- Add more data for all kinds of dogs.<br>- Augment training images by rotating different angles to increase training accuracy.<br>- If a human is detected as a dog, a random dog of that type can be shown.<br>- More network architecture can be explored and apply transfer learning.</p><p><strong>Conclusion</strong></p><p>In this project, haar cascade classifier and ResNet50 pre-trained are used to detect the human and dog faces. I apply the VGG19 and ResNet50 models as fixed extractor and changed the global average pooling layer. Finally, the ResNet50 produced higher accuracy than others, around 81%. It is a challenge for me to get a high accuracy due to the differences among some breeds are subtle.</p><p>My repo:<a href="https://github.com/cssamanda0104/Data-Scientist-Nanodegree-Capstone-Dog-app">Data-Scientist-Nanodegree-Capstone-Dog-app</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab8b235d01c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Investigate TMDB Movie Dataset]]></title>
            <link>https://rachelchen0104.medium.com/investigate-tmdb-movie-dataset-4d9beef988e5?source=rss-9c7e43b06849------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d9beef988e5</guid>
            <dc:creator><![CDATA[Sisi (Rachel) Chen]]></dc:creator>
            <pubDate>Mon, 25 May 2020 15:31:38 GMT</pubDate>
            <atom:updated>2020-05-25T15:31:38.613Z</atom:updated>
            <content:encoded><![CDATA[<p>What kind of movie should I invest in?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*wXaTqc-nGS8JEylerl4x2A.png" /></figure><h4>Business Understanding</h4><p>Imagine an investor who would like to know more about the features that can affect the profit. We have the TMDB data to solve his problem. The following questions are the ones I am interested in tackling in the context of a movie investor:</p><ol><li>What release season is the peak season that can bring the most profit?</li><li>Which movie production company is the most profitable company?</li><li>Which movie genre is the most profitable genre?</li><li>Which actor is the most profitable actor that can bring the most profit?</li><li>How well can we predict a movie’s average vote? What aspects correlate well to its average vote?</li><li>How well can we predict a movie’s adjusted profit? What aspects correlate well to its adjusted profit?</li></ol><h4>Data Understanding</h4><p>I will use the TMDB data to get some insight into each of these questions. In the rest of this project, I will work along to answer the six questions above.</p><p>The dataset I use is the TMDB data. The link for this data is <a href="https://d17h27t6h515a5.cloudfront.net/topher/2017/October/59dd1c4c_tmdb-movies/tmdb-movies.csv">https://d17h27t6h515a5.cloudfront.net/topher/2017/October/59dd1c4c_tmdb-movies/tmdb-movies.csv</a>. As the data will not be clean at first, I will wrangle and clean the data first.</p><p><strong>Data wrangling</strong></p><pre># Load the movie data <br>df = pd.read_csv(&#39;tmdb-movies.csv&#39;)<br>pd.pandas.set_option(&#39;display.max_columns&#39;, None)</pre><pre>print(df.head(3))</pre><pre>print(&quot;The tmdb dataset have {} rows and {} columns&quot;.format(df.shape[0], df.shape[1]))</pre><p>The TMDB dataset has 10866 rows and 21 columns and the top three rows are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*5FpN-u9SR5HI0_KVjfy55w.png" /></figure><p>After checking the datatype, null values, and 0 values. I have four data cleaning steps:</p><p><strong>Data Cleaning</strong></p><ol><li>Drop the columns I do not need in the further data analysis;</li><li>Change the data type of the column “realease_date” into DateTime;</li><li>Drop the rows with 0 value;</li><li>Drop the duplicates.</li></ol><pre># === 1.Drop the unrelated columns ===<br>to_drop =  [&#39;id&#39;, &#39;imdb_id&#39;,&#39;homepage&#39;,&#39;tagline&#39;,&#39;keywords&#39;,&#39;overview&#39;]<br>df.drop(to_drop, inplace = True, axis = 1)</pre><pre>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*06Zg42_Sf6IBBAbL86NnZA.png" /></figure><p>As we are going to analyze how popularity, revenue, genres, and runtime affect the vote average and profit. These columns do not have any null values except the genres column have 23 null values. I do not think the 23 null values will affect my data analysis result. Therefore, I will do nothing with the null values.</p><pre># === 2.Change the data type ===</pre><pre>df.release_date = pd.to_datetime(df.release_date)</pre><pre># === 3. Deal with the null values  ===<br>df.isnull().sum()</pre><p>There are 1030 rows without the information of production_companies. I do not want to drop them because these rows also contain important information for other questions. <br>Therefore, I will fill null values in the cast, director, genres, and production_companies with “Unknown” to solve the null value problem.</p><pre>df.fillna(&quot;unknow&quot;, inplace = True)</pre><p>We still have 0 values in some continuous columns, I locate these rows and delete them.</p><pre># find the rows with 0 buget or 0 revenue or 0 runtime<br>zero = (df.budget == 0) | (df.revenue == 0)|(df.runtime == 0)<br>zero_rows = df.loc[zero]</pre><pre>df = df.loc[~zero]</pre><p>Right now the data frame only has 3854 rows and 15 columns. Our data is ready, let us start to answer the six questions:</p><h4>1. What release season is the peak season that can bring the most profit?</h4><p>I create a function <strong>peak_season() (Appendix 1)</strong>to plot the profit by weekday and month. Therefore, we can check the line charts of the profit in the last 10 years.</p><pre># input the calculator column and the time range<br>peak_season(‘profit’, “weekday”)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*Ow-dhAgHHGwARy8aGZLozw.png" /></figure><p>I assume that the customers would like to watch movies with the release date at weekends. Because they have enough time to spend on watching movies at weekends. However, the line chart shows that customers would like to watch movies with the release date on Wednesdays. I think that is because Wednesday is in the middle of a week, the customers get to know the movie releases on Wednesday. Then they spend two to three days to decide to watch the movie at weekends or not. That is why the Wednesday released movie can bring a lot of profits.</p><pre>peak_season(&#39;profit&#39;, &quot;month&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*0Px0Ra4L7cbOdwXudorMzQ.png" /></figure><p>The line chart shows that June always the quarter with the highest adjusted revenue from 2006 to 2015. In December, there is another peak season. It makes sense because June is in the summertime, people would like to attend more entertainment activities. Then December is the holiday season and there are lots of Christmas Movies in December, so people would like to watch movies during this month.</p><p><strong>2. Which movie production company is the most profitable company?</strong></p><p>The list of production company column is as follows. We can see that each row the value is a combination of the production companies names separated by “|”. Therefore, I will use the pandas.Series.str.get_dummies to return a binary indicator matrix of the company, then append these dummy variables to my original data frame using pd.concat. I have created a function <strong>indicator_by_feature() (Appendix 2)</strong> to create dummy columns base on the feature column I choose(production companies, genres, cast), calculate the indicator(mean, sum) of the calculation field(profit, adjusted profit, average vote).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*-os-LrJqLVJzHCV9SOPe0w.png" /></figure><pre>dummies_columns = basic_dataframe[feature_col].str.get_dummies(sep=’|’)<br> df_final = pd.concat([basic_dataframe, dummies_columns], axis=1)</pre><p>I wonder which company has the most total profit. Therefore I use the function indicator_by_feature().</p><pre>df_com = df.copy()</pre><pre>df_com_total_profit = indicator_by_feature(df_com,’production_companies’,’profit’,’sum’)</pre><pre># The top 10 production companies ranked by total profit<br>df_com_total_profit[:10]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*k9gPZFOYuOhr9iLOB4d16A.png" /></figure><pre>df_com_total_adj_profit = indicator_by_feature(df_com,’production_companies’,’profit_adj’,’sum’)<br># The top 10 production companies ranked by total adjusted profit<br>df_com_total_adj_profit[:10]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*VSoZ6XBKl7WbA7P7nftQGg.png" /></figure><p>The top 10 production companies lists ranked by total profit and total adjusted profit have lots of overlapped companies, for example Warner Bros., Universal Pictures, Paramount Pictures, Twentieth Century Fox Film Corporation, Walt Disney Pictures, Columbia Pictures, New Line Cinema, and Amblin Entertainment.</p><h4>3. Which movie genre is the most profitable genre?</h4><p>As the genre column is also a column with a combination of genres in one cell. I will still use the function indicator_by_feature() to get the rank of the movie genre.</p><pre>df_genre = df.copy()</pre><pre># average profit by each genre</pre><pre>df_genre_profit = indicator_by_feature(df_genre,’genres’,’profit’,’avg’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*-OMl6NvJiQcRbqP0buKSwg.png" /></figure><pre># average adjusted profit for each genre<br>df_genre_adj_profit = indicator_by_feature(df_genre,’genres’,’profit_adj’, ‘avg’)<br>df_genre_adj_profit</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*8_DRvdaim73WdJQ80i-BiA.png" /></figure><p>The movie genre that has the largest profit and adjusted profit is Animation. We can check the comparison of calculation fields by genre.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*KPm3MPYL2Bp3-oC43PMOrA.png" /></figure><h4>4. Which actor is the most profitable actor that can bring the most profit?</h4><p>Let us check who is the most bankable star that brings the highest profit and adjusted profit. We still use the function indicator_by_feature() to get the answer.</p><pre>df_actor = df.copy()</pre><pre># check the total profit by each actor</pre><pre>df_actor_total_profit = indicator_by_feature(df_actor ,’cast’,’profit’,’sum’)<br>df_actor_total_profit</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*ujOYhQISVtnN0thgjS__2w.png" /></figure><pre>df_actor = df.copy()</pre><pre># check the total adjusted profit by each actor</pre><pre>df_actor_total_profit = indicator_by_feature(df_actor ,’cast’,’profit_adj’,’sum’)</pre><pre>df_actor_total_profit</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*uwrb-Mxv5oGIIZKZaejAoA.png" /></figure><p>The star that can bring the highest total profit and the highest total adjusted profit is Harrison Ford. The actor with the second-highest adjusted profit is Tom Cruise and the third one is Tom Hanks.</p><p>From the four questions above, we know that the movies that released in June and December or released on Wednesdays,<br>always earn a lot of money. Big production companies, animation genre, and big stars will always collect the larget proportion of benefits in this industry.<br>As a movie investor, I want to know how well can we predict a movie’s average vote, profit, and adjusted profit.</p><p><strong>5. How well can we predict a movie’s average vote? What aspects correlate well to its average vote?</strong></p><p>I want to apply the linear regression model to predict the average vote. Therefore, I need to do more cleaning of the data frame, for example, remove some columns I do not need, and turn some categorical columns into dummy variables.</p><pre>df_pred = df.copy()</pre><pre># check the datatype <br>df_pred.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*CT7mkRg-S1_MiCqCh2cTfQ.png" /></figure><p>The release year is also a DateTime, so I will drop this column at first. I choose two categorical columns to convert to dummy variables. The “director” and “cast” are also categorical columns but I did not choose them because I do not want so many dummy variables.</p><pre>for col in [‘genres’,’production_companies’]:<br> dummies_columns = df_[col].str.get_dummies(sep=’|’)<br> df_ = pd.concat([df_, dummies_columns], axis=1)</pre><p>I only want to use numeric columns:</p><pre># Only use the numerical columns <br>numerics = [&#39;int16&#39;, &#39;int32&#39;, &#39;int64&#39;, &#39;float16&#39;, &#39;float32&#39;, &#39;float64&#39;]<br>df_model = df_.select_dtypes(include=numerics)</pre><p>After all these data cleaning steps, let us check how many columns in df_model.</p><pre>df_model.shape</pre><pre>Out[69]:</pre><pre>(3854, 3296)</pre><p>There are 3296 columns and only 3854 rows in this dataset. The number of rows is a little bigger than that of columns. Therefore, I will do the feature selection with the feature_selection package in sklearn.</p><p>Define the X and y at first:</p><pre>X = df_model.drop(&#39;vote_average&#39;,1)<br>y = df_model[&#39;vote_average&#39;]</pre><pre># pearson’s correlation feature selection for numeric input and numeric output<br> # Create and fit selector<br> selector = SelectKBest(score_func=f_regression, k=10)<br> selector.fit(X, y)</pre><p>Then we can use the SelectKBest() selection method to find the 10 best features that we will use.</p><pre># pearson&#39;s correlation feature selection for numeric input and numeric output<br># Create and fit selector<br>selector = SelectKBest(score_func=f_regression, k=10)<br>selector.fit(X, y)<br># Get columns to keep and create new dataframe with those only<br>cols = selector.get_support(indices=True)<br>X_selected = X.iloc[:,cols]<br>print(&quot;The columns left are:&quot;)<br>print(X_selected.columns)</pre><pre>Out[78]:</pre><pre>The columns left are:<br>Index([&#39;popularity&#39;, &#39;revenue&#39;, &#39;runtime&#39;, &#39;vote_count&#39;, &#39;revenue_adj&#39;,<br>       &#39;profit&#39;, &#39;profit_adj&#39;, &#39;Comedy&#39;, &#39;Drama&#39;, &#39;Horror&#39;],<br>      dtype=&#39;object&#39;)</pre><p>Then let us use split the data into train and test set. Then apply the linear regression model and get back the evaluation indicators of the model.</p><pre>X_train, X_test, y_train, y_test = train_test_split(X_selected, y, test_size=0.2, random_state=0)</pre><pre>regressor = LinearRegression()  <br>    regressor.fit(X_train, y_train) #training the algorithm</pre><pre>y_pred = regressor.predict(X_test)</pre><pre>print(&#39;Mean Absolute Error:&#39;, metrics.mean_absolute_error(y_test, y_pred))  <br>    print(&#39;Mean Squared Error:&#39;, metrics.mean_squared_error(y_test, y_pred))  <br>    print(&#39;Root Mean Squared Error:&#39;, np.sqrt(metrics.mean_squared_error(y_test, y_pred)))<br>    print(&#39;R square:&#39;,metrics.r2_score(y_test, y_pred))</pre><pre>Out[79]:</pre><pre>Mean Absolute Error: 0.49745945025019167<br>Mean Squared Error: 0.4019416764711173<br>Root Mean Squared Error: 0.63398870374094<br>R square: 0.3499607819931152</pre><p>R-Squared(0.349): only 35% of the variability in the vote average can be explained by the model.</p><h4>6. How well can we predict a movie’s adj profit? What aspects correlate well to its adj profit?</h4><p>To make the prediction process more productive, I create a function <strong>linear_regression()(Appendix 3) </strong>to get the evaluation indicators by inputting the target variable’s column name.</p><p>The evaluation indicators I get is :</p><pre>Mean Absolute Error: 78720314.91636488<br>Mean Squared Error: 1.6824098974243844e+16<br>Root Mean Squared Error: 129707744.46517773<br>R square: 0.386260119091398</pre><h3>Evaluation</h3><p>From the R-squared we know that only 35% of the variability in the vote average can be explained by the model. And only 39% of the variability in the adjusted profit can be explained by the model. In general, the higher the R-squared, the better the model fits the data.</p><p>But R-squared cannot determine whether the coefficient estimates and predictions are biased, which is why I assess the residual plots. Also, R-squared does not indicate whether a regression model is adequate. we may have a low R-squared value for a good model, or a high R-squared value for a model that does not fit the data.</p><h3>Deployment</h3><p>As a movie investor, from the questions above I know that:</p><ol><li>The movie release on Wednesday will bring high profits. Also, July and December are the peak months for the movie industry. so I will choose the right season to release my movie.</li><li>The big production companies such as Warner Bros., Universal Pictures, Paramount Pictures, Twentieth Century Fox Film Corporation, Walt Disney Pictures, Columbia Pictures, New Line Cinema, and Amblin Entertainment are in the top 10 production companies lists ranked by total profit and total adjusted profit. To cooperate with the big companies, I will have a high probability to get a great profit.</li><li>The genre of Animation can bring the highest average profit. The second genre is Adventure and the third one is Fantasy. The animation is the genre that is popular so that I will think about investing in an animation movie.</li><li>The most bankable star that can generate the most average profit is Raquel Welch. Jason Miller has the most average adjusted profit. But the star that can bring the highest total profit and total adjusted profit is Harrison Ford. The bankable stars will attract people to go to see movies.</li><li>The vote average and profit can not be predicted well from the linear regression model. I think the reasons why the model does not fit very well are:</li><li>The TMDB dataset has 10866 rows and 21 columns. But 7011 rows have 0 values in the budget, revenue, or runtime columns. For further data analysis, I drop the 7011 rows. Removing the 70% of the rows of the dataset, there must be a lot of information missing.</li><li>The latest release year of the movies in this dataset is 2015, the results of the analysis can not track the latest changes. There are lots of movies releasing from 2016 to 2020. The movie industry has changed a lot in the past five years. For example, Netflix produces movies, and consumers may choose to watch movies on TV instead of going to the theater. Therefore, I will ask the data engineer more updated data.</li></ol><p>More details in the <a href="https://github.com/cssamanda0104/Data-Scientist-Nanodegree-Project-1-Write-A-Data-Science-Blog-Post">https://github.com/cssamanda0104/Data-Scientist-Nanodegree-Project-1-Write-A-Data-Science-Blog-Post</a></p><p>Appendix:</p><ol><li>peak_season()</li></ol><pre>def peak_season(calculation_col, time_range):<br> <br> “””<br> a multiple line plot shows the latest 10 years’ sum of the calculation column by different time range<br> <br> input: <br> calculation_col: profit, profit_adj, vote_average<br> time_range: weekday, month, quarter<br> output:<br> None<br> <br> “””<br> <br> if time_range == ‘weekday’:<br> df_season[‘release_’+ time_range] = df_season[‘release_date’].dt.weekday<br> if time_range == ‘month’:<br> df_season[‘release_’+ time_range] = df_season[‘release_date’].dt.month<br> if time_range == ‘quarter’:<br> df_season[‘release’+ time_range] = df_season[‘release_date’].dt.quarter<br> <br> <br> # find out the adjuested revenue for each quarter in each year<br> df_timerange_revenue = pd.pivot_table(df_season, values= calculation_col, index=’release_’+ time_range,<br> columns=[‘release_year’], aggfunc=np.sum).reset_index()<br> # There are some time ranges do not have profit data in some years, I drop the year column when there are NA value<br> df_timerange_revenue.dropna(axis = 1, inplace = True)<br> # I only want to check the most recent 10 years of quartely profit.<br> df_10_year_mr = pd.concat([df_timerange_revenue.iloc[:, 0], df_timerange_revenue.iloc[:, -10:]], axis=1)</pre><pre># Draw a line plot to check the seasonality of the profit curve in differnt time range.<br> # style<br> plt.style.use(‘seaborn-darkgrid’)<br> # create a color palette<br> palette = plt.get_cmap(‘Set1’)<br> # multiple line plot<br> num=0<br> plt.figure(figsize=(20,12))<br> for column in df_10_year_mr.drop(‘release_’+time_range , axis=1):<br> num+=1<br> plt.plot(df_10_year_mr[‘release_’+ time_range], df_10_year_mr[column], marker=’’, color=palette(num), linewidth=1, alpha=0.9, label=column)<br> # Add legend<br> plt.legend(loc=2, ncol=2, fontsize = 14)<br> # Add titles<br> plt.title(calculation_col + “ by “ + time_range + “ plot”, loc=’center’, fontsize=18, fontweight=0, color=’orange’)<br> plt.xlabel(time_range, fontsize=14)<br> plt.ylabel(calculation_col, fontsize=14)<br> plt.xticks(fontsize=14)<br> plt.yticks(fontsize=14);</pre><p>2. indicator_by_feature()</p><pre>def indicator_by_feature(basic_dataframe, feature_col, calculation_col, cal_method):<br> <br> “””<br> create dummy columns base on the feature column, calculate the indicator, <br> create a dataframe to store the results.<br> <br> input:<br> basic_dataframe — the basic dataframe which is a copy of df<br> feature_col — “geners”, “production_companies”, or “cast”<br> calculation_col — “profit” or “profit_adj”<br> cal_method — “avg” or “sum”<br> <br> output:<br> a dataframe contains the categories in the feature col and the average indicator<br> <br> “””<br> <br> # Use pandas.Series.str.get_dummies to return a binary indicator matrix of genre, <br> # Then append to your original dataframe using pd.concat.<br> dummies_columns = basic_dataframe[feature_col].str.get_dummies(sep=’|’)<br> df_final = pd.concat([basic_dataframe, dummies_columns], axis=1)<br> <br> # create a feature list to store all the types in the feature.<br> feature_list = df_final.columns[17:].tolist()</pre><pre># create a blank list to store the average indicator<br> indicator_list = []</pre><pre>for feature in feature_list:<br> cnt = df_final[feature].sum()<br> total = df_final[df_final[feature] == 1][calculation_col].sum()<br> if cal_method == “avg”:<br> indicator = total/cnt<br> else: <br> indicator = total<br> indicator_list.append(indicator)</pre><pre># Create a dataframe to store the production company name and its average vote<br> df_feature_indicator = pd.DataFrame(list(zip(feature_list, indicator_list)), <br> columns =[feature_col, cal_method + ‘_’ + calculation_col]) <br> <br> # sort the dataframe by the calculation field<br> df_feature_indicator.sort_values(by = cal_method + ‘_’+ calculation_col, \<br> ascending = False, inplace = True)<br> return df_feature_indicator</pre><p>3. linear_regression()</p><pre>def linear_regression(col):<br> “””<br> args: the column name we want to predict<br> output : the parameters to test the model<br> <br> “””<br> # get the X and y<br> X = df_model.drop(col,1)<br> y = df_model[col] <br> <br> if col == ‘profit_adj’:<br> X = df_model.drop([‘budget_adj’, ‘revenue_adj’,’profit’,’budget’, ‘revenue’],1)</pre><pre># pearson’s correlation feature selection for numeric input and numeric output<br> # Create and fit selector<br> selector = SelectKBest(score_func=f_regression, k=10)<br> selector.fit(X, y)<br> # Get columns to keep and create new dataframe with those only<br> cols = selector.get_support(indices=True)<br> X_selected = X.iloc[:,cols]<br> print(“The columns left are:”)<br> print(X_selected.columns)<br> X_train, X_test, y_train, y_test = train_test_split(X_selected, y, test_size=0.2, random_state=0)</pre><pre>regressor = LinearRegression() <br> regressor.fit(X_train, y_train) #training the algorithm</pre><pre>y_pred = regressor.predict(X_test)</pre><pre>print(‘Mean Absolute Error:’, metrics.mean_absolute_error(y_test, y_pred)) <br> print(‘Mean Squared Error:’, metrics.mean_squared_error(y_test, y_pred)) <br> print(‘Root Mean Squared Error:’, np.sqrt(metrics.mean_squared_error(y_test, y_pred)))<br> print(‘R square:’,metrics.r2_score(y_test, y_pred))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d9beef988e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>