Exploratory Analysis and Data Wrangling


Exploratory Analysis and Data Wrangling

Maria
Welcome to Part 3A of Machine Learning Essentials for Biomedical Data Science. In this episode, we are focusing on the early stages of preparing data for machine learning, especially exploratory data analysis and data wrangling.

Anna
And this is the first half of a two-part discussion on data preparation. Today we will cover exploratory analysis, feature extraction, formatting, cleaning, and integration. Part 3B will continue with data splitting and feature processing.

Maria
A useful way to think about the machine learning pipeline is that it should begin with a clearly defined target problem. As Charles Kettering put it, “A problem well-stated is a problem half-solved.” Before touching the data, we need to communicate the problem, the goal or hypothesis, the target outcome, the nature and quality of the data, and how much data we have.

Anna
We should also bring in domain knowledge at this stage. That includes possible sources of bias, reasonable assumptions, known predictors or covariates, and whether features will need to be extracted or engineered before modeling.

Maria
Exactly. These considerations matter whether you are preparing your own analysis or working with a data scientist. They help everyone understand what the data represents and what a successful analysis is supposed to accomplish.

Anna
The next stage is data collection, and that raises a long list of practical and ethical questions. Do we have the right data for the problem? What sources already exist? Are there privacy concerns? Is the data public, or does access require permission, training, certification, or approval?

Maria
We also need to plan where the data will be stored, whether there is enough space, and whether sensitive data has proper security and restricted access. Patient identifiers are especially important here. Finally, we need to know whether the data is structured, semi-structured, or unstructured, because the format determines what processing will be needed.

Anna
And if suitable data does not already exist, we may need to generate new data. That means thinking about the study design and the way new observations will be collected.

Maria
This brings us to the first major machine learning pitfall: bad data. Bad data can lead to bad results throughout the entire downstream pipeline.

Anna
Bad data can take several forms. It can be noisy, meaning it contains uninformative, conflicting, or misleading information. It can be dirty, meaning it contains missing values or errors that do not reflect the true values at collection.

Maria
It can also be sparse. Sparsity might mean too few samples, many missing values, or categorical features with a huge number of possible categories, such as ZIP code.

Anna
Bias is another concern. It can result from how the data was selected, from outliers, or from survivorship bias—for example, when only patients who were still alive were available for data collection. We also need to watch for accidental duplicate instances and features that are perfectly or highly correlated.

Maria
The main responses are to define and understand the target problem clearly, perform exploratory analysis, and follow good practices when collecting and cleaning data. Those steps give us the perspective needed to identify and address problems in the dataset.

Anna
A question that naturally follows is: how many instances do we need? Unfortunately, there is no universal answer. It depends on the problem's complexity, the learning algorithm, the proportion used for training versus evaluation, and whether data must also be held out for replication or validation.

Maria
As rough guidelines, simpler machine learning models might need at least 100 samples per class. More complex approaches such as deep learning might need around 1,000 samples per class. About 5,000 samples per class gives more comfort for average problems, while 10,000 per class provides fairly solid ground for many situations.

Anna
But those are only rough recommendations. Cleaner and simpler problems may require fewer observations, while noisy or complex problems may require more. Also, more data is not automatically better: adding poor-quality or inconsistent observations may fail to improve performance.

Maria
There are several ways to estimate sample needs more specifically. We can look at published research on similar problems, use a heuristic based on the number of classes, or relate the number of independent instances to the number of features or model parameters.

Anna
Nonlinear algorithms and models that detect complex multivariate interactions will generally require more instances. Another option is to simulate datasets and empirically examine how dataset size relates to model performance. In practice, researchers usually try to collect as much data as they can afford within their time and financial constraints.

Maria
Now let us define the broader purpose of data preparation. It helps us understand the data we have, convert it into a format that machine learning can use, identify and remove errors or potential biases, and provide the smallest set of relevant or maximally informative features possible.

Anna
The first data preparation element is exploratory data analysis, or EDA. It is also called descriptive analysis. EDA uses summaries and visualizations to investigate the main characteristics of data, discover patterns between features and outcomes, and examine relationships among features.

Maria
EDA is also useful for spotting anomalies, outliers, and errors; checking assumptions for later statistical tests; and testing initial hypotheses. It is not a single event that happens only at the beginning. Some parts are useful for an initial quality assessment, while others may be repeated just before modeling, so EDA should be integrated throughout data preparation.

Anna
Examples include calculating means, medians, modes, ranges, variances, and interquartile ranges. We can identify whether variables are categorical or numeric, count feature and outcome types, and examine correlations, perhaps with a correlation heat map.

Maria
We can also study individual feature-outcome associations using statistical tests or plots such as bar charts and scatter plots. EDA includes checking class balance, counting missing values across features or instances, and applying strategies to detect outliers.

Anna
Class imbalance is the second major machine learning pitfall. It occurs when one class makes up a much larger proportion of the data than another. That imbalance can affect some algorithms and can also change how we interpret evaluation results.

Maria
One option is to keep the imbalance and remain mindful of it, especially by using appropriate evaluation metrics later. Another is undersampling, where we randomly select from the majority class to create a more balanced dataset. The drawback is that we lose observations, which is usually undesirable.

Anna
A third option is oversampling, where we repeatedly resample the minority class to increase its apparent size. Unless there is a clear justification, this should generally be avoided because it can introduce bias by effectively manufacturing data to create balance.

Maria
The next broad area is data wrangling, also called data munging. It is the process of cleaning and unifying messy, complex datasets so they are easier to access and analyze. Data wrangling is closely connected with EDA because examining the data often reveals the cleaning and restructuring it needs.

Anna
The aspects we are covering are feature extraction, data formatting, data cleaning, and data integration. Data wrangling can also include structuring, enriching, validating, and publishing data, although those activities are outside our main focus here.

Maria
Feature extraction means creating new features when the raw data cannot be used directly for analysis. The new features should accurately represent the raw data. Extraction can be done manually, or it can be automated through machine learning.

Anna
For example, from an image of a car, a researcher might manually create features such as the number of wheels or the car's color. Alternatively, methods such as deep learning can automatically extract features or even model the original non-tabular data directly.

Maria
Raw data that may require extraction includes images, audio, video, unstructured text, and time series. For spam detection, we might turn emails into features indicating whether words such as “money” or “pills” appear, whether spelling is poor, or whether the sender is known. Those engineered features can then form a tabular dataset for machine learning.

Anna
The best extraction technique depends on the problem and the data type. One text approach is bag of words, which counts word occurrences but ignores grammar and word order. That can be useful, but word order may contain important predictive information in some problems.

Maria
Another example is an autoencoder, a neural network that learns a compressed representation of raw data such as images. Other unsupervised learning methods can also be used for feature extraction. Feature extraction should not be confused with feature learning, which will be discussed with feature processing in the next video.

Anna
Data formatting is the logistical process of organizing information according to specifications required by particular algorithms or software packages. This includes file type, such as tab-delimited text or comma-separated values, and the orientation of the table.

Maria
For example, a dataset with features in rows and instances in columns may need to be transposed so that features are columns and instances are rows. Formatting can also require a header, specific labels for features, outcomes, or IDs, and a particular order for the columns.

Anna
Formatting may overlap with feature extraction. We might convert start and stop dates into a single duration feature, or encode text as numbers when a package requires numerical input. But numerical encoding of categories can cause algorithms to treat those categories as quantitative values, so it must be used carefully.

Maria
Missing values also need a consistent representation. It is generally better to avoid numerical codes such as minus nine or minus 999, because a downstream method might mistake them for genuine quantities.

Anna
Data cleaning is the removal of corrupted, inaccurate, biased, or useless records. A basic step is removing redundant features or instances. Redundant features could be duplicate columns or perfectly correlated features, in which case all but one can be removed without losing information.

Maria
It is wise to document those correlations. If the retained feature later appears important, the other correlated features may be candidates for investigating possible causality. For instances, however, identical feature values and outcomes do not always mean duplication; two observations could genuinely be independent samples.

Anna
We can also remove features known to be irrelevant or features that create data leakage. Data leakage occurs when information that should not be available during training is used to train the model.

Maria
For example, imagine predicting whether an emergency-room patient will be admitted to the ICU. A feature recording the total time until ICU admission would not be available at the moment the prediction is supposed to be made, even though it may appear in the historical dataset. Using it would leak future information into training.

Anna
A simpler leakage mistake would be accidentally including the outcome itself as a feature. To prevent leakage, understand what every feature represents in relation to the target, remove features that would not be available in practice, and investigate model performances that seem too good to be true.

Maria
A perfect or unusually strong model should prompt the question, “Did I make a mistake?” Skepticism about our own results can help reveal leakage or other errors.

Anna
Outliers are another cleaning issue. An outlier is an observation that lies an abnormal distance from other values in a random sample. Some outliers are real extreme cases, while others result from data collection errors, especially when the values are impossible.

Maria
Impossible values should generally be corrected or treated as missing, using logic and knowledge of the data. An age of 180 for a human patient is one example. An age of 18 in a study of Alzheimer's patients might also signal a collection error, depending on the study.

Anna
Potential extreme outliers can be identified through sorting, visualization, statistical tests such as z-scores, and the interquartile range. Once identified, we might keep an outlier if it is a real observation, remove it if it is likely an error, or verify and correct it by returning to the source.

Maria
Removal requires caution because we can impose our own biases. It is safer when many other observations are available. If outliers make a distribution non-normal, a logarithmic transformation may reduce their influence and produce a more nearly normal distribution.

Anna
Missing values require different decisions depending on whether the missing item is the outcome or a feature. In supervised learning, an instance without an outcome label generally has to be removed because it cannot contribute to training.

Maria
For missing feature values, one option is to leave them in place if the downstream methods can handle missingness. Such methods may treat missing values as neutral information or perform imputation during processing, so we need to understand how those methods behave.

Anna
Another option is to remove a feature or an instance containing missing values. Removing a feature might discard an important predictor, while removing instances reduces sample size and therefore reduces power to detect real associations. A feature with an especially high frequency of missingness may nevertheless be too low-quality to retain.

Maria
Missingness itself may also be predictive. In that case, we can engineer a feature indicating whether a value is missing. The final option is imputation, which substitutes missing data with estimated placeholder values.

Anna
Imputation can be necessary when a chosen method cannot handle missing values and removing data is not acceptable. But it should be used cautiously: at best it is an educated guess, and at worst it creates manufactured data and bias.

Maria
At a high level, single imputation estimates a missing value from other observations of that particular feature. Multiple imputation estimates it using many or all feature values in the dataset. The appropriate strategy depends on the data and the analysis.

Anna
The final data-wrangling element is data integration: combining features or instances from different sources or studies. In biomedical research, those sources might include environmental information such as lifestyle or socioeconomic data, clinical records or trial data, biological measurements, and genetic or other omics data.

Maria
These sources may be in different files, formats, locations, or institutions. The first challenge is overcoming data silos, which are isolated stores of information. Access may require permissions, data-sharing agreements, and logistical planning.

Anna
After access is arranged, the data may need to be unified across formats and harmonized across institutions or clinical trials. Harmonization means ensuring that the final dataset uses consistent features and feature names, standardized values and encodings, and compatible measurement units.

Maria
Security must be considered during integration and when storing the final dataset. Patient identifiers might be required to link records, and that makes strong protection especially important.

Anna
So the initial preparation stage is a progression: define the problem, understand and collect appropriate data, investigate it through EDA, then wrangle it through extraction, formatting, cleaning, and integration.

Maria
And throughout the process, we need to watch for bad data, class imbalance, leakage, outliers, missingness, bias, and security concerns. In Part 3B, the preparation discussion will continue with data splitting and feature processing.

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