Data Structures for Big Data¶
When dealing with big data, minimizing the amount of memory used is critical to avoid having to use disk based access, which can be 100,000 times slower for random access. This notebook deals with ways to minimizee data storage for several common use case:
- Large arrays of homogenous data (often numbers)
- Large string collections
- Counting distinct valuees
- Yes/No responses to queries
Methods covered range from the mundane (use numpy
arrays rather than
lists), to classic but less well known data structures (e.g. prefix
trees or tries) to algorihtmically ingenious probabilistic data
structures (e.g. bloom filter and hyperloglog).
Storing numbers¶
Less memory is used when storing numbers in numpy arrays rather than lists.
In [1]:
%load_ext memory_profiler
In [2]:
%memit
peak memory: 117.23 MiB, increment: 0.21 MiB
In [3]:
%memit [0]*int(1e8)
peak memory: 880.07 MiB, increment: 762.77 MiB
In [4]:
%memit list(range(int(1e8)))
peak memory: 3967.04 MiB, increment: 3849.74 MiB
In [5]:
%memit np.arange(int(1e8))
peak memory: 879.11 MiB, increment: 760.94 MiB
Storing strings¶
In [6]:
def flatmap(func, items):
return it.chain.from_iterable(map(func, items))
In [7]:
def flatten(xss):
return (x for xs in xss for x in xs)
Using a list¶
In [8]:
%%memit
with open('data/Ulysses.txt') as f:
word_list = list(flatten(line.split() for line in f))
peak memory: 151.86 MiB, increment: 33.65 MiB
In [9]:
target = 'WARRANTIES'
In [10]:
%timeit -r1 -n1 word_list.index(target)
1 loops, best of 1: 5.59 ms per loop
In [11]:
%timeit -r1 -n1 target in word_list
1 loops, best of 1: 10.1 ms per loop
Using a sorted list¶
In [12]:
%memit word_list.sort()
peak memory: 137.34 MiB, increment: 0.00 MiB
In [13]:
import bisect
%timeit -r1 -n1 bisect.bisect(word_list, target)
1 loops, best of 1: 24.7 µs per loop
Using a set¶
In [14]:
%memit word_set = set(word_list)
peak memory: 140.59 MiB, increment: 3.25 MiB
In [15]:
%timeit -r1 -n1 target in word_set
1 loops, best of 1: 3.39 µs per loop
Probabilisitc Data Structues¶
Morris counter¶
The Morris counter is used as a simple illustration of a probabiliistic data structure, with the standard trading off of using less memory in return for less accuracy. The algorithm is extreemly simple - keep a counte \(c\) that represents the exponent - that is, when the Morris counter is \(c\), the estimated count is \(2^c\). The probabilistic part comes from the way that the counter is incremented by comparing a unform random variate to \(1/2^c\).
In [19]:
from random import random
class MorrisCounter:
def __init__(self, c=0):
self.c = c
def __len__(self):
return 2 ** self.c
def add(self, item):
self.c += random() < 1/(2**self.c)
In [20]:
mc = MorrisCounter()
In [21]:
print('True\t\tMorris\t\tRel Error')
for i, word in enumerate(word_list):
mc.add(word)
if i%int(.2e5)==0:
print('%8d\t%8d\t%.2f' % (i, len(mc), 0 if i==0 else abs(i - len(mc))/i))
True Morris Rel Error
0 2 0.00
20000 16384 0.18
40000 32768 0.18
60000 65536 0.09
80000 65536 0.18
100000 131072 0.31
120000 131072 0.09
140000 131072 0.06
160000 131072 0.18
180000 131072 0.27
200000 131072 0.34
220000 131072 0.40
240000 131072 0.45
260000 131072 0.50
Increasing accuracy¶
A simple way to increase the accuracy is to have multiple Morris counters and take the average. These two ideas of using a proabbilisitc calculation and multiple samples to imrprove precision are the basis for the more useful probabilisitc data structures described below.
In [22]:
mcs = [MorrisCounter() for i in range(10)]
In [23]:
print('True\t\tMorris\t\tRel Error')
for i, word in enumerate(word_list):
for j in range(10):
mcs[j].add(word)
estimate = np.mean([len(m) for m in mcs])
if i%int(.2e5)==0:
print('%8d\t%8d\t%.2f' % (i, estimate, 0 if i==0 else abs(i - estimate)/i))
True Morris Rel Error
0 2 0.00
20000 14336 0.28
40000 40140 0.00
60000 57344 0.04
80000 93388 0.17
100000 93388 0.07
120000 113049 0.06
140000 127795 0.09
160000 140902 0.12
180000 170393 0.05
200000 173670 0.13
220000 203161 0.08
240000 255590 0.06
260000 255590 0.02
Distinct value Sketches¶
The Morris counter is less useful because the degree of memory saved as compared to counitng the number of elemetns exactly is not much unless the numbers are staggeringly huge. In contrast, counting the number of distinct elements exactly requires storage of all distinct elements (e.g. in a set) and hence grows with the cardinality \(n\). Probabilistic data structures knwon as Distinct Value Sketches can do this with a tiny and fixed memory size.
Examples where counting distinct values is useful:
- number of unique users in a Twitter stream
- number of distinct records to be fetched by a databse query
- number of unique IP addresses accessing a website
- number of distinct queries submitted to a search engine
- number of distinct DNA motifs in genomics data sets (e.g. microbiome)
[Hash functions](https://en.wikipedia.org/wiki/Hash_function_¶
A hash function takes data of arbitrary size and converts it into a number in a fixed range. Ideally, given an arbitrary set of data items, the hash function generates numbers that follow a uniform distribution within the fixed range. Hash functions are immensely useful throughout computer science (for example - they power Python sets and dictionaries), and especially for the generation of probabilistic data structures.
A simple hash function mapping¶
Note the collisions. If not handled, there is a loss of information. Commonly, practical hash functions return a 32 or 64 bit integer. Also note that there are an arbitrary number of hash functions that can return numbers within a given range.
Note also that because the hash function is deterministic, the same item will always map to the same bin.
In [24]:
def string_hash(word, n):
return sum(ord(char) for char in word) % n
In [25]:
sentence = "The quick brown fox jumps over the lazy dog."
for word in sentence.split():
print(word, string_hash(word, 10))
The 9
quick 1
brown 2
fox 3
jumps 9
over 4
the 1
lazy 8
dog. 0
Built-in Python hash function¶
In [26]:
for word in sentence.split():
print('{:<10s} {:24}'.format(word, hash(word)))
The -5484744546882122582
quick -7108007350593547279
brown -6814734720224203537
fox -1763212765689429847
jumps 849897467049591091
over -2139207452593339407
the 6020327406432540674
lazy -7708543853339552466
dog. -6627810124593739785
Using a hash function from the MurmurHash3 library¶
Note that the hash function accepts a seed, allowing the creation of multiple hash functions. We also display the hash result as a 32-bit binary string.
In [27]:
import mmh3
for word in sentence.split():
print('{:<10} {:+032b} {:+032b}'.format(word.ljust(10), mmh3.hash(word, seed=1234),
mmh3.hash(word, seed=4321)))
The +0001000011111110001001110101100 +1110110100100101010111100011010
quick -0101111111011110110101100101000 +1000100001101010110000101101100
brown +1000101010000110110010001110101 -1101101110000000010001100010100
fox -1000000010010010000111001111011 +0111011111000011001001001110111
jumps +0000010111000011010000100101010 +0010010001111110100010010110011
over -0110101101111001001101011111011 -1101110111110010000101101000100
the -1000000101110000000110011111001 +0001000111100111011000011100101
lazy -1101011000111111110011111001100 +0010101110101100001000101110000
dog. +0100110101101111101011110111111 -0101111000110000001011110001011
LogLog family¶
The binary digits in a (say) 32-bit hash are effectively random, and equivalent to a sequence of fair coin tosses. Hence the probability that we see a run of 5 zeros in the smallest hash so far suggests that we have added \(2^5\) unique items so far. This is the intuition behind the loglog family of Distinct Value Sketches. Note that the biggest count we can track with 32 bits is \(2^32 = 4294967296\).
The accuracy of the sketch can be improved by averaging results with multiple coin flippers. In practice, this is done by using the first \(k\) bit registers to identify \(2^k\) different coin flippers. Hence, the max count is now \(2 ** (32 - k)\). The hyperloglog algorithm uses the harmonic mean of the \(2^k\) flippers which reduces the effect of outliers and hence the variance of the estimate.
In [28]:
best = 0
k = 16
for i in range(2**k):
r = bin(np.random.randint(0, 2**k))[2:].zfill(k)
run = len(list(it.takewhile(lambda x: x=='1', r)))
if run > best:
best = run
if np.log2(i) in range(k):
print(i, 2**best)
1 2
2 2
4 2
8 4
16 4
32 32
64 128
128 256
256 256
512 1024
1024 4096
2048 8192
4096 8192
8192 8192
16384 32768
32768 32768
In [29]:
from hyperloglog import HyperLogLog
In [30]:
hll = HyperLogLog(0.01)
In [31]:
print('True\t\tHLL\t\tRel Error')
s = set([])
for i, word in enumerate(word_list):
s.add(word)
hll.add(word)
if i%int(.2e5)==0:
print('%8d\t%8d\t\t%.2f' % (len(s), hll.card(), 0 if i==0 else abs(len(s) - hll.card())/i))
True HLL Rel Error
1 1 0.00
6585 6560 0.00
11862 11777 0.00
15390 15318 0.00
18358 18236 0.00
24705 24711 0.00
28693 28749 0.00
30791 30945 0.00
34530 34676 0.00
36002 36076 0.00
41720 42091 0.00
45842 46384 0.00
46389 46978 0.00
49524 50226 0.00
Bloom filters¶
Bloom filters are designed to answer queries about whether a specific item is in a collection. If the answer is NO, then it is definitive. However, if the answer is yes, it might be a false positive. The possibility of a false positive makes the Bloom filter a probabilistic data structure.
A bloom filter consists of a bit vector of length \(k\) initially set to zero, and \(n\) different hash functions that return a hash value that will fall into one of the \(k\) bins. In the construction phase, for every item in the collection, \(n\) hash values are generated by the \(n\) hash functions, and every position indicated by a hash value is flipped to one. In the query phase, given an item, \(n\) hash values are calculated as before - if any of these \(n\) positions is a zero, then the item is definitely not in the collection. However, because of the possibility of hash collisions, even if all the positions are one, this could be a false positive. Clearly, the rate of false positives depends on the ratio of zero and one bits, and there are Bloom filter implementations that will dynamically bound the ratio and hence the false positive rate.
Possible uses of a Bloom filter include:
- Does a particular sequence motif appear in a DNA string?
- Has this book been recommended to this customer before?
- Check if an element exists on disk before performing I/O
- Check if URL is a potential malware site using in-browser Bloom filter to minimize network communication
- As an alternative way to generate distinct value counts cheaply (only increment count if Bloom filter says NO)
In [32]:
from pybloom import ScalableBloomFilter
# The Scalable Bloom Filter grows as needed to keep the error rate small
# The default error_rate=0.001
sbf = ScalableBloomFilter()
In [33]:
for word in word_set:
sbf.add(word)
In [34]:
test_words = ['banana', 'artist', 'Dublin', 'masochist', 'Obama']
In [35]:
for word in test_words:
print(word, word in sbf)
banana True
artist True
Dublin True
masochist False
Obama False
In [36]:
### Chedck
for word in test_words:
print(word, word in word_set)
banana True
artist True
Dublin True
masochist False
Obama False
In [37]:
%load_ext version_information
In [38]:
%version_information pybloom, hyperloglog, hat_trie
Out[38]:
Software | Version |
---|---|
Python | 3.5.1 64bit [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] |
IPython | 4.0.1 |
OS | Linux 4.2.0 23 generic x86_64 with debian jessie sid |
pybloom | 2.0.0 |
hyperloglog | 0.0.10 |
hat_trie | 0.2 |
Sun Jan 24 22:48:43 2016 EST |
In [ ]: