<?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 Tom Allport on Medium]]></title>
        <description><![CDATA[Stories by Tom Allport on Medium]]></description>
        <link>https://medium.com/@ta7qf?source=rss-d23027b6c755------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0aIBc0dItQE70KcICqhnBQ.jpeg</url>
            <title>Stories by Tom Allport on Medium</title>
            <link>https://medium.com/@ta7qf?source=rss-d23027b6c755------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:52:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ta7qf/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[Use PySpark for your Next Big Problem]]></title>
            <link>https://medium.com/swlh/use-pyspark-for-your-next-big-problem-8aa288d5ecfa?source=rss-d23027b6c755------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aa288d5ecfa</guid>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Tom Allport]]></dc:creator>
            <pubDate>Sat, 15 Jun 2019 19:01:00 GMT</pubDate>
            <atom:updated>2019-06-15T19:01:00.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z68F4SMRusBjJ7Q8ox4Waw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">NASA</a> on <a href="https://unsplash.com/search/photos/big-data?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Use PySpark for Your Next Big Problem</h3><h4>Harnessing the power of big data</h4><p>Big Data is becoming a buzz word in all areas of business with its ability to answer more questions more completely and allows more confidence in the quality of the data. The question is how can you harness this power for your next problem?</p><p>Spark is a platform for cluster computing. A cluster is a set of loosely or tightly connected computers that work together to perform the same task. Spark lets you spread information and computations over clusters with multiple nodes (think of each node as a distinct computer). Splitting up your data makes working with huge datasets easier since each node only works with a small amount of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGMpCZJ6vVKhg773UeHwQQ.png" /><figcaption>Simple Cluster Computing Architecture</figcaption></figure><p>Each node works on its own subset of the total data and also performs part of the total calculations required, so that both data processing and computation are performed in parallel over the nodes in the cluster. Parallel computation can make certain types of programming tasks much faster.</p><p>However, as the computation power increases the complexity of dealing with the data and creating meaningful solutions also increases. Deciding whether or not Spark is the best solution for your problem is not always clear cut, but some useful questions to ask are:</p><ul><li>Is my data too big to work with on a single machine?</li><li>Can my calculations be easily parallelised?</li></ul><p>Connecting to a cluster is the first step in using Spark. Usually, the cluster will be hosted on a remote machine that’s linked to all other nodes. There will be one computer, called the master that manages splitting up the data and the computations. The master is connected to the rest of the computers in the cluster, which are called slaves. The master sends data to the and calculations to the slaves to run, and they send their results back to the master. When you’re just getting started with Spark it’s simpler to just run a cluster locally — the principles remain the same though.</p><p>Spark’s core data structure is the Resilient Distributed Dataset (RDD). This is a low-level object that allows Spark to work its magic by splitting data across multiple nodes in the cluster. However, RDDs are difficult to work with directly, so for this article I will be working with its DataFrame abstraction which is built on top of RDDs.</p><p>The Spark DataFrame was designed to behave a lot like a SQL table (a table with variables in the columns and observations in the rows). Spark DataFrames are both considerably easier to understand and work with as well as being better optimised than RDDs for complicated operations.</p><p>When you start modifying and combining columns and rows of data, there are many ways to arrive at the same result, but some often take much longer than others. When using RDDs, it’s up to the data scientist to figure out the right way to optimise the query, but the beauty of using the Spark DataFrame implementation is that is has much of this optimisation built in.</p><p>You can always convert a Spark DataFrame to a pandas DataFrame using .toPandas() and vice versa the .createDataFrame() method takes a pandas DataFrame and returns a Spark DataFrame. However, it’s easy to work in PySpark without using pandas at all.</p><p>For this article I am going to be using the Default of Credit Card Clients Dataset provided by UCI Machine Learning. The dataset contains information on default payments, demographic factors, credit data, history of payment, and bill statements of credit card clients in Taiwan from April 2005 to September 2005.</p><p>First, we need to set up a SparkSession in our environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b4186ffb2fdaa98f679dbcdf8bddb5a/href">https://medium.com/media/4b4186ffb2fdaa98f679dbcdf8bddb5a/href</a></iframe><p>Now we import the data into our environment. You can read csv files and other formats using .read</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e672ccb3d91a34932babfd2eb57da47e/href">https://medium.com/media/e672ccb3d91a34932babfd2eb57da47e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDHuV0xPFzFaivIxtDSsKw.png" /></figure><p>A basic understanding of SQL is going to be helpful in managing Spark DataFrames as the operations are analogous.</p><pre># Add column to DataFrame<br>data = data.withColumn(&quot;colname&quot;,new_column)</pre><pre># Filter data with a SQL string<br>filtered_data = data.filter(&quot;colname &gt; value&quot;)</pre><pre># Filter data with a boolean column<br>filtered_data2 = data.filter(data.colname &gt; value)</pre><pre># Select the first set of columns<br>selected1 = data.select(&quot;colname1&quot;, &quot;colname2&quot;, &quot;colname3&quot;)</pre><pre># Group by column<br>grouped_data = data.groupBy(&quot;colname&quot;)</pre><pre># Join the DataFrames<br>joined_data = data1.join(data2, on=”common_colname”, how=”join_type”)</pre><p>Now we have the data, the next step is to build models to gain insight from the data. The first thing to note here is that PySpark needs numeric data to perform machine learning. To get data into numeric form there is the cast function which can be used to create new columns of the desired datatype.</p><p>For this article I won’t be doing any data preprocessing so I will skip to the last step in the Pipeline — combining all of the columns containing our features into a single column. This has to be done before modelling can take place because every Spark modelling routine expects the data to be in this form. You can do this by storing each of the values from a column as an entry in a vector. Then, from the model’s point of view, every observation is a vector that contains all of the information about it and a label that tells the modeller what value that observation corresponds to.</p><p>The pyspark.ml.feature submodule contains a class called VectorAssembler. This Transformer takes all of the columns you specify and combines them into a new vector column.</p><p>Pipeline is a class in the pyspark.ml module that combines all the Estimators and Transformers that you’ve already created. This lets you reuse the same modelling process over and over again by wrapping it up in one simple object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a8419bc5d0fa38f3e98eec8d5bab546/href">https://medium.com/media/6a8419bc5d0fa38f3e98eec8d5bab546/href</a></iframe><p>Depending on the datatypes different methods will need to be included to the pipeline. PySpark has functions for handling strings built into the pyspark.ml.features submodule. You can create ‘one-hot vectors’ to represent unordered categorical data. A one-hot vector is a way of representing a categorical feature where every observation has a vector in which all elements are 0 except for at most one element, which has a value of 1. Each element in the vector corresponds to a level of the feature, so it’s possible to tell what the right level is by seeing which element of the vector is equal to one 1.</p><p>The first step to encoding your categorical feature is to create a StringIndexer. Members of this class are Estimators that take a DataFrame with a column of strings and map each unique string to a number. Then, the Estimator returns a Transformer that takes a DataFrame, attaches the mapping to it as metadata, and returns a new DataFrame with a numeric column corresponding to the string column.</p><p>The second step is to encode this numeric column as a one-hot vector using a OneHotEncoder. This works exactly the same way as the StringIndexer by creating an Estimator and then a Transformer. The end result is a column that encodes your categorical feature as a vector that’s suitable for machine learning routines!</p><pre># Create a StringIndexer<br>string_indexer = StringIndexer(inputCol=”inputCol”, outputCol=”outputCol”)</pre><pre># Create a OneHotEncoder<br>one_encoder = OneHotEncoder(inputCol=”inputCol”, outputCol=”outputCol”)</pre><p>Now split the data into train and test using then create an instance of the ml model of your choice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e97a580dfc30d126275f764f1887ce0/href">https://medium.com/media/5e97a580dfc30d126275f764f1887ce0/href</a></iframe><p>Now we fit the model and then test it on the test set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6decf32a1e49a4f4e93896dc7063437/href">https://medium.com/media/d6decf32a1e49a4f4e93896dc7063437/href</a></iframe><p>And that’s it, you’ve used PySpark to classify if someone is likely to default on their credit card payment, using a framework that allows you to scale this project up to use much larger datasets which might provide more accurate results.</p><h4><strong>Conclusion</strong></h4><p>PySpark is a great tool for performing machine learning on large datasets that are too big to run on a single machine and when the calculations can be easily parallelised. The workflow and code are very similar to any other python library and allows you to harness the power of big data and cluster computing.</p><h4><strong>Key vocab</strong></h4><p>Pyspark — Python implementation of Apache Spark</p><p>Cluster — a set of loosely or tightly connected computers that work together to perform the same task</p><p>Node — a computer used as a server to perform the tasks</p><p>Parallel computation — a type of computation in which many calculations or the execution of processes are carried out simultaneously.</p><p>RDD — Resilient distributed database</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aa288d5ecfa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/use-pyspark-for-your-next-big-problem-8aa288d5ecfa">Use PySpark for your Next Big Problem</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AutoML — A Tool to Improve Your Workflow]]></title>
            <link>https://medium.com/data-science/automl-a-tool-to-improve-your-workflow-1a132248371f?source=rss-d23027b6c755------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a132248371f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[h2o]]></category>
            <category><![CDATA[automl]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <dc:creator><![CDATA[Tom Allport]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 19:33:22 GMT</pubDate>
            <atom:updated>2019-06-13T21:40:19.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bp6ZYiZm4Rb445dvh7_FDw.png" /><figcaption>Photo by <a href="https://unsplash.com/@agkdesign?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alex Knight</a> on <a href="https://unsplash.com/search/photos/robot?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>AutoML — A Tool to Improve Your Workflow (Updated)</h3><h4>A improved look at H2O AutoML in binary classification</h4><p><strong>After publishing my original article on this topic, </strong><a href="https://twitter.com/ledell"><strong>Erin LeDell</strong></a><strong> — Chief machine learning scientist at h2o.ai, provided me with some great feedback on the article. As a response to this I decided to include her comments in this article to demonstrate how easy it can be to use the AutoML features.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4MySh4Oo1aTNyquK3MPtQ.png" /></figure><p><strong>I have included the feedback sections in bold throughout the article and the gist she provided at the end of the article.</strong></p><p>Recently, the upsurge in demand for data science skills has grown faster than the current supply of skills can keep up with. Today it’s difficult to imagine a business that wouldn’t benefit from the detailed analysis data scientists and machine learning algorithms perform. As artificial intelligence makes its way into every corner of industry, it’s hard to meet the demand of data scientists in every possible use case. To elevate the pressure created by this shortage, several companies have started developing frameworks which are able to partly automate the process typically taken by a data scientist.</p><p>AutoML is a method which automates the process of applying machine learning techniques to data. Typically, a data scientist would spend much of their time pre-processing, selecting features, selecting and tuning models and then evaluating the results. AutoML is able to automate these tasks by providing a baseline result but can provide high performing results to certain problems and insights into where to explore further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*vG03fma-Ee7OJLHJs4F3WA.png" /></figure><p>This article is going to look at the Python module H2O and its AutoML feature. H2O is a Java-based software for data modelling and general computing. According to H2O.ai:</p><blockquote>“The primary purpose of H2O is as a distributed (many machines), parallel (many CPUs), in memory (several hundred GBs Xmx) processing engine.”</blockquote><p>AutoML is a function in H2O that automates the process of building large number of models, with the goal of finding the “best” model without any prior knowledge. AutoML isn’t going to win you any competitions but it can provide lots of information to help you build better models and reduce the time spent exploring and testing different models.</p><p>The current version of their AutoML function can train and cross-validate a Random Forest, an Extremely-Randomized Forest, a random grid of Gradient Boosting Machines, a random grid of Deep Neural Nets, and then trains a Stacked Ensemble using all of the models.</p><p>Stacking (also called meta ensembling) is a model ensembling technique used to combine information from multiple predictive models to generate a new model. Often times the stacked model (also called 2nd-level model) will outperform each of the individual models due its smoothing nature and ability to highlight each base model where it performs best and discredit each base model where it performs poorly. For this reason, stacking is most effective when the base models are significantly different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*TcGmOuMTARvshOY5bDN81Q.png" /><figcaption>Stacking visualized — Image from <a href="http://supunsetunga.blogspot.com/">http://supunsetunga.blogspot.com/</a></figcaption></figure><p>Stacking methods are procedures designed to increase predictive performance by blending or combining the predictions of multiple machine learning models. There is a variety of ensembling or stacking methods, from simple ones like voting or averaging the predictions, to building complex learning models (logistic regressions, k-nearest neighbours, boosting trees) using the predictions as features.</p><p>Stacking of machine learning model predictions very often beat state-of-the-art academic benchmarks and are widely used to win Kaggle competitions. On the downside, they are usually computationally expensive, but if time and resources are not an issue, a minimal percentage improvement in predictive performance could, for example, help companies save a lot of money. The AutoML feature can also drastically reduce the time it takes to run some of these stacked methods.</p><h4>Data Exploration</h4><p>This article is going to look at the Mushroom Classification Dataset which can be found on Kaggle and is provided by UCI Machine Learning. The dataset contains 23 categorical features and over 8000 observations. The data is classified into two categories, edible and poisonous. The classes are fairly evenly distributed, with 52% of the observations in the edible class. There are no missing observations in the data. This is a popular dataset with over 570 Kernels on Kaggle which we can use to see how well AutoML performs against traditional workflows.</p><h4>Running H2O</h4><p>First you will need to install and import the H2O Python module and H2OAutoML class, as with any other library, and initialize a local H2O cluster.(I am using Google Colab for this article.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/378da8345f5ba658cd0f5589443083b0/href">https://medium.com/media/378da8345f5ba658cd0f5589443083b0/href</a></iframe><p>Then we need to load the data, this can either be done straight into a “H2OFrame” or (as I will do for this dataset) into a panda DataFrame so that we can label encode the data and then convert it to a H2OFrame. As with many things in H2O, the H2OFrame works very similarly to a Pandas DataFrame but with its slight differences and syntax <strong>— H2O AutoML can handle categorical columns directly so this step is not necessary.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07f63509946e3135f4c2c58e9c73eb0c/href">https://medium.com/media/07f63509946e3135f4c2c58e9c73eb0c/href</a></iframe><p>Even though AutoML will be doing most of the work for us in the initial stages it is important that we still have a good understanding of the data we are trying to analyse so that we can build upon its work.</p><pre>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*doSx25dYa12vUFM09vo9UA.png" /><figcaption>H2OFrame from df.describe()</figcaption></figure><p>Similar to functions in sklearn we can create a train test split so that the perfomance of the model can be checked on an unseen dataset to help prevent overfitting. It is important to note that when splitting frames, H2O does not give an exact split. It’s designed to be efficient on big data, using a probabilistic splitting method rather than an exact split. For example, when specifying a 0.70/0.15 split, H2O will produce a test/train split with an expected value of 0.70/0.15 rather than exactly 0.70/0.15. On small datasets, the sizes of the resulting splits will deviate from the expected value more than on big data, where they will be very close to exact <strong>— Note here its not necessary to include the validation set as I don’t use it later but it can be used if needed</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02acdb89cd22dd16d2d102c128c9e6ef/href">https://medium.com/media/02acdb89cd22dd16d2d102c128c9e6ef/href</a></iframe><p>Then we need to get the column names for the dataset so we can pass them to the function. For AutoML there are a few parameters which should be specified x, y, training_frame, validation frame out of which y and training_frame are required parameter and rest are optional. You can also configure values for max_runtime_sec and max_models here. max_runtime_sec parameter is required, and max_model is optional if you don’t pass any parameter it takes NULL by default. The x parameter is the vector of predictors from training_frame if you don’t want to use all predictors from the frame you passed you can set it by passing it to x.</p><p>For this problem we are going to send all the parameters in the dataframe to x (except the target) and set the max_runtime_sec to 10 minutes (some of these models take a long time). Now it’s time to run AutoML:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff16233af340f5c71d75c97ea8055db/href">https://medium.com/media/0ff16233af340f5c71d75c97ea8055db/href</a></iframe><p>Here the function has been specified to run for 10 minutes but a max number of models could have been specified instead (or alongside). If you wish to tune the process of how AutoML runs there are also plenty of optional parameters you can pass to do this. Here are the descriptions from the h2o documentation:</p><ul><li>x: A list/vector of predictor column names or indexes. This argument only needs to be specified if the user wants to exclude columns from the set of predictors. If all columns (other than the response) should be used in prediction, then this does not need to be set.</li><li>validation_frame: This argument is ignored unless nfolds == 0, in which a validation frame can be specified and used for early stopping of individual models and early stopping of the grid searches (unless max_models or max_runtime_secs overrides metric-based early stopping). By default and when nfolds &gt; 1, cross-validation metrics will be used for early stopping and thus validation_frame will be ignored.</li><li>leaderboard_frame: This argument allows the user to specify a particular data frame to use to score and rank models on the leaderboard. This frame will not be used for anything besides leaderboard scoring. If a leaderboard frame is not specified by the user, then the leaderboard will use cross-validation metrics instead, or if cross-validation is turned off by setting nfolds = 0, then a leaderboard frame will be generated automatically from the training frame.</li><li>blending_frame: Specifies a frame to be used for computing the predictions that serve as the training frame for the Stacked Ensemble models metalearner. If provided, all Stacked Ensembles produced by AutoML will be trained using Blending (a.k.a. Holdout Stacking) instead of the default Stacking method based on cross-validation.</li><li>fold_column: Specifies a column with cross-validation fold index assignment per observation. This is used to override the default, randomized, 5-fold cross-validation scheme for individual models in the AutoML run.</li><li>weights_column: Specifies a column with observation weights. Giving some observation a weight of zero is equivalent to excluding it from the dataset; giving an observation a relative weight of 2 is equivalent to repeating that row twice. Negative weights are not allowed.</li><li>ignored_columns: (Optional, Python only) Specify the column or columns (as a list/vector) to be excluded from the model. This is the converse of the x argument.</li></ul><p>Once the models have run, you can view which models have performed best, and consider these for further investigation.</p><pre>lb = aml.leaderboard<br>lb.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ht5Mb0FvfaJqLGqimKh9A.png" /><figcaption>Leaderboard of best models from H2O AutoML</figcaption></figure><p>To check that the model hasn’t been overfitted, we now run it on the test data:</p><pre>preds = aml.predict(test)</pre><h4>Results</h4><p>The AutoML has given an accuracy and F1 score of 1.0 on the test data, suggesting the model hasn’t been overfit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7Lr8OcUR6Wsf0lSEzUA-Q.png" /><figcaption>Results for best model from AutoML on test data</figcaption></figure><p>Clearly this is an exceptional case for AutoML as we cannot improve on 100% accuracy on our test set without testing on more data. Looking at many of the Kernels submitted to Kaggle for this dataset, it seems that lots of people (and even the Kaggle Kernel Bot) were also able to produce the same result using traditional machine learning methods.</p><p><strong>Here is the gist provided by Erin LeDell:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e47e3c5453a9eadb885ae8874452b7f3/href">https://medium.com/media/e47e3c5453a9eadb885ae8874452b7f3/href</a></iframe><h4>Future Work</h4><p>The next step would be to save the trained model. There are two ways to save the leader model — binary format and MOJO format. If you’re taking your model to production, then it is suggested to use MOJO format since it’s optimised for production use.</p><p>Now that you have found the best model for the data, further exploration can be done into steps that will increase the performance of the model. Maybe the best model on the training data overfits and another of the top models is preferred. Perhaps the data could be better prepared for some of the models or only select features of most importance. Many of the best models in H2O AutoML use Ensemble methods and maybe the models the ensemble uses can be tuned further.</p><p>Although AutoML alone won’t get you top spot in machine learning competitions, it is definitely worth considering as an addition alongside your blended and stacked models.</p><p>AutoML can handle a varitey of different dataset types including binary classification (as was shown here), multi-class classification as well as regression problems.</p><h4>Conclusions</h4><p>AutoML is a great tool to help (not replace) the work that data scientists do. I look forward to see the advances that can be made in AutoML frameworks and how they can benefit all of us as data scientist as well as the organisations they serve. A single automated mixer certainly cannot outperform a human creative mind when it comes to feature engineering but AutoML is a tool worth exploring in your next data project.</p><p><strong>Thank you again to Erin LeDell for the feedback and make sure to follow her on </strong><a href="https://twitter.com/ledell"><strong>twitter</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTPw0H-q3m8d9zX2rJBgzQ.jpeg" /><figcaption>Image from TechRadar</figcaption></figure><h4>Key Vocab</h4><ul><li>AutoML — A framework for automating some of the tasks typically performed by a data scientist.</li><li>H2OFrame — H2O version of a Pandas DataFrame.</li><li>Stacking — a model which takes several different models and creates a prediction based on the results of these “sub-models”.</li></ul><h3>Further Reading</h3><ul><li>Tutorial on H20 including AutoML and other features — <a href="http://docs.h2o.ai/h2o-tutorials/latest-stable/h2o-world-2017/automl/index.html">http://docs.h2o.ai/h2o-tutorials/latest-stable/h2o-world-2017/automl/index.html</a></li><li>To learning more about stacked models — <a href="http://blog.kaggle.com/2016/12/27/a-kagglers-guide-to-model-stacking-in-practice/">http://blog.kaggle.com/2016/12/27/a-kagglers-guide-to-model-stacking-in-practice/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a132248371f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/automl-a-tool-to-improve-your-workflow-1a132248371f">AutoML — A Tool to Improve Your Workflow</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Should Use Convolutions in Your Next Neural Net — Using TensorFlow]]></title>
            <link>https://medium.com/better-programming/why-you-should-use-convolutions-in-your-next-neural-net-using-tensorflow-37d347544454?source=rss-d23027b6c755------2</link>
            <guid isPermaLink="false">https://medium.com/p/37d347544454</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Tom Allport]]></dc:creator>
            <pubDate>Wed, 05 Jun 2019 19:11:46 GMT</pubDate>
            <atom:updated>2019-06-08T18:16:35.652Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why You Should Use Convolutions in Your Next Neural Net — Using TensorFlow</h3><h4>Dramatically improve performance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKfIBp6SnoOm8koISygJrQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kalenemsley?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kalen Emsley</a> on <a href="https://unsplash.com/search/photos/mountains?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Neural Nets are a common solution to the image classification problem. Typically they will train by taking a large dataset of images, flatten the image, pass it through fully connected layers, and then to the output layer to get the prediction. This article won’t be touching on many of the basics of neural nets, so if you are new to the top I recommend you read <a href="https://medium.com/@eth6re/beginners-guide-to-building-neural-networks-in-tensorflow-dab7a09b941d">this</a> first.</p><p>Some of the basics that will be required to understand this article are that an image is a matrix of values (typically three layers with values ranging from 0 to 255) and, as with most data science, a reasonable understanding of linear algebra.</p><p>For this article we are going to be looking at a model that could be used to classify images in the <a href="https://www.kaggle.com/puneet6060/intel-image-classification">Intel Image Classification</a> dataset on <a href="https://www.kaggle.com/">Kaggle</a>. The data contains around 25k images of size 150x150 distributed across 6 categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1utdJDbQBPxiIFP_NaRo8w.png" /><figcaption>Some of the images in the dataset</figcaption></figure><p>In <a href="https://www.tensorflow.org/">TensorFlow</a>, a typical neural net with no hidden layer may look something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0f527396a0b5647dc81e2f06f3eea5c/href">https://medium.com/media/a0f527396a0b5647dc81e2f06f3eea5c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ffa14XYmjBroij3KsLlsQw.jpeg" /><figcaption>Comparing Neural Net with and without hidden layers. Source: <a href="https://towardsdatascience.com/multi-layer-neural-networks-with-sigmoid-function-deep-learning-for-rookies-2-bf464f09eb7f">https://towardsdatascience.com/multi-layer-neural-networks-with-sigmoid-function-deep-learning-for-rookies-2-bf464f09eb7f</a></figcaption></figure><p>This is a simple neural net which flattens the image into a 1-d array, uses 128 input functions to help classify the image with a ReLu activation function and then 6 outputs, one for each of the potential classes the image could be in.</p><p>For this more complicated problem, the model performs fairly poorly with an accuracy of only 20% on the testing set. We can do better!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s6vlcJSxsRNdepME" /><figcaption>Training and testing results for classification with simple neural net</figcaption></figure><h3>What is a Convolution</h3><p>Convolutions are a set of layers that go before the neural network architecture. The convolution layers are used to help the computer determine features that could be missed in simply flattening an image into its pixel values. The convolution layers are typically split into two sections, convolutions and pooling.</p><p>First, a convolution uses a filter which is applied to the image in order to highlight certain features deemed important in the classification of the image. These filters can be to highlight simple features, such as vertical or horizontal lines to make it more obvious to the computer what it is looking at.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*SDGrpKjKssRZxBm6ERselA.jpeg" /><figcaption><strong>Left:</strong> Image of a building <strong>Right: </strong>Same image with horizontal line convolution applied. Source: <a href="http://aishack.in/tutorials/image-convolution-examples/">http://aishack.in/tutorials/image-convolution-examples/</a></figcaption></figure><p>When thinking about convolutions, there are three main characteristics of the layers that need to be considered.</p><p>The first is the <strong>kernel size</strong>. This is the dimension of the filter that you will be a applying to the image. Changing the size of the kernel depends on what images you are looking at. If you are looking at a larger image, you will typically want a larger kernel, as the features will typically be larger. If you are looking at a smaller image, a smaller kernel will be preferable, as you don’t want to miss the key features in the image.</p><p>Next we have <strong>padding</strong>, which is a fairly simple concept of adding extra pixels around the side of the image so that we can apply the convolution to all of the original pixels equally.</p><p>Finally, we have the <strong>stride</strong> of the filter. As the name suggests this is the number of pixels the filter moves each time it is applied. A larger stride results in reduced image size and quicker training time, but may yield lower performance in certain cases. A non-linear function, such as ReLu, is often applied after the convolution to ensure all pixels have positive values.</p><p>After a convolution layer, we have a <strong>pooling layer</strong>. The pooling layer takes the image from the convolution (which is still an image as it is a 2-d matrix of values) and then applies a function to a section of the pixels. Typical examples of pooling layers use functions such as min, max and mean to result in a new pooled image.</p><p>The benefit of pooling is that is drastically reduces the size of the image going into the next layer (either another convolution or the flattening layer before the fully connected layers).</p><p>For this dataset, there are over 14000 images in the training set, a reasonable size for a problem like this — more complicated problems can use millions of images. The architecture of the neural net for this problem uses two convolutions and therefore two pooling layers with size 2, so the dimensions of the image gets halved twice before it reaches the main neural net. This means that we are effectively training on fewer than 1000 images in terms of processing time — clearly a huge benefit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*GksqN5XY8HPpIddm5wzm7A.jpeg" /><figcaption>Visual representation of how MaxPool works. <em>Source: </em><a href="http://cs231n.github.io/convolutional-networks/#pool"><em>http://cs231n.github.io/convolutional-networks/#pool</em></a></figcaption></figure><h3>When to use more convolutions, and how many convolutions should you use</h3><p>In general, the more convolution layers you are using the better. However, there is a trade-off in training time. As you increase the number of convolution layers, you are increasing the detail in the image you are looking for.</p><p>For example the first layer may just find vertical edges in an image, the second layer then adds horizontal edges and then a third a certain type of curve. Each layer is adding more detail to the image that is being passed to the computer but more computations have to be performed. As you increase images there are diminishing returns for the accuracy in classification that can be achieved since you are looking for more specific details each time.</p><h3>When to Use Convolutional Neural Networks</h3><p>CNN were designed to map image data to an output variable. They have proven so effective that they are the go-to method for any type of prediction problem involving image data as an input. The benefit of using CNN is their ability to develop an internal representation of a 2-d image. This allows the model to learn position and scale invariant structures in the data, which is important when working with images that cannot be understood by simply flattening an image. Typically we want to use a CNN for image data, classification prediction problems or regression prediction problems. More generally, CNN work well with data that has a spatial relationship.</p><h3>What improvements can these offer over regular neural net</h3><p>The main benefits to a CNN are that reducing the “noise” in an image via filtering the image for important features allows the computer to make better predictions on the image since it is looking at only the important features. Also the pooling layers in a CNN drastically reduce the size of an image the computer is looking at and therefore speeds up the training time significantly. Pooling can also enhance certain features, for example taking the max value we can further highlight the edges in an image whilst reducing its size and still keeping the main idea of the image.</p><p>So if we take our original simple neural net and add some convolutional and pooling layers to the model, we may end up with something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86a3c58bbbddf4cabdd0d7127d3393ae/href">https://medium.com/media/86a3c58bbbddf4cabdd0d7127d3393ae/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*zkxkk1tfa0r5D_wbptUy4A.png" /><figcaption>Diagram of CNN. Source: <a href="https://cdn-images-1.medium.com/max/1600/1*zkxkk1tfa0r5D_wbptUy4A.png">https://cdn-images-1.medium.com/max/1600/1*zkxkk1tfa0r5D_wbptUy4A.png</a></figcaption></figure><p>Now we have added two convolutional layers on top of the neural net. The first takes the image and applies 32 different filters of size 3 and then uses a MaxPooling of size 2 to compress the image. This is repeated again for the smaller image and then passed to the flattening layer and classified as before.</p><p>We now get a training accuracy of over 90% and validation accuracy of 77% as well as a 77% accuracy on the test set of 3000 images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jOCcDz9fPsZm-bK-" /><figcaption>Training and testing results for classification with convolutional neural net</figcaption></figure><p>This is a significant improvement on our original neural net and still takes a reasonably short amount of time to train on over 10,000 images.</p><h3>Where to go from here</h3><p>Further improvements can be made to this model by introducing more convolutional layers to increase the detail passed to the image. The time to run this model has been reasonably small, so increasing the number of layers should not be much of a time penalty for a potential increase in accuracy.</p><p>Another potential way to improve the performance of the model is to use <strong>data augmentation</strong>. Data augmentation involves transforming an image (e.g. a horizontal flip) to essentially create a different image that the computer can learn more from. This technique has proved popular and can often increase performance, especially when the number of images in a class is small.</p><p>Due to the difference in training and testing accuracy, it might be worthwhile to explore methods to prevent overfitting such as dropout. <strong>Dropout</strong> refers to each training stage, when individual nodes are either dropped out of the net with probability 1-p or kept with probability p, so that a reduced network is left — incoming and outgoing edges to a dropped-out node are also removed.</p><h3>Conclusion</h3><p>We have seen that adding convolutional layers to a neural network can dramatically improve the performance of a neural network by reducing the noise in an image and making an image that is more interpretable by the computer. Pooling allows us to both highlight certain features and reduce the size of the images allowing faster training times.</p><h3>Resources</h3><ul><li>Go here for intro to Neural Nets in Tensor Flow <a href="https://medium.com/@eth6re/beginners-guide-to-building-neural-networks-in-tensorflow-dab7a09b941d">https://medium.com/@eth6re/beginners-guide-to-building-neural-networks-in-tensorflow-dab7a09b941d</a></li><li>Data used in this project <a href="https://www.kaggle.com/puneet6060/intel-image-classification">https://www.kaggle.com/puneet6060/intel-image-classification</a></li><li>You can find the model at <a href="https://github.com/TomAllport/Intel-cnn">https://github.com/TomAllport/Intel-cnn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37d347544454" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/why-you-should-use-convolutions-in-your-next-neural-net-using-tensorflow-37d347544454">Why You Should Use Convolutions in Your Next Neural Net — Using TensorFlow</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Assumptions for Regression Problems]]></title>
            <link>https://medium.com/data-science/model-assumptions-for-regression-problems-e4591af44901?source=rss-d23027b6c755------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4591af44901</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Tom Allport]]></dc:creator>
            <pubDate>Fri, 24 May 2019 16:59:02 GMT</pubDate>
            <atom:updated>2019-06-08T21:23:53.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cE0yk1_a6-ROhY8XZktigw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@campaign_creators?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Campaign Creators</a> on <a href="https://unsplash.com/search/photos/graph?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>How to Tackle Your Next Regression Problem</h3><h4>The Key Ideas to Consider for Your Next Regression Model</h4><p><em>Tom Allport, Jammie Wang, Jack Stalfort</em></p><p>This article is going to walk through a few of the ideas you need to be thinking about when building a regression model. In order to produce a well fitting regression model for your data there are several assumptions you need to check, as well as testing for outliers and multicollinearity. After reading this article you should have a better of idea of how to implement a well fitting regression model.</p><p>When looking for relationships in your data, it’s no good just fitting a regression and hoping for the best. Linear regression has many assumptions that need to be met in order for the model to be accurate. Some of the common assumptions are:</p><ul><li><strong>Linearity</strong>: A linear relationship exists between the dependent and predictor variables. If no linear relationship exists, then linear regression is an inaccurate representation of the data</li><li><strong>No multicollinearity</strong>: Predictor variables are not collinear, meaning they aren’t highly correlated</li><li><strong>No autocorrelation</strong> (serial correlation in time): Autocorrelation is when a variable is correlated with itself across observations</li><li><strong>Homoscedasticity</strong>: There is no pattern in the residuals, meaning that the variance is constant</li><li><strong>Normally distributed</strong>: Residuals, independent, and dependent variables must be normally distributed</li><li><strong>Residual average is zero</strong>, indicating that data is evenly spread across the regression line</li></ul><h3>Dataset Distributions</h3><p>The first assumption that a linear regression model makes is the independent variable or predictor (X) and the dependent variable or outcome (y) have a linear relationship.</p><p>Linear regression assumes that the independent and dependent variables are normally distributed, which can be checked in many different ways; the most simple way is by observing a histogram of the values. Other ways of testing normality include a goodness of fit test, Shapiro–Wilk test, which are numerical tests, or generating a Q-Q plot to test normality graphically.</p><p>Sometimes, a <strong>sample size</strong> of 30 or greater is the threshold for determining normality due to the Central Limit Theorem, which states that adding independent and identically distributed random variable will result in a normalized distribution when the sample size is at least 30, even if the random variable themselves are not normal.</p><p>However, there is no true right answer for the minimum sample size (lots of people use 50 + 8k where k is the number of parameters in the model). The sample size is also a trade off between fitting well and time/cost. Not enough samples will result in a regression line that doesn’t fit well, but more samples require time and money to be invested into gathering data.</p><p>However, the predictor and response variables do not necessarily have to be normal. A data set that is not normally distributed can be fixed by applying a transformation to it in order to make it normal. If a data set is skewed due to the presence of outliers, then these points must also be appropriately dealt with to restore normality, which we can do with distribution plots.</p><p>Residuals in linear regression are assumed to be normally distributed. A non-normal residual distribution is the main statistical indicator that there is something “wrong” with the data set, which may include missing variables or non-normal independent/dependent variables.</p><p>Furthermore, homoscedasticity of the residual variance is also assumed; the residuals are assumed to have a constant variance.<strong> </strong>This is important because it demonstrates that the errors are evenly distributed, meaning the linear regression is the “best” fit for all points in the data set. An outlier can affect the normality of the residuals because each data point moves the line towards it. Therefore, looking at the residuals is the best indicator of how good of a fit that linear regression line is, and what we should do to fix it if there are any normality issues.</p><h3>Outliers</h3><p>An outlier is a point in a data set which does not follow the expected trend of that data set. Outliers have the ability to change the slope of the regression. For linear regression this change in slope will have an effect of the output as the effect of the variable has been distorted by the point.</p><p>When considering outliers we need to consider their influence, which is determined by the leverage and residual of the point. <strong>Leverage</strong> is the distance the point is away from the centre of the data set, the further the point is from the centre the higher the leverage and is a number between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*9llO_xXKLxF5ZRoAKCv47w.png" /><figcaption>Points with low leverage</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*L1itGmNbw1YSaRJM0w_hMg.png" /><figcaption>Point on far right has high leverage</figcaption></figure><p>Looking at the plots above, we can see that the furthest right point in Fig 1 has a smaller leverage than the furthest right point in Fig 2 as the distance from the centre of the points is greater.</p><p>In order to see if a point is an outlier we also check the residual value for the point. <strong>Residuals</strong> are defined for each point in the data set as the distance of the point from the true value.</p><p>However, these values vary based on the data and it can be easier to interpret the studentized (standardized) residuals.</p><p><strong>Influence</strong> is the effect of the point on the slope of the regression. Points with high leverage have the potential to have greater influence on the slope of the regression. Consider two people sat on a seesaw, the further the person is sat away from the centre the easier it is for the person to move up and down on the seesaw but the mass of the person also matters. The size of the data set also effects the influence of the outlier, with larger data sets the impact of an outlier is reduced. A common methods of calculating a points influence is Cook’s Distance.</p><p>Once you have determined there is an outlier in the data set there several methods to deal with them effectively. The first option is to <strong>remove the point</strong> from the data set. This has the benefit of removing the influence of the point completely however, if the data set is small or the point is of high leverage, alternative methods should be considered as it may also introduce bias into the regression and find a false relationship in the data. Another method is to <strong>assign a new value</strong> to point, such as the mean of similar values, which is known as imputation. This method is typically used when the value is known to be incorrect and can be beneficial when the data set used is small as it doesn’t remove values. An alternative is to <strong>transform the entire data set</strong> rather than using the recorded values. This can be useful when the outlier is known to be the true value of the point and the point has high leverage.</p><h3>Diagnostic Plots</h3><p>Diagnostic plots commonly graph residual trends in 4 different ways and are incredibly useful for verifying that the assumptions for linear regression have been met. In this section, we will cover each plot.</p><h4>Residuals vs Fitted Plot</h4><p>The residual vs fitted plot is mainly used to check that the relationship between the independent and dependent variables is indeed linear. Good residual vs fitted plots have fairly random scatter of the residuals around a horizontal line, which indicates that the model sufficiently explains the linear relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*rvBod4frsi1OmtpyTUPSfw.jpeg" /></figure><p>In the figure above, Case 1 is a good example of a “good” model as the line through the points is close to horizontal. Case 2 is clearly a parabolic arch, which indicates that there’s some other relationship between the independent and dependent variables that hasn’t been explored yet.</p><h4>Normal Q-Q Plot</h4><p>The normal Q-Q plot examines the normality of the residuals. Given that one of the main assumptions for a good linear regression model is the normality of the residuals, this plot can tell us a lot about the relationship between the variables, as discussed before. A “good” linear regression model will have residuals that closely follow the dashed line, like in Case 1. Clearly, there is something significantly wrong with Case 2 since the residuals do not follow that linear pattern, and are exponential instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Hu-ZfVpMNe4nv1iCYmjG8Q.jpeg" /></figure><h4>Scale-Location Plot</h4><p>Also called the Spread-Location plot, the Scale-Location plot examines the homoscedasticity of the residuals. As discussed before, verifying that the variance of the residuals remains constant ensures that a good linear regression model has been produced. A “good” model will have random scatter around a horizontal line, indicating that the variance has remained constant. Case 1 is a good example of this, while Case 2 shows that the variance of the residuals gradually increases as the points slowly grow farther apart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0hPsSu74mJ_FjuKIgukSJg.jpeg" /></figure><h4>Residuals vs Leverage Plot</h4><p>The Residuals vs Leverage plot allow us to find cases that significantly impact the linear regression line. To do this, the plot generates a line that indicates Cook’s distance, which is defined as the sum of all the changes in the regression model when an observation is removed from it. Any point outside of Cook’s distance is considered to be influential. The general cutoff for Cook’s distance is 0.5. The larger the Cook’s distance score for a point, the more influential it is to the regression line. This method is very good at identifying outliers and leverage points.</p><p>When looking at the plot, we simply want to remove any data points located outside of Cook’s distance. For example, in Case 1, there are no points outside of the dashed line indicating Cook’s distance, so there is no need to remove any outliers or leverage points. However, in Case 2, there is a data point far outside of the Cook’s distance threshold, indicating that it is a point of high influence and should be dealt with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Wi2D6gdkRIF12bAtQ_9u3A.jpeg" /></figure><h3>Multicollinearity</h3><p>One big assumption about linear regression models is that our predictor variables are independent. That means that each predictor variable doesn’t depend on any other independent variable. Only the response variable does that, which is why it is also called the dependent variable.</p><p>However, say we have a model and we graph 2 of our predictors against each other:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/0*XeU5DGCiGazKXnpg" /></figure><p>These variables don’t look independent, but we assumed that they were. So our assumptions have not been met. When two or more variables we assume to be independent are actually dependent on each other, we have multicollinearity.</p><p>There are two main types of multicollinearity. One is called “structural multicollinearity”. This is when we make new predictor variables based on old ones. A common example of this would be making a predictor variable X² from X - clearly X² will be correlated with X. So how do we fix this? One way is to remove X² from the model. But some quadratic models need this squared component. So we do something called centring the predictors. To centre the predictors we find the mean of X and subtract it from the values of our observations. This causes approximately half of the observations to have negative values, but when we square X we will still get a positive value. So now the graph of X versus X² is in the shape of a parabola, lowering R² between the two predictors.</p><p>The more common form of multicollinearity is called “data based multicollinearity”. It happens when seemingly uncorrelated variables are correlated. In the first form of multicollinearity, X² was correlated with X as is it is a function of X. However, if variables we expect to be independent, such as pulse and body square area, are correlated, then we have data based multicollinearity. This type is the most common and problematic, and happens for two main reasons. One is when the people collecting the data rely solely on observational data instead of having a mix of observational data and experimental data. The other, more broad, case happens with a poorly designed experiment, meaning that the researchers collect data in a way that certain variables might be influencing each other.</p><p>So we know what multicollinearity is, but why is this a problem for our model? Say we are trying to predict y with variables X₁, X₂, and X₃.</p><p>If we made a model based on just X₁ and X₂ we get y = 4 + X₁+ 3X₂. If instead we made a model based on X₁ and X₃, we get y = 5 – 5X₁ + 7X₃. Notice how the coefficients all change? These models still predict y accurately, but they go about it in a very different way. So the major flaw multicollinearity brings to your model is that one variable’s influence cannot be isolated. More concisely, multicollinearity doesn’t affect the accuracy of the model, it makes it hard to find the effect one variable has. In our first model an increase of one unit in X₁ caused y to increase by one unit, but our second model had an increase of one unit in X₁ decreasing y by 5 units. So if your goal is to just make a model to predict something, multicollinearity can be ignored. However, if you want to understand each variables’ effect on the dependent variable, multicollinearity needs to be addressed.</p><p>So we know what multicollinearity is and how it affects our model, but how do we detect it? One way is to make a plot of the correlation coefficients between each variable and look for high ones. But this method assumes one variable can only be dependent on just one other one. What if a more complex relationship exists between multiple predictors, like X₁= 2X₂ + 3X₃? A better way of detecting multicollinearity is a method called Variance Inflation Factors (VIFs).</p><p>If multicollinearity is present, the coefficients will vary drastically between each model. If a model is made with just one independent variable, the variance of that variable’s coefficient is at a minimum, and it is called the baseline variance. If we then regress that independent variable against all other independent variables, another model can be created. This model will have a certain R² value. It can be shown that the baseline variance increases by a factor given by this equation involving the R² of this large regression.</p><p>This is called a VIF, and it can be calculated for each independent variable. A VIF less than four is considered good: assumed no multicollinearity for that variable. A VIF between 4 and 10 indicates multicolinearity might be present between variables and might need some investigation. A VIF above 10 is a strong indicator of multicollinearity between variables in your model.</p><p>These VIFs can be used to correct multicollinearity. One way to do this is to remove some of the predictors with a high VIF. If these variables just cannot be removed because we have scientific reason to keep them in there, we still have some options. We could go collect some more data for the predictors with a high VIF, and then recreate the VIFs based on this new and more complete data set. If that still doesn’t change it then we will have to remove some of those variables.</p><h3>Conclusion</h3><p>Now we have seen several methods that you should consider when fitting your regression model that will help improve its preformance.</p><h3>Key Vocab</h3><p>Residuals, fitted values, QQ-plot, multicollinearity, sample size, leverage, influence, outliers, Cook’s Distance, VIF</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4591af44901" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/model-assumptions-for-regression-problems-e4591af44901">Model Assumptions for Regression Problems</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>