Skip to content
🎯⭐ INTERACTIVE LESSON

Data Compression & Analysis

Learn step-by-step with interactive practice!

Data Compression & Analysis - Complete Interactive Lesson

Part 1: Lossless vs Lossy, Compression Techniques, and Data Analysis

📦 Data Compression & Analysis

Part 1 of 7 — Lossless vs Lossy, Compression Techniques, and Data Analysis


Why Compress Data?

Smaller files mean:

  • Faster transmission over networks
  • Less storage space needed
  • Lower bandwidth usage
  • Faster loading for users

Lossless vs Lossy Compression

TypeData Loss?QualitySmaller?Use Cases
LosslessNo — original perfectly restoredIdentical to originalModerate reductionText, code, spreadsheets, medical images
LossyYes — some data permanently removedSlightly reducedMuch smallerPhotos, music and video for streaming or sharing

Lossless Example: Run-Length Encoding

Original:  AAABBBCCDDDDDD
Compressed: 3A3B2C6D

The original can be perfectly reconstructed from the compressed version.

Lossy Example: Compressing a Photo

A photograph has millions of color values. A lossy image algorithm removes subtle color differences that human eyes cannot easily detect. The file shrinks dramatically, but the removed data cannot be recovered.

🔑 Lossless = perfect reconstruction. Lossy = smaller file but permanent data loss. Choose based on whether quality loss is acceptable.

Concept Check 🎯

Data Analysis and Visualization

Extracting Patterns from Data

When working with large datasets, visualization reveals patterns that raw numbers cannot.

VisualizationBest For
Bar chartComparing categories
Line graphShowing trends over time
Scatter plotShowing relationships between two variables
Pie chartShowing parts of a whole
HistogramShowing frequency distributions

Filtering and Transforming Data

Programs extract information from data with a few basic processes:

  • Transforming: change every element (double every value, add a parent's email to every student record)
  • Filtering: keep only the elements that meet a condition (only scores above 80)
  • Combining or comparing: add up a list, or find the student with the highest GPA
  • Visualizing: turn the data into a chart or graph

Interpreting Results

  • Look for trends (increasing, decreasing, stable)
  • Identify outliers (values far from the norm)
  • Check for clusters (groups of similar data points)
  • Be cautious of bias in data collection

Challenges with Large Datasets

  • Storage: Require significant space
  • Privacy: May contain sensitive personal information
  • Accuracy: Errors are amplified at scale
  • Bias: If collection methods are biased, conclusions will be skewed

Applied Recall ✍️

  1. Compression that can perfectly restore the original data is called _______ compression.

  2. Compression that permanently removes some data, such as sound frequencies most listeners cannot hear, is called _______ compression.

  3. A chart that shows the relationship between two variables using dots is called a _______ plot.

Classify the Compression 🔍

AP Exam Strategy: Data Compression & Analysis

  • Know the difference: lossless (perfect reconstruction) vs lossy (an approximation, usually much smaller). Exam questions describe the situation; they do not ask about specific file formats
  • Lossless for critical data (medical, legal, code). Lossy for media where small quality loss is acceptable
  • Run-length encoding is a simple example of lossless compression; the exam asks you to compare lossless and lossy, not to name specific algorithms
  • Data analysis questions test your ability to interpret visualizations and identify patterns
  • Correlation does not imply causation — always consider confounding variables
  • Large datasets can reveal patterns but also amplify errors and privacy concerns

AP-Style Application 🎯

Part 2: Key Processes

🗜️ Data Compression & Analysis

Part 2 of 7 — Key Processes


Compression: Same Information, Fewer Bits

Compression takes a sequence of bits and produces a shorter sequence that decodes back to the original (lossless) or to an approximation of it (lossy).

TypeRound-trip propertyTypical uses
LosslessDecoded = original, bit-for-bitText, code, spreadsheets, medical images
LossyDecoded ≈ originalPhotos, music and video for streaming or sharing

Concept Check 🎯

How Much Can Lossless Compression Save?

The amount of size reduction depends on two things: how much redundancy (repetition) the original data has, and which compression algorithm is applied.

A simple example: a 100-character string of alternating "AB" patterns can be encoded as "AB × 50" — far smaller. A 100-character string of random characters has no pattern to exploit, so lossless compression saves little or nothing.

Also remember: fewer bits does not necessarily mean less information. A losslessly compressed file holds exactly the same information as the original in fewer bits.

Why Lossy Can Go Further

Lossy compression throws away detail that people are unlikely to notice, such as tiny color differences in a photo or sounds that are hard to hear. Because it keeps only an approximation, it can usually shrink data much more than lossless compression, but the original can never be rebuilt exactly.

A Tiny Lossless Example: Run-Length Encoding

OriginalEncoded
AAAABBBCCD4A3B2C1D
AAAAAAAAAA10A
ABCDEF1A1B1C1D1E1F (worse!)

RLE wins on data with long runs and loses on data without them. Compression is data-dependent.

Applied Recall ✍️

  1. Compression that perfectly preserves the original data is called _______.

  2. Compression that drops some information to save space is called _______.

  3. Repetition in data that compression can take advantage of is called _______.

Targeted Practice 🔍

AP Exam Strategy: Compression Basics

  • "Must be perfect" → lossless.
  • "Need much smaller, perceptual loss OK" → lossy.
  • How much compression saves depends on the data's redundancy AND the algorithm used.
  • Lossy usually shrinks files more than lossless; lossless guarantees the original can be rebuilt.

AP-Style Application 🎯

Part 3: Patterns & Examples

🗜️ Data Compression & Analysis

Part 3 of 7 — Patterns & Examples


The Lossless Pattern: Replace Repeats With Short Codes

Most lossless compression works by finding redundancy (repeated patterns) and replacing each repeat with something shorter. A key records what each short code stands for, so the original can be rebuilt exactly.

OriginalKeyCompressed
AAAAABBBrun-length: count + letter5A3B
the cat sat on the mat# = "at"the c# s# on the m#

The compressed version uses fewer characters (fewer bits), but no information is lost: anyone with the key can decode it back to the original.

Concept Check 🎯

Worked Example: Counting the Savings

Original: the cat sat on the mat (22 characters, counting spaces).

Using the key # = "at", the compressed text is the c# s# on the m# (19 characters). Each of the three "at" pairs became one character, saving 3 characters.

Add a second code, @ = "the ": the text becomes @c# s# on @m# (13 characters). More redundancy removed means more savings, but data with few repeats (like a random string) leaves almost nothing to replace.

Choosing Lossless or Lossy

The AP exam asks you to compare compression options and pick the best one for a particular situation:

SituationBetter choiceWhy
A program's source code, a contract, a bank recordLosslessThe original must be rebuilt exactly.
A medical scan used for diagnosisLosslessQuality is maximally important.
A photo for a social media postLossySize matters more than tiny detail.
A video streamed to a phone on a slow connectionLossyMinimizing transmission time matters most.

🔑 Lossy algorithms can usually shrink data more than lossless ones. Choose lossless when quality or exact reconstruction is maximally important; choose lossy when minimizing size or transmission time is maximally important.

Applied Recall ✍️

  1. When the original data must be rebuilt exactly, choose _______ compression.

  2. When minimizing file size or transmission time matters most, choose _______ compression.

  3. Using the key # = "at", the compressed word "c#" decodes to _______.

Targeted Practice 🔍

AP Exam Strategy: Compression Patterns

  • Lossless = find repeats, replace with shorter codes, keep a key. Nothing is lost.
  • Savings depend on the data's redundancy and on the algorithm applied.
  • Fewer bits does not necessarily mean less information.
  • "Which algorithm is best?" always depends on the context: exact reconstruction → lossless; smallest size / fastest transfer → lossy.

AP-Style Application 🎯

Part 4: Extracting Information and Metadata

🗜️ Data Compression & Analysis

Part 4 of 7 — Extracting Information and Metadata


From Data to Information

Information is the collection of facts and patterns extracted from data. Data give us chances to identify trends, make connections, and address problems.

Two cautions the AP exam returns to again and again:

IdeaWhat it means
Correlation is not causationProcessed data may show that two variables change together. That does not prove one causes the other; more research is needed to understand the relationship.
One source is often not enoughA single data source may not contain everything needed to draw a conclusion. Combining data from several sources is often necessary.

Concept Check 🎯

Metadata: Data About Data

Metadata are data that describe other data. If the data is an image, the metadata might include the date it was created, the location, or the file size.

DataMetadata
A photoDate taken, location, file size
A songArtist, album, length
A documentAuthor, date last edited, number of pages

What metadata do:

  • Find, organize, and manage information. Searching a photo library by date or sorting songs by artist uses metadata.
  • Add useful context, which increases the effective use of the data.
  • Give data structure, so large collections can be organized.

🔑 Changing or deleting metadata does not change the primary data. Editing a photo's date tag leaves every pixel exactly as it was.

Worked Example

A teacher has 2,000 class photos. She adds a tag for the event (field trip, science fair, graduation) to each photo's metadata. Now a search for "science fair" pulls up the right photos in seconds, and none of the images themselves were changed.

Applied Recall ✍️

  1. Data that describe other data, such as a photo's file size, are called _______.

  2. When two variables change together, the relationship is called a _______.

  3. The facts and patterns extracted from data are called _______.

Targeted Practice 🔍

AP Exam Strategy: Information and Metadata

  • "Does this prove X causes Y?" → No; a correlation needs more research to explain.
  • "Why combine data sets?" → a single source often lacks what is needed for a conclusion.
  • Metadata = data about data. They help find, organize, and manage data.
  • Changing metadata does not change the primary data.

AP-Style Application 🎯

Part 5: Challenges of Processing Data

🗜️ Data Compression & Analysis

Part 5 of 7 — Challenges of Processing Data


Every Data Set Has Problems

Data sets pose challenges regardless of size:

ChallengeExample
Data need cleaning"NYC", "New York City", and "new york" all mean the same place.
Incomplete dataSome survey takers left the age field blank.
Invalid dataA high school roster lists a student's age as 150.
Sources must be combinedGrades are in one file and attendance in another.

Data collected through open fields (free typing) are often not uniform: people abbreviate, spell, and capitalize differently. Cleaning makes the data uniform without changing their meaning, for example by replacing every equivalent spelling or abbreviation with the same word.

How well data can be processed also depends on the capabilities of the users and their tools.

Concept Check 🎯

Bias in Data

Problems of bias are often created by the type or source of data being collected. If a survey about public transit is posted only on a car-owners' forum, its results will be skewed no matter how many people answer.

🔑 Bias is not eliminated by simply collecting more data. More data from the same biased source is still biased.

Size Matters

  • The size of a data set affects how much information can be extracted from it. A survey of 10 people reveals far less than a survey of 10,000.
  • Large data sets are difficult to process with a single computer and may require parallel systems (many processors or computers working at the same time).
  • Scalability, a system's capacity to change in size and scale to meet new demands, is an important consideration: the computing capacity of a system affects how data sets can be processed and stored.

Worked Example

A city collects 5 years of bike-share trips: 40 million rows.

  1. Clean: station names were typed several ways; replace each with one standard name.
  2. Check validity: remove trips that end before they start.
  3. Note incompleteness: some trips lack an end station; decide how to treat them and say so.
  4. Scale: the full analysis is split across several computers working in parallel.

Applied Recall ✍️

  1. Making data uniform without changing their meaning is called _______ the data.

  2. A survey field that was left blank is an example of _______ data.

  3. A system's capacity to change in size and scale to meet new demands is called _______.

Targeted Practice 🔍

AP Exam Strategy: Data Challenges

  • Know the four challenges: data need cleaning, incomplete data, invalid data, combining sources.
  • Cleaning = uniform without changing meaning.
  • Bias comes from the type or source of data; more data does not fix it.
  • Big data sets → parallel systems and scalability.

AP-Style Application 🎯

Part 6: Problem-Solving Workshop: Using Programs With Data

🗜️ Data Compression & Analysis

Part 6 of 7 — Problem-Solving Workshop: Using Programs With Data


Four Ways Programs Extract Information

ProcessExample
Transform every elementDouble every number in a list; add a parent's email to every student record.
Filter the data setKeep only the positive numbers; keep only students who signed up for band.
Combine or compareAdd up a list of numbers; find the student with the highest GPA.
VisualizeShow the data as a chart, graph, or other visual.

Tools such as spreadsheets, search tools, and data filtering systems help people organize data, find information efficiently, and recognize patterns. Programs are used iteratively and interactively: you run a program, look at the result, adjust, and run it again.

A filter in AP pseudocode:

scores ← [72, 95, 88, 60, 91]
high ← []
FOR EACH s IN scores
{
    IF (s ≥ 90)
    {
        APPEND(high, s)
    }
}
DISPLAY(high)

Concept Check 🎯

Worked: Transform

prices ← [4, 10, 7]
doubled ← []
FOR EACH p IN prices
{
    APPEND(doubled, p * 2)
}

After the loop, doubled is [8, 20, 14].

Worked: Combine or Compare

Find the highest GPA in a list (lists on the AP exam start at index 1):

best ← gpas[1]
FOR EACH g IN gpas
{
    IF (g > best)
    {
        best ← g
    }
}
DISPLAY(best)

Worked: Patterns Emerge

Combining data sources, clustering data (grouping similar items, such as customers with similar buying habits), and classifying data (sorting items into categories) are all parts of using programs to gain insight. Patterns often appear only after the data are transformed, for example after converting raw timestamps into "hour of the day" and counting trips per hour.

Applied Recall ✍️

  1. Keeping only the elements of a data set that meet a condition is called _______.

  2. After the transform code runs on [4, 10, 7], the second element of doubled is _______.

  3. After the filter program at the top of this part runs, LENGTH(high) is _______.

Targeted Practice 🔍

AP Exam Strategy: Programs and Data

  • Name the process: transform, filter, combine/compare, or visualize.
  • A filter = FOR EACH + IF + APPEND into a new list. A transform = FOR EACH + APPEND of a changed value.
  • Trace code carefully: lists start at index 1, and APPEND adds to the end.
  • Programs are used iteratively and interactively; insight comes from running, inspecting, and adjusting.

AP-Style Application 🎯

Use this program for the first question.

temps ← [50, 68, 75, 59]
warm ← 0
FOR EACH t IN temps
{
    IF (t > 60)
    {
        warm ← warm + 1
    }
}
DISPLAY(warm)

Part 7: AP Review

🗜️ Data Compression & Analysis

Part 7 of 7 — AP Review


AP Exam Recap — Compression & Analysis

Final review.

Concept Check 🎯

Final Vocab

TermDefinition
LosslessReduces bits while guaranteeing the original can be rebuilt exactly.
LossyReduces bits much more, but only an approximation can be rebuilt.
RedundancyRepetition in data; more redundancy allows more compression.
InformationFacts and patterns extracted from data.
MetadataData about data; changing it does not change the primary data.
CorrelationTwo variables change together; this does not prove causation.
CleaningMaking data uniform without changing their meaning.
BiasCreated by the type or source of data; more data does not remove it.
Filtering / transformingKeeping only matching elements / changing every element.
ScalabilityA system's capacity to grow to meet new demands.

Common Pitfalls

  • Saying "compression makes data smaller" without distinguishing lossless vs lossy.
  • Thinking fewer bits always means less information.
  • Treating a correlation as proof of cause.
  • Believing more data from the same source will remove bias.
  • Using lossy formats where exact reconstruction matters (source code, legal or medical records).

Applied Recall ✍️

  1. A photo-sharing app accepts a small loss of image detail to make files much smaller. It uses _______ compression.

  2. A program's source code must be restored exactly after it is decompressed. It needs _______ compression.

  3. Data about data, such as the date a photo was taken, are called _______.

Targeted Practice 🔍

Final Exam Tips

  • Lossless vs lossy is the #1 compression distinction; pick based on the situation.
  • Correlation ≠ causation, and one data source is often not enough.
  • Metadata help find, organize, and manage data.
  • Data challenges: cleaning, incomplete, invalid, combining sources; bias needs a better source, not more data.
  • Programs extract information by transforming, filtering, combining, and visualizing data.

AP-Style Application 🎯