1. Home
  2. Explore
  3. Computer Science
  4. Exploratory Analysis and Data Wrangling

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Exploratory Analysis and Data Wrangling

Transcript

[Music] Hi, I'm Ryan Urbanowicz and welcome to Part 3A of  "Machine Learning Essentials for Biomedical Data Science". In the two videos encompassing Part 3 of  this video series we'll cover the preparation of   data for downstream machine learning analysis. In  the present video we'll cover the initial aspects   of data preparation with focus on "exploratory  analysis" and some of the key elements of "data wrangling".

Here's a quick reminder of the parts  making up this video series. In the last video we   covered biomedical data: goals and challenges.  Due to the amount of content we're going to   cover I've split Part 3 of this series into two  separate videos with 3A focusing on exploratory   analysis and data wrangling as mentioned and 3B  focusing on data splitting and feature processing.   As a refresher here's a schematic illustrating  the potential elements of a data science pipeline that utilizes machine learning. Over the next  two videos we'll discuss all of the elements   leading up to and including data preparation.  But again for now we're just going to cover these   initial elements. As we saw in our last slide,  a data analysis pipeline should typically begin   with the clear definition of a target problem.  Here's a quote by Charles Kettering hinting   at the importance of this. Specifically "A  problem well-stated is a problem half-solved".

Effectively, we want to be able to clearly define  and communicate the problem, associated goal   (and/or hypothesis), the nature of the data itself  (as well as the target outcome of interest),   and the size and the quality of the data. This  is also a good time to think about any available   domain knowledge we might have access  to. Including potential sources of bias,   what reasonable assumptions we're willing or able  to make, whether they're already known predictors of our outcome (including possible covariates),  and whether we know ahead of time that some   features in our data will need to be extracted  or engineered prior to any kind of statistical or   machine learning modeling. We'll learn more about  all of these domain knowledge elements later on.   These are all important considerations when  preparing to conduct machine learning analysis   on your own or when preparing to speak to a data  scientist to get their advice or engage them as

collaborators in the research. The next step  in our analysis pipeline is data collection.   Here are some questions we may need to consider at  this point. What kind of problem are we trying to   solve? Do we have the right data to try and  solve our target problem? What data sources   might already exist that we could access to  solve our problem? Are there patient or other   privacy concerns that will need to be addressed in  order to access, analyze, or share data. There may be important ethical considerations here. Is the  data public or does it require special permission,   training, certifications, or approvals to  access? Once we obtain the data, where will   it be stored? Do we have the space? Do we have  proper security and restricted access for data   that may be sensitive? (In other words, data with  patient identifiers). Also is the data structured,   semi-structured, or unstructured? And based on  its format, what processing might need to be

done before we can start to analyze it? And also  will we need to generate new data from scratch   if sufficient data doesn't already exist? And  what will our study design look like for the   collection of that new data? At this point we hit  our first machine learning pitfall. Specifically,   "bad data". Ultimately bad data can lead to bad  everything downstream. So what specific problems   am I referring to when I say "bad data"? First  off, data can be "noisy" including uninformative features or conflicting or misleading  information with respect to our target problem.   Data can also be "dirty", and by this I mean that  it can include missing values or errors in values   that don't reflect the true values at the time  of collection. Furthermore, data can be "sparse"   meaning that the sample size might be sparse,  there could be a large number of missing values,   or you could have categorical features  with a large number of possible categories.

For example a feature like zip-code, with many  possible unique values across the country. Data   can also be "biased" which may be the result of  selection bias (in how the data was collected)   or it could be due to outliers or survivorship  bias (in other words only patients that were still   alive were available to have their data collected)  And lastly, "duplicate data" where instances may   have been repeated by accident in the data set.  Or features may exist in the data set that are perfectly or highly correlated with one another.  So what are potential solutions for the pitfall   of bad data? First, make sure that you've  taken steps to clearly define and understand   the target problem. Second, employ exploratory  analysis. These first two elements will help   provide the proper perspective to identify  and address bad data. Third, seek to apply   best practices when either collecting or cleaning  data. We'll discuss this more on upcoming slides.

One common question that comes up during data  collection is, how many instances are needed   for machine learning? Unfortunately, the answer  here is, "it depends". There's no simple rule.   It's ultimately going to depend on the complexity  of the problem, the complexity of the learning   algorithm (or algorithms) that you're using, the  ratio of the data that will be used for training   vs. those that are held out for model evaluation,  and whether data is being further set aside for replication or validation downstream. However,  here's a very rough guide to how much training   data you need for machine learning based on my  own experience. Generally, I'd recommend a minimum   of 100 samples per class to train simpler machine  learning models. To train more complex machine   learning models such as "deep learning" I'd  suggest a minimum of 1000 samples per class.   Having 5000 samples per class would put you more  in a comfort zone for machine learning modeling

on average problems. And having 10,000 samples  per class will put you on pretty solid ground   for most any situation. Again, these are just  rough guidelines. Simpler, cleaner problems   require fewer instances for effective training,  and more complex and noisy problems will likely   require more. However, keep in mind that when it  comes to sample size sometimes more isn't always   better. Sometimes more is just more. After all,  the addition of poor quality or inconsistent data is unlikely to improve machine learning  performance. Now let's take a slightly closer   look at this question of sample size. Here are  some possibly better ways for you to answer this   question for yourself. For one you can look for  published research in similar problems to see what   sample sizes were effective in those previous  studies. You could also employ a statistical   heuristic to estimate a target instance count.  This could be some factor of the number of classes

(as I gave in the last slide): in other words have  x independent instances per class. Or it could be   based on a factor of the number of features.  For example, having x percent more independent   instances than there are features. Or it could  be based on a factor of the number of model   parameters (as in the case of applying logistic or  linear regression). For example, use x independent   instances per model parameter. In general be  aware that non-linear algorithms will likely require more instances to be as effective. Also  the detection of complex multivariate interactions   will require more instances as well. Furthermore,  you could use simulated data sets to empirically   evaluate the relationship between data set size  and model performance in order to get a better   estimate of the number of instances you'll need.  Ultimately, we make the best with what we have   and most people would recommend that you gather  as much data as you can afford to collect based

on the constraints of either time or money. Now  we move on to "data preparation" itself. On the   right here we can see the portion of our data  pipeline schematic focused on data preparation.   We'll spend the rest of this and the next video  discussing all the elements included here.   But first, from a high level perspective, let's  review the purpose of data preparation as a whole.   First, it's about getting us oriented with our  available data. Second, it's about getting data into a format that machine learning can work with.  Third, it seeks to identify and remove errors   and potential biases. And four, it seeks to  provide machine learning with the smallest set   of relevant or maximally informative features as  possible. As our first data preparation element,   let's discuss "exploratory data analysis"  otherwise known as "descriptive analysis" or EDA.   The purpose of EDA is to analyze and investigate  data using summaries of main data characteristics

or visualizations. It's typically conducted to  preliminarily understand or discover patterns   between features and outcome or among features  themselves. It's also applied to spot anomalies,   outliers, and errors, as well as to check  assumptions for downstream statistical tests,   and to test initial hypotheses. There isn't really  a single best time to conduct an exploratory   analysis, as aspects of an EDA might be useful to  conduct as an initial assessment of data quality and others might be useful to conduct just before  moving on to modeling. It's best to think of EDA   as being continuously integrated into the entire  data preparation phase of a machine learning   analysis pipeline. So what are some example  aspects of conducting an EDA. It can involve   generating feature summary statistics: including  mean, median, mode, range, variance, interquartile   range, etc. Or can be used to assess feature  and outcome types or counts. In other words

determining if variables are categorical, numeric,  etc. EDA can also include examining correlations   between features. For example, generating this  heat map visualization of feature correlations.   EDA can also focus on explicitly examining  univariate associations between individual   features and outcome. And you can do this by  applying relevant statistical tests of association   or generating plots such as bar or scatter plots.  EDA also includes evaluating possible class imbalance in classification problems. As well as  counting the "missingness" of data values across   features and or instances. And lastly EDA is  the time to apply strategies for detecting "data   outliers" that may need to be addressed. This  brings us to our second machine learning pitfall:   "class imbalance in modeling". So the problem  here is that when we have class imbalance we're   training and evaluating a model with a much  larger proportion of one class than the other.

This can influence the performance of certain  modeling algorithms and how we interpret our   model evaluation results. Potential solutions to  having class imbalance include: One, keeping this   class imbalance in the data but making sure to be  mindful of its presence and making sure to focus   on appropriate evaluation metrics downstream. This  is the strategy that I personally prefer. Second, you can utilize "undersampling". Here we randomly  sample the majority class to make a more balanced   data set. However, the obvious downside here is  the loss in overall sample size, which is almost   never preferable. Or as a third option, you could  utilize "oversampling". Here we randomly resample   the minority class to artificially increase  its sample size to something similar to the   majority class. However, unless you can clearly  justify this I'd strongly recommend avoiding this

approach as you're likely adding bias to your  data, since in essence, you are (to a degree)   manufacturing data to create a balanced data  set. Moving on, let's take a high level look at   "data wrangling" as part of data preparation. This  is the process of cleaning and unifying messy and   complex data sets for easy access and analysis.  It's also referred to as "data munging". Of note,   data wrangling is often intimately connected to  exploratory analysis. In this video we're going to focus on the aspects of data wrangling necessary  for data analysis. Including feature extraction,   data formatting, data cleaning, and data  integration. However, data wrangling can also   be simply focused on the preparation of data  as a resource for others to analyze. This can   include aspects such as structuring, enriching,  validating, and publishing data (that we're not   going to specifically cover here). So let's start  by taking a closer look at feature extraction.

This is where we create new features when we can't  use the original raw data for analysis. So in the   simplest case, the data is in a non-tabular form.  An important consideration here is that these   new features should accurately represent the raw  data. Feature extraction can be achieved manually   or it can be automated using machine learning. For  example a researcher could manually craft features from input data (such as the image of a car) to  pass downstream for machine learning analysis.   These could be features like: the  number of wheels, the color of the car,   etc. Or alternatively, some machine learning  strategies, such as deep learning, could be   applied to automatically extract features or even  conduct modeling directly using non-tabular data.   Some examples of raw data for which feature  extraction might be needed include: images,

audio, video, unstructured text, and time series  data. Now let's look at a simple example of   feature extraction. Here we have some unstructured  text from emails and we want to employ machine   learning to detect whether the email is spam or  not. We could manually construct features that   indicate whether certain "keywords" are present  in a given email. For example, the word "money"   or "pills". Or we could characterize  other aspects of the email as features such as whether the email includes bad spelling  or if the email comes from a known sender.   These "engineered" features now constitute  a standard tabular data set that we can pass   to machine learning to train a model. A few more  bits of information regarding feature extraction.   First, there are a variety of feature extraction  techniques out there and they tend to be problem   or data type dependent. Second, the term "feature  extraction" is sometimes confused with the term

"feature learning" which we'll discuss further  when we get to feature processing in the next   video. And lastly, let's take a look at some  other examples of feature extraction techniques.   One for dealing with unstructured text (in  natural language processing) is the "bag of   words" technique. Similar to the email example,  this counts the occurrence of words found in text   samples. But notably this approach disregards  grammar or word order which might be critical information for making accurate predictions  downstream depending on the problem. Another   approach is an auto encoder which uses a neural  network to learn a compressed representation   of raw data (such as images). Furthermore there  are a variety of other "unsupervised learning"   approaches that are often adopted as feature  extraction techniques. Now let's move on to   "data formatting". We'll define this simply  as organizing information according to preset

specifications. This is an important "logistical"  component of data preparation, so that the data   can be utilized by specific algorithms or packages  downstream. It involves considerations such as the   file type or extension. For example, having tab  delimited text files (in other words .txt) or   comma separated files (in other words .csv files).  And it can involve the orientation of features and instances in the data structure. For example,  if you have a tabular data set with features as   rows and instances as columns this might need to  be transposed so that features are columns and   instances are rows. Formatting can also involve  whether a "header" is included in the data file   and what header labels are expected or allowed.  For example, features, outcome, and maybe instance   IDs. And whether columns have to be arranged in  a certain order or position in the data set. For

example, "outcome" might need to be placed in the  first column and all features coming after it.   Formatting could also involve items that overlap  with feature extraction such as "numerical   encoding" where we have to convert features like  "start" and "stop" dates (which a machine learner   might not know what to do with) into a single  time duration feature. Or it can involve encoding   text values in data into numerical values if the  downstream algorithm or package requires it. For example, most scikit-learn packages require all  data values to be numerically encoded. However,   keep in mind here, that numerically encoding  categorical values will result in them being   treated as "quantitative values" by most machine  learning algorithm implementations. So use some   caution here. And lastly, formatting might need  to consider using a standard identifier for any   missing data values. In general, I recommend  avoiding numerical identifiers like -9 or -999,

as this can easily lead to mistakes downstream  when these identifiers are mistaken for valid   numerical quantities. Now let's move on to "data  cleaning". We'll define "data cleaning" as the   process of removing corrupted, inaccurate,  biased, or useless records from the data.   First let's cover some really basic forms of  data cleaning. For example, removing redundant   features or instances. Redundant features may  be duplicate feature columns that are mistakenly included more than once in the data. Or they could  be perfectly correlated features. With perfectly   correlated features, all but one of them could be  removed prior to analysis to reduce the overall   feature count without losing information. It's  best to document these correlations so that if,   after modeling, the retained feature ends up being  important, we know what other correlated features   might be candidates for causality. Redundant  instances might similarly have been instance

duplicates that were mistakenly included in the  data. However, it's certainly possible to have   two instances that have exactly the same feature  values and outcome but are truly independent   samples. Another form of basic data cleaning  is the removal of features that are either   "irrelevant" (in other words we already know they  have no value in predicting outcome) or removing   features that might introduce "data leakage".  "Data leakage" brings up another potential machine learning pitfall. In the context of machine  learning, data leakage occurs when information   (that shouldn't be in the training set) is used to  train a model. This could be a feature whose value   would not be available when a trained model would  have been applied to make predictions, despite the   future having been available in the training data.  Or it might have been a mistake as simple as;

the outcome having been labeled as a feature. So  for example, consider a feature that captures the   total time until a patient in an emergency room  was admitted to an intensive care unit (ICU). And   in this situation we're trying to predict whether  a patient would be admitted to the ICU. Such a   variable would not be available in practice  when we're trying to predict whether patient   will be admitted to the ICU despite it having  been collected in the dataset being analyzed. Potential solutions here include getting to know  the data and understanding what the features are   or represent (in particular in the context of our  target outcome). And of course make sure to remove   features that represent data leakage prior to  analysis. And lastly, watch out for and track down   causes of model performances that seem "too good  to be true". Often, the first question I ask when

I train a perfect or high-performing model is:  "Did I make a mistake?" After all, being skeptical   of your own work is a great way to avoid mistakes.  Another form of data cleaning to consider is the   handling of "outliers" (or data points that differ  significantly from other observations). Outliers   can represent real but more extreme edge cases  in the data or they might indicate errors in the data collection (in particular when the feature  values of the outlier are impossible). Let's look   at outliers a bit further. Here we can see a rough  illustration of an outlier (in red) among a set   of data points. As a more formal definition, an  outlier is an observation that lies an abnormal   distance from other values in a random sample.  We pretty much always want to apply cleaning   when we encounter impossible outliers since these  often reflect errors in data collection. For this,

apply logic and you're understanding the data  to identify impossible outliers. So for example,   let's say you encounter an instance with a  value of 180 for the age of a human patient.   Or you encounter an instance with an age of 18 in  a study of Alzheimer's patients. In both cases you   would likely reasonably conclude that these were  data collection errors and these values should   be changed to "missing" or possibly the entire  sample removed from the analysis. When it comes to identifying extreme outliers there are a variety  of strategies that can be utilized as part of an   exploratory analysis. Examples include sorting,  data visualization, statistical tests (such as the   z-score), and the use of the interquartile range  (IQR). Once candidate outliers are identified   what you do with them often depends on  your specific data and goals. For example,   you can choose to keep your outlier (or outliers)  since these may be extreme but real values.

Also of course you could remove the outlier (in  particular if you suspect it may be an error).   But beware of applying your own biases when doing  this. It's also safer to remove an outlier when   you have plenty of other instances available. Or  perhaps it's possible to go back to verify or fix   the suspected outlier value if it's possible to  recollect that particular bit of information.   And lastly, when faced with outliers that lead  to data not following a normal distribution, outliers can be de-emphasized using a logarithmic  transformation in an attempt to yield a more   normal distribution. The last aspect of data  cleaning we'll discuss involves "missing values".   First, assuming we are preparing to conduct  "supervised learning" where we need outcome   labels for all instances, if we encounter a  missing value in the outcome of some instance,   we'll have to remove the entire instance  (since it adds nothing to the analysis).

However, if we come across missing values in  our features, we have some options. If we plan   to work only with methods downstream that can  handle the presence of missing values in data,   our first option is to leave them alone. Machine  learning methods that can handle missing values   usually attempt to treat them as neutral  information. Or they apply some form of,   "on the fly", imputation, guessing at its likely  value. If you leave missing values in your data I'd suggest that you make yourself aware of  how these missing values would be handled   in the methods you applied downstream.  When it comes to cleaning missing values,   your first option is to remove either any feature  (or any instance) that includes missing values.   Here the drawback of removing a feature is that  you may be removing a feature that could end up   having been important downstream. And the drawback  to moving instances is the obvious reduction in

sample size which leads to reduced power to detect  true associations. Even if you do not choose this   more extreme approach to missing value data  cleaning, if you find a feature instance in   your data set with a particularly high frequency  of missingness, it may still be prudent to remove   this low quality aspect of your data set. Or, as  we'll see later, you can ask if missingness itself   is predictive of outcome. And we can do this  by engineering a feature for missingness. And lastly, we have the option of "imputation".  "Imputation" is the process of substituting   missing data with placeholder values. My own  personal perspective is that imputation should   be avoided if possible. At its best, imputation  represents an educated guess. But at its worst,   imputation can represent manufactured data that  adds bias to your analysis. Often missing value   imputation is a necessary "evil". Perhaps you want  to apply a methodology that can't handle missing

values but at the same time removing features  or instances entirely is not a satisfactory   solution. Imputation can certainly be justifiable  but it should be used with caution and skepticism.   There are many strategies available for imputing  missing data values ranging in complexity and   performance from data set to data set. At a high  level these methods can be separated into either   single imputation methods (where the placeholder  value is estimated based on other instance values of that respective feature in the data  set. Or into multiple imputation methods,   where the placeholder value is estimated based  on many or all feature values in the data. That   brings us to the last element of data wrangling  that we'll discuss and that's "data integration".   This is the combination of either features  (and/or instances) from different sources   or studies. As a biomedical example, perhaps  data has been collected separately on patients

including: "environmental data" such as lifestyle,  socioeconomic, or behavioral information,   "clinical data" coming from electronic health  records or perhaps clinical trials, "biological   data" such as testing for biomarkers or biological  processes and perhaps genetic or other omics data   in the form of genome-wide association data,  whole exome sequencing, whole genome sequencing,   gene expression, epigenetic data, and more. All  of this data might originate as different files, perhaps with different formats. And further, it  could be stored in different locations or even   across different institutions. So the first  challenge of data integration is overcoming   "data silos" wherein data may be stored in  self-contained islands of isolated access.   We may need to get permission to access certain  data, establish data sharing agreements, and work   out the logistics of access in order to gather  all data required for the downstream analysis.

Next, we might have to deal with unifying data  stored using different formats. Further, it may   be necessary to conduct "data harmonization".  For example to combine data instances that were   gathered across different institutions or  separate clinical trials. This unification   makes sure that the final data set has all the  same features, feature names, standardized values,   value encodings, units of measurements, and so  on. And lastly, we might need to think of data security issues (both during the integration  process and in storing the final data set). For   example, we may need patient identifiers for the  integration process which will require a higher   level security for the protection of patients.  So far in this section on "preparing data",   we've covered all of the "initial" elements of  data preparation, as reviewed in this schematic.   Part 3B of this video series will extend our  overview of data preparation to "data splitting"

and five elements of "feature processing".  And later videos in the series will cover the   remaining elements of a data science pipeline  with machine learning. Thank you for joining   me for part 3A of machine learning essentials  for biomedical data science. In the next video,   we'll extend our discussion of "data preparation"  to include "data splitting" and "feature   processing". If you enjoyed this video please  like and subscribe to follow my future content. [Music]

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent