|
| 1 | +--- |
| 2 | +title: "Data Sketching: The Art of Guesstimating with Big Data" |
| 3 | +date: 2024-08-07 7:45:00 -0500 |
| 4 | +categories: |
| 5 | + - dataengineering |
| 6 | + - datavisualization |
| 7 | + - datasketching |
| 8 | + - datasketch |
| 9 | +author: steven |
| 10 | +--- |
| 11 | + |
| 12 | +# Data Sketching: The Art of Guesstimating with Big Data |
| 13 | + |
| 14 | +Picture this: You're at a county fair, and there's a huge jar of jellybeans. The person who guesses closest to the actual number wins a |
| 15 | +prize. Now, you could try counting each jellybean individually, but that would take forever. Instead, you might estimate based on the jar's |
| 16 | +size, how densely packed the beans are, and maybe a quick count of one small section. That's essentially what data sketching does, but for |
| 17 | +massive datasets. |
| 18 | + |
| 19 | +## What is Data Sketching? |
| 20 | + |
| 21 | +Data sketching is like being a clever detective with big data. Instead of examining every single piece of evidence (which could take years), |
| 22 | +you use smart techniques to get a good idea of what's going on without looking at everything. It's all about making educated guesses that |
| 23 | +are "good enough" for practical purposes. |
| 24 | + |
| 25 | +The beauty of data sketching is that it lets you work with enormous amounts of data using limited memory and processing power. It's like |
| 26 | +summarizing a thousand-page novel in a few paragraphs - you lose some details, but you capture the essence. |
| 27 | + |
| 28 | +## Aspects of Data Sketching |
| 29 | + |
| 30 | +1. **One-Pass Processing**: Data sketching algorithms typically only need to see each data point once. This is crucial when dealing with |
| 31 | + streaming data or datasets too large to fit in memory. |
| 32 | + |
| 33 | +2. **Approximate Results**: Sketches provide estimates, not exact answers. But these estimates often come with provable error bounds, so you |
| 34 | + know how much to trust them. |
| 35 | + |
| 36 | +3. **Space Efficiency**: Sketches use way less memory than the full dataset. It's like compressing a high-res photo into a smaller file - |
| 37 | + you lose some quality, but it's much easier to store and share. |
| 38 | + |
| 39 | +4. **Fast Processing**: Because sketches are small and approximate, computations on them are typically very fast. |
| 40 | + |
| 41 | +## Data Sketching Techniques and When to Use Them |
| 42 | + |
| 43 | +### Counting and Frequency Estimation |
| 44 | +- **Count-Min Sketch**: |
| 45 | + - What it does: Estimates how often items appear in a data stream. |
| 46 | + - When to use it: Tracking trending hashtags on social media or popular products in e-commerce. |
| 47 | + |
| 48 | +- **HyperLogLog**: |
| 49 | + - What it does: Estimates the number of unique elements (cardinality) in a dataset. |
| 50 | + - When to use it: Counting unique visitors to a website or unique products in a large inventory. |
| 51 | + |
| 52 | +### Set Operations |
| 53 | +**Bloom Filters**: |
| 54 | +- What it does: Tests whether an element is a member of a set. |
| 55 | +- When to use it: Checking if a username already exists or if an email is in a spam database. |
| 56 | + |
| 57 | +### Quantiles and Rankings |
| 58 | +**T-Digest**: |
| 59 | +- What it does: Estimates percentiles and creates histograms. |
| 60 | +- When to use it: Analyzing response times in a web service or summarizing large datasets of numerical values. |
| 61 | + |
| 62 | +### Sampling |
| 63 | +**Reservoir Sampling**: |
| 64 | + - What it does: Maintains a random sample of items from a data stream. |
| 65 | + - When to use it: Keeping a representative sample of user actions on a busy website. |
| 66 | + |
| 67 | +## Data Sketching in Python with Visualizations |
| 68 | +In Python, the `datasketch` library is a popular choice for data sketching. Let's look at some examples and create some impressive |
| 69 | +visualizations. |
| 70 | + |
| 71 | +### HyperLogLog for Cardinality Estimation |
| 72 | + |
| 73 | +First, let's use HyperLogLog to estimate unique visitors to a website: |
| 74 | + |
| 75 | +```python |
| 76 | +import numpy as np |
| 77 | +import matplotlib.pyplot as plt |
| 78 | +from datasketch import HyperLogLog |
| 79 | + |
| 80 | + |
| 81 | +def simulate_website_traffic(n_days, n_visitors_per_day): |
| 82 | + hll = HyperLogLog() |
| 83 | + true_uniques = set() |
| 84 | + estimated_uniques = [] |
| 85 | + true_uniques_count = [] |
| 86 | + |
| 87 | + for _ in range(n_days): |
| 88 | + daily_visitors = np.random.randint(0, n_visitors_per_day * 10, n_visitors_per_day) |
| 89 | + for visitor in daily_visitors: |
| 90 | + hll.update(str(visitor).encode('utf8')) |
| 91 | + true_uniques.add(visitor) |
| 92 | + estimated_uniques.append(len(hll)) |
| 93 | + true_uniques_count.append(len(true_uniques)) |
| 94 | + |
| 95 | + return estimated_uniques, true_uniques_count |
| 96 | + |
| 97 | + |
| 98 | +# Simulate 30 days of traffic |
| 99 | +n_days = 30 |
| 100 | +n_visitors_per_day = 10000 |
| 101 | +estimated, true = simulate_website_traffic(n_days, n_visitors_per_day) |
| 102 | + |
| 103 | +# Plotting |
| 104 | +plt.figure(figsize=(12, 6)) |
| 105 | +plt.plot(range(1, n_days + 1), true, label='True Uniques', marker='o') |
| 106 | +plt.plot(range(1, n_days + 1), estimated, label='HyperLogLog Estimate', marker='x') |
| 107 | +plt.title('Website Unique Visitors: True vs HyperLogLog Estimate') |
| 108 | +plt.xlabel('Days') |
| 109 | +plt.ylabel('Unique Visitors') |
| 110 | +plt.legend() |
| 111 | +plt.grid(True) |
| 112 | +plt.show() |
| 113 | +``` |
| 114 | + |
| 115 | +This code simulates website traffic and compares the true number of unique visitors with the HyperLogLog estimate. The resulting plot shows |
| 116 | +how accurate the estimation is over time. |
| 117 | + |
| 118 | +### Count-Min Sketch for Frequency Estimation |
| 119 | + |
| 120 | +Now, let's use Count-Min Sketch to estimate word frequencies in a large text: |
| 121 | + |
| 122 | +```python |
| 123 | +import numpy as np |
| 124 | +import matplotlib.pyplot as plt |
| 125 | +from countminsketch import CountMinSketch |
| 126 | + |
| 127 | + |
| 128 | +def generate_word_stream(n_words, vocabulary_size): |
| 129 | + return np.random.randint(0, vocabulary_size, n_words) |
| 130 | + |
| 131 | + |
| 132 | +# Generate a stream of words |
| 133 | +n_words = 1000000 |
| 134 | +vocabulary_size = 1000 |
| 135 | +word_stream = generate_word_stream(n_words, vocabulary_size) |
| 136 | + |
| 137 | +# Use Count-Min Sketch |
| 138 | +cms = CountMinSketch(width=1000, depth=10) |
| 139 | +for word in word_stream: |
| 140 | + cms.add(word) |
| 141 | + |
| 142 | +# Get true frequencies |
| 143 | +true_freq = np.bincount(word_stream) |
| 144 | + |
| 145 | +# Get estimated frequencies |
| 146 | +estimated_freq = [cms.check(i) for i in range(vocabulary_size)] |
| 147 | + |
| 148 | +# Plot results |
| 149 | +plt.figure(figsize=(12, 6)) |
| 150 | +plt.scatter(true_freq, estimated_freq, alpha=0.5) |
| 151 | +plt.plot([0, max(true_freq)], [0, max(true_freq)], 'r--') # Perfect estimation line |
| 152 | +plt.title('Word Frequency: True vs Count-Min Sketch Estimate') |
| 153 | +plt.xlabel('True Frequency') |
| 154 | +plt.ylabel('Estimated Frequency') |
| 155 | +plt.grid(True) |
| 156 | +plt.show() |
| 157 | +``` |
| 158 | + |
| 159 | +This code generates a stream of "words" (represented by integers) and uses Count-Min Sketch to estimate their frequencies. The scatter plot |
| 160 | +compares true frequencies with estimated frequencies. |
| 161 | + |
| 162 | +These visualizations demonstrate the power of data sketching techniques. They allow us to process and analyze enormous amounts of data |
| 163 | +efficiently, providing useful insights without the need to store or process every single data point. |
| 164 | + |
| 165 | +Remember, data sketching is all about making smart trade-offs. You're exchanging a bit of accuracy for a lot of speed and efficiency. It's |
| 166 | +not about getting perfect answers, but about getting useful insights from data that would otherwise be too big to handle. |
| 167 | + |
| 168 | +So next time you're faced with a dataset as big as that jellybean jar at the county fair, don't panic! Reach for a data sketch, and you'll |
| 169 | +be making educated guesses in no time. |
0 commit comments