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 than random access. This notebook deals with ways to minimizee data storage for several common use cases:
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 algorithmically ingenious probabilistic data structures (e.g. bloom filter and hyperloglog).
We have alrady seen that there are many ways to retrieve only the parts of the data we need now into memory at this particular moment. Options include
numpy.memmap
h5py
redis
)sqlite3
)
In [1]:
sys.getsizeof(list(range(int(1e8))))
Out[1]:
In [2]:
np.arange(int(1e8)).nbytes
Out[2]:
In [3]:
np.arange(int(1e8)).astype('float32').nbytes
Out[3]:
In [4]:
np.arange(int(1e8)).astype('float64').nbytes
Out[4]:
In [5]:
def flatmap(func, items):
return it.chain.from_iterable(map(func, items))
In [6]:
def flatten(xss):
return (x for xs in xss for x in xs)
In [7]:
with open('data/Ulysses.txt') as f:
word_list = list(flatten(line.split() for line in f))
In [8]:
sys.getsizeof(word_list)
Out[8]:
In [9]:
target = 'WARRANTIES'
In [10]:
%timeit -r1 -n1 word_list.index(target)
In [11]:
word_list.sort()
In [12]:
import bisect
%timeit -r1 -n1 bisect.bisect(word_list, target)
In [13]:
word_set = set(word_list)
In [14]:
sys.getsizeof(word_set)
Out[14]:
In [15]:
%timeit -r1 -n1 target in word_set
! pip install hat_trie
In [16]:
%load_ext memory_profiler
In [17]:
from hat_trie import Trie
In [18]:
%memit word_trie = Trie(word_list)
In [19]:
%timeit -r1 -n1 target in word_trie
A sketch
is a probabilistic algorithm or data structure that approximates some statistic of interest, typically using very little memory and processing time. Often they are applied to streaming data, and so must be able to incrementally process data. Many data sketches make use of hash functions to distribute data into buckets uniformly. Typically, data sketches have the following desirable properties
Some statistics that sketches have been used to estimate include
Packages for data sketches in Python are relatively immmature, and if you are interested, you could make a large contribution by creating a comprehensive open source library of data sketches in Python.
The Morris counter is used as a simple illustration of a probabilistic data structure, with the standard trade-off of using less memory in return for less accuracy. The algorithm is extremely simple - keep a counter $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 uniform random variate to $1/2^c$.
In [20]:
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 [21]:
mc = MorrisCounter()
In [22]:
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))
In [23]:
mcs = [MorrisCounter() for i in range(10)]
In [24]:
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))
The Morris counter is less useful because the degree of memory saved as compared to counting the number of elements 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 known as Distinct Value Sketches can do this with a tiny and fixed memory size.
Examples where counting distinct values is useful:
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.
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 [25]:
def string_hash(word, n):
return sum(ord(char) for char in word) % n
In [26]:
sentence = "The quick brown fox jumps over the lazy dog."
for word in sentence.split():
print(word, string_hash(word, 10))
In [27]:
help(hash)
In [28]:
for word in sentence.split():
print('{:<10s} {:24}'.format(word, hash(word)))
In [29]:
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 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 [30]:
for i in range(1, 15):
k = 2**i
hashes = [''.join(map(str, np.random.randint(0,2,32))) for i in range(k)]
print('%6d\t%s' % (k, min(hashes)))
pip install hyperloglog
In [31]:
from hyperloglog import HyperLogLog
In [32]:
hll = HyperLogLog(0.01) # accept 1% counting error
In [1]:
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), len(h1), 0 if i==0 else abs(len(s) - len(h1))/i))
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:
pip install git+https://github.com/jaybaird/python-bloomfilter.git
In [34]:
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 [35]:
for word in word_set:
sbf.add(word)
In [36]:
test_words = ['banana', 'artist', 'Dublin', 'masochist', 'Obama']
In [37]:
for word in test_words:
print(word, word in sbf)
In [38]:
### Chedck
for word in test_words:
print(word, word in word_set)
In [39]:
%load_ext version_information
In [40]:
%version_information pybloom, hyperloglog, hat_trie
Out[40]:
In [ ]: