Lecture 1: Introduction
Big Data Challenges
Quote from https://hbr.org/2012/10/data-scientist-the-sexiest-job-of-the-21st-century:
If your organization stores multiple petabytes of data, if the information most critical to your business resides in forms other than rows and columns of numbers, or if answering your biggest question would involve a “mashup” of several analytical efforts, you’ve got a big data opportunity
In general:
- Capturing data
- Aligning data from different sources
- Transforming data into a form that is suitable for analysis
- Modeling data through a form of simulation
- Understanding output (visualizing and sharing)
So knowledge of quite various fields is required, and when the talent is there, managers and analysts need to use big data insights.
What is Big Data (The 3 Vs)
- Volume
- Scope beyond the ability of typical database software tools to capture, store and manage and analyze the data. (McKinsey, "Big Data: The next frontier for innovation, competition and productivity, "2011).
- Velocity
- "Big data is the data that you aren’t able to process and use quickly enough with the technology you have now" - Buck Woody, http://www.simple-talk.com/sql/database-administration/big-data-is-just-a-fad/
- Variety
- Data has various forms, both structured and unstructured
Why Big Data?
- Analyse and differentiate to the level of the individual
- What is meant here exactly?
- Less likely to miss rare events, e.g. one out of ten million.
- Account for the real-time nature of data
What is Big?
- 20 TB? Clueweb 2009
- 80-120-150 TB? Recent web crawls: IA, CommonCrawl 2009-2016, Clueweb 2012.
- 10 PB? Complete internet archive
Google processes 20 PB per day (2008). JPMorganChase has 150PB on 50k+ servers. Facebook has about 36PB of user data (2010).
In 2012, Facebook:
- 2.5 billion content items shares per day
- 2.7 billion likes per day
- 300 million photos uploaded per day
- 100+ PB of disk space in one of FB largest Hadoop clusters (HDFS).
- 105 TB of data scanned via Hive (Facebook's Query Language) every 30 min.
- Very fast disk can scan up to 300MB/s
- One a single disk, this would then imply 6000 minutes
- In order to do it in 30m, you need minimally 200 disks in parallel
- 2010 estimate: Facebook uses 60K servers
- 70.000 queries on these databases per day
- 500+ TB of new data inserted every day
Lecture 2
Emerging Big Data solutions are:
- Distributed
- Shared-nothing
- Components/resources are not logically shared between processes.
- Data parallel
- Same task is performed on different pieces of data
- Why is that important?
Shared-nothing
Set of independent (virtual) machines with their own local disk and memory. They are connected on a high-speed network.
Trade-off: Large number of low-end servers vs. small number of high-end ones.
Performance estimations
1) Bandwidth: Processing speed; amount of processing/second. (throughput?) 2) Latency between action/request and response.
A high bandwidth does not imply low latency!
Modern hardware takes this into account, tries to improve bandwidth despite latency: If you start to read something from disk, it will tell adjacent cells to also start sipping things, even if you don't know you need the data. Transferring data from disk is slow, so data is already shipped in advance. Predictive computing: predict data most likely needed.
As a programmer, you can help the hardware do better.
Difference in reading from local server vs. diference in cluster: 20 GB/s vs 10MB/s. This is due to the distance the data needs to travel; the hardware is the same. So this slowdown is caused by latency.
E.g. LinkedList is a really bad data structure. Speed of programs is heavily affected by how memory is used. E.g relies heavily on cache vs. main memory.
See interview with Jeff Dean.
Seeks vs Scans
Updating is very expensive compared to writing a new database. With updates you get random access; you have to process/move individuals files in memory from different places: LATENCY. (I guess?) HDFS indeed never updates. They write a new file; file as such are immutable.
Main lesson: do not ship data to the application, ship the application logic to the data! Moving data around is a million times slower. Let applications in parallel work on the data to get the required result.
Gray's Laws
1) Scientific computing is becoming increasingly data intensive * Gray himself switched to helping astronomers deal with increasingly large amounts of data. 2) See slides for other laws.
Parallel programming complications
Concurrency is difficult at datacenter scale:
- How to deal with hardware failure?
- In terms of multiple interacting services
One-off solutions are not maintainable and depend too much on the programmer. Too expensive.
Prototype Big Data Analysis task
- Iterate over large number of records
- Map step:Extract something of interest from each one
- Agregate intermediate results; requires shuffling and sorting of intermediate results
- Reduce step: Generate output
Hadoop
Master program brings program to the nodes, called workers.
Workers read from data, do processing..
They write out intermediate results (results of "map step"). Writing to disk is slow, but this is to ensure failure tolerance, not having to restart the whole job.
Reduce workers collect what they need to produce the final results.
Every computer can access every bit of data. This is why you need a distributed file system.
NFS
When logging in, your data is not stored locally. All your data is transferred from the server to the local computer and vice versa.
This is not good for big data.
- Filesize limited to single machine's capacity.
- Implicit copying of data to local network over network.
- Single oint of failure
- No load balancing
Alternative: DFS
GFS: original proposed name, Google file system.
See slides. Did not feel well.
Q: Why does HDFS prefer big files? See paper.
3 chunk replications implies that you can only use 1/3 of your netspace of your data.
The block should be large, otherwise you are wasting the latency.
Single master is still not fault tolerant.
HDFS
See picture from slides.
Why are there arrows from Application/HDFS cleitn to HDFS datanodes.
If all communication has to go through the HDFS namenode, this would need huge bandwidth. So it is better to use the namenode only for coordinating, and then let the client itself communicate with the data nodes.
Paper highlights
DataNodes do not use data protection mechanisms such as RAID, but used replication. But RAID is within machine replication; still has to wait for a new data node to get online?
Why use large blocks?
Namenode: responsibility with updates.
Page 2: decentraliez all data processing to the data nodes. This is possible because HDFS provides API that exposes the location of blocks.(p.3) Code goes to the data.
Lecture 3: Continuation on HDFS: MapReduce
Take-away from last week's MapReduce paradigm: code goes to the data (data locality).
Take a classical data structure such as the binary search tree. A pointer access is a form of random access.
Q What is random access?
If the end points are on disk, then any lookup through pointers is a random access. The memory pointer will probably not point to a cell that is already in cache.
Solution: store bigger chunks. In data science: a B-tree instead of binary tree (?). Apparently something I should have learned at databases. See picture in the slide: I get e.g. 10 MB for free?
Mapreduce
Two primitives: map(), reduce().
Example: Word Counter.
E.g. map: detect word. Takes key-value pair (docid, document).
E.g. reduce: count word occurrences. Get key and all values corresponding to that key, as emitting by the mapper. So the value types of the reducer input must equal the output value type of the mapper.
N.B. you want a distribution of word counts, not the count of a single word.
The mapper runs in the location of the data; the data does not go into the mapper (remember data locality).
Aggregation is done by the reducer, but some is pushed into the "shuffle and sort" value between mapper and reducer; that the MapReduce framework takes care of.
Note the double occurrence of 'c'. The mapper doesn't know about the data.
Ideally, every reducer gets one key. This is not guaranteed. An unequal distribution of values over keys to the reducer leads to imbalanced program execution; stays a problem. Missed the example. The values are skewed. I.e. one key has 10k values, whereas another key has one value.
Unfortunately, the reducers can't run where the data is. So data needs to be transmitted after the shuffle and sort phase.
As expensive as the amount of data that goes into the shuffle and sort phase: this data will move between clusters. So cost estimation: output that mappers emit.
So whatever processing you can already do before (e.g. sum up the counts), the less data needs to be moved. This process is basically done by the 1) Partitioner and 2) Combiner. Here we focus on the combiner.
Combiners
Combiners are mini-reducers that run on the mapper location. Goal is to reduce the total communication; data that goes in the shuffle phase.
What is the key for the mapper depends on you: you program it, and have to choose the keys smartly.
Do not have to know the internals of "Shuffle and sort".
The MapReduce framework might not run the combiner if the framework decides it's not useful. So the imperative for you is to write the reducer such that is actually applies to your data and can be used as a combiner.
Word count version 1 saves memory due to pre-aggregration. Downside: you use more main memory and it might not fit the data. You need to to main memory management.
Version 2: Initialize hash, and then aggregate across all documents. But the memory issue here is worse. The spilling by the framework here does not apply, you would have to take care of the spilling yourself. In principle this means you are writing your combiner wrong; if you have to do much memory management, you are probably using the framework in the wrong way.
This is called In-mapper combining: If you do this pre-aggregration step in the mapper already, you don't need the combiner. You might still need a combiner in a later phase, just before the reducer runs.
Why is this faster? The combiner writes spills to disk and thus reads from disk, whereas the mapper can do this combining in memory. So if you can do early-aggregation (if your memory allows it), that is faster.
Heap's Law: relation of unique vocabulary vs. corpus size.
Implication: this is why intermediate associative arrays may be useful. If they would be linear in their input, they would be infeasible.
Controlling Execution
Your only influence is the writting of the mapper and reducer. But there are some tricks (they also apply for Spark! More detail later.):
1) Good data structures 2) Sort order of intermediate keys for better processing (example next week) 3) Partition the key space * Which reducer processes which key? 4) Preserving state in mappers and reducers * Can be tricky! * Captures dependencies across multiple keys and values
MapReduce API, some notes
Keys need to be comparable, and therefore are part of the WriteableComparable.
Code example: private final static intWritable ONE - new IntWritable(1);.
This avoids creating more objects, doing it only once.
Java objects are expensive because they have a lot of pointers; they are bad for latency.
Block splitting into blocks of 128Mb might cause for example a single sentence to be in two blocks. This would be annoying for mappers trying do do operations on sentences. Therefore you instead deal with input splits.
Tricks for getting data to mappers and reducers
1) Configuration parameter * Config files sends configuration values to mappers 2) "Side data" Run distributed cache or read from HDFS in setup method. * Runs alongside map reduce jobs; not fault tolerant but that's okayish. * If configuration files become too big
Complex data types in Hadoop
For proper data types, you need to implement a lot of methods/interfaces.
Quick and dirty: write your own text objects and define a method to parse them. (Ok in this course, but not in a job setting!)
Lecture 4: MapReduce continuation
Example: Mean Computing
Mapper: identity mapping.
Reducer: important that it gets all values associated with a single pair.
Imagine having two reducers: then you will not find the right mean based on averaging two means on subsets.
Intermezzo: About shuffle and sort:
- Distributed sorting + fault tolerance
- Makes sure all values of the same key are aggregated and moved to the right location/reducer.
- Most expensive part of MapReduce.
Computer mean version 2: input to combiner cannot be the same as input to mapper.
Version 3: Mapper now keeps count and has different input. Allows use of combiner. But still: we cannot guarantee the combiner is run in the first place.
Version 4: In-mapper combiner. Memory issues. Fault tolerance does not help here (fault tolerance of the framework is for hardware problems. Bad software will fail on whatever node.)
Question for version 4: Is a combiner still needed after the in-mapper combining? In principle: no.
Secondary sorting (i.e. on value)
Web server, e.g. do something with logs per user. Key=site of server. Value=user logs.
You get all website access in the same reducer. But if you want to do something per user, you need to group logs per website (primary sorting on key), per user (secondary sorting on value).
Solutions
1) Buffer values in memory, then sort. BAD. 2) Value to key conversion: include value into new key. E.g. key is google+edwin. * This way MapReduce framework can do the sorting * But reducer will not get data per website anymore. This is weird!
To solve the problem of 2: Custom partitioner.
Custom Partitioner
What is partitioned? The key values themselves, to split the keys over the reducers. So partition: key -> reducer ID.
If allocation of keys to reducers is not going well, you probably need a custom partioner. Often hashing is used to counteract skewed key-value pairs. After hashing, occurrence frequencies of hashes is better distributed.
In the previous example: with website-user pairs you can tell the partitioner to only take the website into account.
Examples text-mining with MapReduce
Text mining infers meaning based on term co-occurrence matrix.
"Pairs" analysis. Upper bound $n^2$. Combiners reduce this to about n in the text-occurrence example.
Stripes approach
Goal: be able to do more aggregation in the mapper.
Solution: organize pairs in associative arrays, and then reducers can perform row-wise / element-wise sums of associative arrays.
Because you work with pairs, and do more work in the mapper, we ship less data. So clever complex data structure allows more aggregation of partial results.
Disadvantages: 1) Memory consumption, the co-occurrence pairs might explode. In this case we know Heap's Law to estimate complexity.
Comparison Stripes vs Pairs
See slides.
Important: the frequency effect causing load imbalancing only gets worse in this approach!
Relative frequencies
Naively three jobs needed.
1) Co-occurrence 2) Sums for marginal counts 3) Run divisions for relative frequencies
Solution: see slides.
(a,*) needs with special number 'a' to go to the right reducer, and this reducer only keeps a in buffer.
Lecture 5: Guest lecture on Google
Made physical notes.
Lecture 6: Old Big Data Systems and Intro Spark
Hadoop's Deficiencies
Most important sources of latency:
- Cf. the amount of debug lines on terminal when running a job.
- Lot's of start up time for jobs.
- Serialization and parsing of Java objects to e.g. a bytestreams
- Java objects are represented with memory pointers, but these cannot be written to disk directly, so serialization is not trivial.
- A lot of information storage is string based, which requires a lot of parsing
- Checkpointing costs time
- Map reduce boundary: reduce phase waits until all mappers are done
- Multi job dataflow: same for multiple jobs; wait until first job is job.
- No indexes: you are always scanning all the data. (Cf. in a database: read only attribute X)
There are some more in-depth limitations:
- There is no record abstraction
- I think what is meant here is that HDFS works directly on records, whereas Spark creates an input RDD that is a representation of records in-memory.
- This means that queries/operations can be done on this RDD without having to read records all the time
- "HDFS" even leads to "broken" records.
- Hadoop focuses on scale-out with little emphasis on single node performance boost
- Cf. Spark: but how does Spark improve on this? Not immediately clear to me.
- Limited expressive power (cf. point above that you always process all data )
- No functions available such as joins, or graph traversal
- Lack of schema information
- No knowledge about the data is used for optimizing
The problems boil down to: Hadoop was designed for batch processing
Cases against batch processing
- Interactive analysis (" Dashboard approach")
- Issue queries over same data interactively (cf. no indexing, I think?)
- MapReduce requires a whole map phase per query... Huge latency for something that can be done in log(n) with a tree structure!
- Iterative machine learning algorithms
- No batch setup: read same data over and over
- The latency increase here is due to full reading and writing
- Data that can be (re)computed easily from existing data on disk is treated as new data, which is also replicated for fault tolerance.
Main improvement of Spark: intermediate results do not always need to written to disk due to a different approach to fault tolerance.
This requires more data in memory, so batching the data is still needed to some extent.
Spark's use of data sharing
On top of DFS, there is also a representation for data distributed in memory in the cluster.
This distributed intermediate memory representation avoids writing to disk in intermediate results.
Work can be done directly on this data in memory.
Most query plans are 10-100x faster than MapReduce's network and disk.
Challenges
- But what about fault tolerance?
- And efficiency in large commodity clusters
- Many people still use DFS in combination of Spark for additional fault tolerance.
Keep pointer to where you are, so you can recompute only the work that you know was terminated, instead of restarting the whole job. In addition, write to disk once in a while.
Traditional database systems work on values, but not on whole blocks of values. This means that in distributed memory, individual values are distributed, rather than large blocks. If you do then do fine-grained record updates in distributed memory, you need to do:
1) a lot of replication operations on these small amounts of records 2) Update logs in many places for fault tolerance
This approach is not feasible for Big Data.
Spark programming model
Such a block is called an RDD, cached in distributed memory. An RDD keeps track of what it is working on, and on what node what part of the RDD fails.
RDD-API in Scala allows interactive use. Arjen argues this is a huge improvement.
Spark has model of lazy evaluation: transformation operations are separated from action commands that actually get the results. So "get" commands trigger data computations.
E.g. "collect" will collect all data to the driver node. This will probably crash the driver node if you have a lot of data and bring the whole cluster down. So in general: be aware of using that. Use "sample" or "top k"
Lazy evaluation allows for query optimization.
Special node is called "driver" (cf. NameNode).
RDD: Semi-batch model.
Set-oriented operations instead of tuple-oriented ops. Cf. SQL databases: "As you may know, SQL data manipulation commands are set-oriented which are involved in operating over entire sets of rows and columns in tables at once." This allows operations, such as a union set operation, on the whole set, rather than processing individual key value tuples.
Also: Spark has nested relational model, so that per key you have only a few values instead of making multiple flat tables and denormalizing. Denormalizing is a way to express a complex relation in different flat tables, in order to improve read performance. In a nested relational database, this relation can be expressed directly in by nesting tables hierarchically.
Because of this nested structure, "flattening" operations are available in Spark.
E.g. map vs flatMap. For a given text...
- Map: count number of sentences
- FlatMap: count length of each sentence, i.e. first flatten text into set of sentences and than count words rather than sentences.
RDD properties
Driver knows lineage of what it sends out to be computed: basis for fault tolerance.
What does an RDD representation contain?
- Abstraction of set of partitions, on different machines
- With preferred locations for each partition
- List of parent RDDs for fault tolerance (DAG LINEAGE)
- Function to compute a partition given parents, because RDD is a filter on data from parents.
- Related to lazy evaluation
- Optimization: e.g. four transformations can be done at once at the partition where the parent data is; intermediate results can immediately be reused from cache.
Additional RDD features:
- Control over partitioning
- Imagine counting words. Why would repartitioning results be smart?
- Imagine filtering on a rare words,this will result in many partitions with a single word
- So now we have different nodes doing the same thing on very small sets. More efficient to collect them in one partition for efficiency.
- So re-partition if most your partitions are empty, at the cost of some network cost, but with benefit of more efficiency of subsequent operations.
- Control over persistence
- Indicate which RDDs are important to cache and keep in memory
- Write to disk once in a while; property also stored and kept track of at RDD level.
- Fine-grained reads by treating RDD as a big table
- See later lectures on Spark-SQL querying.
Key points
- Avoid materialization of intermediate results
- Recomputation instead of replication for fault tolerance
- Good and user-friendly API.
Example Interactive Querying: Log mining
Main point: keep smaller filtered data in memory, so that from there on we can interactively query it without reading to disk.
For 1 TB, improvement from 170sec to 5-7 sec.
- transform chain of RDDs into all lines with ERROR. Lazy evaluation: nothing done yet!
messages.cache(): keep it in memory if possible, do not swap this out (first). You just tell you need this in memory with some priority.
This commands replaces the MapReduce equivalent of writing to disk. If after our first job, we now do another query, this data does not need to be read from disk.
Example Iterative Processing: logistic regression
Main point: gradient learning step in the regression is done in-memory at the same location, without writing intermediate results.
p is a named variable for each element of the set of interest: but the map operation "under the hood" is done over the whole set.
Lecture 7: Spark continued, Advanced Spark
Components
Spark client (app master)
- RDD graph.
- No execution yet; preserves lineage.
- Scheduler and block- and shuffle tracker: keep track of progress, but as a programmer you do not deal with this directly.
Spark worker
RDD location: Partition of RDD will be put on the place of the data block in HDFS, to avoid shipping data. Or at HBase: relational database system on clusters; reads records instead of files; alternative to HDFS.
Cf. Assignment: why did we have two files part 1, Part 0: Working on two partitions.
Materialize results where the work is done. Only at collect all data is shipped to the driver node. Input data in the partitions stays there (after a transformation).
When reading from hdfs, Spark communicates what partition of the RDD will be at what datablock. A "HadoopRDD". Task threads, block manager.
RDD Graph, Partitions, Jobs.
How many partitions? Filesize / 128Mb or 64Mb.
Any transformation creates the same amount of new partitions of a new RDD, where each partition is a transformation on the parent partition (unless you explicitly repartition of course). Each transformation is a task.
Example slide: 4 tasks belonging to one job.
Executing a transformation command is building a DAG for the specified operations.
Data locality
1st RDD is loaded in memory cache directly from disk. This step uses the locality preferences from HDFS. I.e. the RDD puts partitions following where HDFS put data blocks.
2nd transformation is done on the location in memory.
If a transformation fails and falls out of cache, the partition falls back on the hdfs location.
Scheduling
- We have RDD objects
- When an operation is defined on RDD objects, the scheduler builds a DAG of this operation.
- E.g. when you define a join on two RDDs, the DAG will have three RDDs, where the third depends on the former two.
- The DAGScheduler takes DAGs as input, and splits them up in stages of tasks.
- A task per partition, outputs a task set.
- Stage borders defined by wide dependencies or input.
- TaskScheduler launches tasks via the cluster manager, and makes sure failed or straggling tasks are retried.
- Worker: task execution; storing and serving blocks; interface between client and HDFS.
Join: if you have no extra info on where to look for particular keys, you need to look at all partitions, leading to a wide dependency. Selection of cartesian product.
You cannot infer what blocks you need to look at for the relevant join key. Wide dependency: you need to look at all partitions, because you don't know what partition depends on which one. Same as shuffle phase in MapReduce; blocking operator.
For middle stage: you sort of have to guess how many partitions we end up with.
Narrow dependency: The last phase: you know the dependencies between partitions, because you are just doing a simple filter. No data needs to be shipped, can be done in place on location of the partition.
The narrow and wide dependencies
Wide dependencies avoid grouping things together, and are the main source of cost as this requires moving data around over the network.
DAG is agnostic of operators because of extensibility: for ease of making new operators, as there is no dependencies except for input dependencies. The framework doesn't care, which is good.
RDD API example
If unspecified, input files are split on lines at the time. So we manually tokenize further.
.map.filter creates two RDDs (I think, double check). (We just only save the last RDD under a value, which allows us for example to cache it, or call some operator on it )
If you map onto a tuple, you get a paired RDD that has key value pairs
Physical Execution model
The DAG is a declarative logical level that tells what needs to be done.
- Jobs: complete work to be done
- Stages are bundles of work that can be done together. E.g. map and filter. Again, stages are determined by the framework based on knowledge of dependencies
- Tasks: units of work, correspond to one RDD partition
- Yeah, when we truncate four sequential tasks, we again end up with one task per partition.
Q: What is the exact difference between Jobs and Tasks?
To the DAG on the physical level: physical optimizations:
- Pipeline narrow transformations into a Stage, execute them together. (Not truncation! You perhaps want to keep old RDDs in memory, e.g. "words" from the example)
- Truncate DAG by using cached intermediate RDDs.
- So truncation cannot be done on the first run!
- All sequential transformations in one stage will be truncated into one tasks.
- So the amount of tasks still depends on the amount of partitions of each RDD, but not the total amount of partitions of all RDDs.
What is the exact difference between pipelining and truncating? Is it just a terminology difference?
A:
1) Pipelining refers to making different sequential steps into a single task. 2) Truncating perhaps is just that on re-runs not the whole DAG needs to be followed. Instead, because intermediate results are cached,
So to clarify the difference, can you pipeline something without truncating the DAG? Yes: on the first run, sequential jobs can be pipelined into a single task, but this does not yet truncate the DAG. The latter is done when the results are re-computed.
Wide dependencies (i.e. "shuffles" )determine stage boundaries, because there no pipelining or truncating is possible.
Black blocks are cached.
Scheduler optimization
See slide 18: Why are there from B to G linear connections? Answer: GroupBy semantics: all keys end up in the same partition, so when you access a key you know all keys are in that partition.
This allows the scheduler to pick a join algorithm that can minimize shuffling and even turn e.g. a join into a narrow dependency.
DEBUG INTERFACE SPARK: localhost:4040 or 4041, contains STAGE GRAPH over time.
Spark SQL and the DataFrames API
Introduced in Spark 2. Useful when data has a bit more structure than text.
Avoid all the overhead of pointers to Java objects by creating Spark DataFrames.
DataFrames hold rows with a known schema.
A DataFrame is a data abstraction or a domain-specific language (DSL) for working with structured and semi-structured data, i.e. datasets with a schema. A DataFrame is a collection of rows with a schema that is a result of a structured query it describes. It uses the immutable, in-memory, resilient, distributed and parallel capabilities of RDD, and applies a structure called schema to the data. Key difference between DataFrames and RDDs are, when working with DataFrames you have much more information about the structure of the data. Information such as names of the column, the data types, etc are already known, which enables a whole bunch of optimization which won’t be possible in RDD.
Source: https://medium.com/@thejasbabu/spark-dataframes-10c349de04c
Based on this data schema, DataFrames offer relational operations through a domain-specific language. In other words, DataFrame offer a unified interface, irregardless of the underlying language used.
DataFrames use relational algebra rather than sequential calculus (difference is a bit unclear to me). This means that (I think), as opposed to sequential calculus, variable pointers are not used, but operations are done on whole sets. The absence of use of pointers also makes that they cannot be used in a language. However, SparkSQL optimizes SQL queries.
DataFrames can thus be created from different contexts, e.g. HDFS or Hive. DataFrames can be used in combination with Spark SQL for easier manipulation.
c = HiveContext()
users = c.sql("select * from users")
ma_users = users[users.state == "MA"]
ma_users.count()
Query optimization
users.state == "MA" is an expression AST (Abstract Syntax Tree).
In other words, the SQL expression using relational algebra, is syntactic sugar for how this query is represented under the hood by SparkSQL.
After optimization, ASTs can be rewritten into JVM code! So whether you are working in Python, Java, Scala... SparkSQL can produce optimized JVM code and sometimes even run it in parallel.
Explained by http://gousios.org/courses/bigdata/spark-datasets.html
Why is SparkSQL so fast? Because it uses optimisation and code generation.
The key to both features is that code passed to higher order functions (e.g. the predicate to filter) is syntactic sugar to generate expression trees.
df.filter(df("team_size") > (3 + 1))
is converted to
df.filter(GreaterThan(
UnresolvedAttribute("team_size"),
Add(Literal(3) + Literal(1))))
This corresponds to an Abstract Syntax Tree.
These trees can again be optimized and simplified, resulting in a very compact query. Moreover, further optimization can be done by running queries in parallel.
This was the result of Catalyst rewriting the SQL query: instead of 1 complex query, SparkSQL run 24 parallel ones using range conditions to restrict the examined data volumes. MySQL cannot do this!
Catalog
Catalog manages types of all relational entities, which are used in the optimization process.
From https://jaceklaskowski.gitbooks.io/mastering-spark-sql/spark-sql-Catalog.html:
"Catalog is the interface for managing a metastore (aka metadata catalog) of relational entities (e.g. database(s), tables, functions, table columns and temporary views)."
Why use DataFrame API?
1) Compact binary representation * Columnar * Compressed cache * Rows for processing * See Spark efficiency lecture 2) Optimization across operators (join reordering, predicate pushdown) 3) Runtime code generation
The DataFrame API allows you to make better programs on RDDs (but of course the output is still the same).
Using DataFrames gives you less flexibility:
- You cannot define your own types
- No dealing with RDD pointers (my own interpretation?)
No difference between Scala and Python if we restrict ourself to DataFrame API, due to 1) delayed execution, 2) query optimization into the same program.
Understand 3.1b well, 3.2 on a higher level.
Q: How does delayed execution allow query optimization?
See the slides on Spark efficiency for: query pushdown into data sources using rich semantics (schema information)
Lecture 8: Guest lecture by BigData Republic: Recommenders in Spark
Objectives
Recommendation can be done on different granularities.
- Populations
- Specific groups
- Individuals
What is a rating?
- Explicit ratings
- Preferences
- Relevance
What are we modeling?
- Click-throughs?
- Purchases
- Conversion probability
Algorithm types
Non-personalized
- E.g. shopping cart trending products over all users
- Which product is most popular, or trending?
- homogeneneous over users
Semi-personalized
- Creating subgroups within which you do non-personalized analysis
- The personalisation is on some shared feature (e.g. male vs female), not that data driven yet
Applications:
- Help setup business rules
- Association rule mining for products
Content-based filtering
- Analysize content attributes and select closest object
- Privacy: only for one user
- But therefore also not very diverse
- E.g. peanut butter + duo penotti --> recommend Nutella
Collaborative filtering (person-based or item-based
- Idem but take other persons in account
- Find relatively close user, and recommend what that other user usually buys
- Does not require in depth analysis of content (cf. content-based filtering)
- Easier and more diverse
- Same idea can be done ITEM-BASED: take a broccoli, who can I sell it to?
- I if I share products with a lot of people that also buy broccoli, I might be a good client to buy a brocolli
Requires:
1) Record user-item interactions 2) User-item preferences (sparse matrix) 3) Model predicted preferences (fill in sparse matrix) 4) Item rankings
Recommender theory
1. Content-based filtering
Main problem:
1) getting good content attributes. 2) Mapping items in item space based on these attributes 3) Calculate closeness between items based on cosine similarity
Cosine similarity is appropriate because it ignores zero entries
Pros:
- Works with small user base
- Finds similar items
CONS:
- Cold start: depends on an user profile
- Depends on content attributes
- Big problem... in practice often not present in company datasets
- Low diversity and serendipity
- Because recommendations are based on your own user profile you are not likely to discover new but interesting items (serendipity; diversity)
2 Collaborative filtering
We zoom in on user-to-user collaborative filtering.
Calculate predicted rating of item i by user u S(u,i).
How?
1) Sum over the ratings that all users v gave to item i minus the average rating for item i 2) weigh this rating with how similar user v and u are. 3) Normalize over the similarity of all users with user v. 4) Add the average ratings given by user u
W.r.t. 4: Introducing add average rating per user for normalizing: e.g. student and family might buy same products but in different quantities. (Note that "rating" here is potentially implicit: the quantity of buying this product)
So normalize, because rating is here implicit i.e. defined by the number of times a user buys a product.
REVIEW
Matrix factorization
Simultaneously learn user and item profiles
- Calculate with matrix factorization.
- Handles sparse data very well.
- Efficiency: Scalable and distributed computation
1) Transform transaction data in users-item matrix (Sparse!) 2) Filter, normalize, transform into binary preferences (1 if rating(u,i) > 0) 3) Express confidence of rating 4) Matrix vectorization into * user profile: user x latent factors * item profiles latent factors x items 5) Apply alternating least squares
CONS:
- Cold start problem
- Context not taken into account
- What is meant with this?
Q: Are there recommender systems that do not suffer cold start problems?
Alternating least squares
1) Fill user profiles and item profiles randomly 2) Fix one, optimize the other. Then alternate. 3) Until convergence: matrix with predicted preferences
Try to approximate the recorded preferences taking into account the confidence we had in them.
Learn based on difference between recorded preference and predicted preferences (which is transposed user profile matrix with item profiles matrix)
See slides for specific ALS formula.
Preferences for
Lecture 9: Efficiency in Spark
Dataframes and efficiency
Possible cecause of schema information.
1) Compact binary representation
N.B. I think this is a quite specific topic, I might want to dive deeper into this if I have time left
- If you tell Spark what the schema of a complex object is, it will not create Java objects
- Columnar: will make columns with fields
- Works on regular data; e.g. not really on parsed web data, because they all have very different parse graphs.
E.g. take a table with: Person1 | country | city
If we now filter on city, we only use the third column, but in the RDD approach we still scan everything.
You could instead also make a different table person.country.city, where you only store the cities per rowId, where rowId points back to the entry in the first table. Now if you also represent city names as numbers, the representation is even more compact. You can represent the whole column very compact as an array of numbers, where the index corresponds to rowId, so even the rowId can be dropped. This is a very compact representation.
But a requirement to do this is that the data is similarly structured.
This is for example done by MonettiMe: SQL database that is 10-100x faster.
Updates on small objects where all info is spread over many columns/arrays, instead of being a row in a big table. So it's hard to make it work well for transactional updating, like in banking.
When is a column-oriented representation more efficient? From https://en.wikipedia.org/wiki/Column-oriented_DBMS
Whether or not a column-oriented system will be more efficient in operation depends heavily on the workload being automated. Operations that retrieve all the data for a given object (the entire row) are slower. A row-based system can retrieve the row in a single disk read, whereas numerous disk operations to collect data from multiple columns are required from a columnar database. However, these whole-row operations are generally rare. In the majority of cases, only a limited subset of data is retrieved. In a rolodex application, for instance, collecting the first and last names from many rows to build a list of contacts is far more common than reading all data for any single address. This is even more true for writing data into the database, especially if the data tends to be "sparse" with many optional columns. For this reason, column stores have demonstrated excellent real-world performance in spite of many theoretical disadvantages.
Example of a row based Person | country | city | layout:
row0: [ Edwin, Nederland, Nijmegen ] row1: [ Michael Jackson, USA, Neverland ]
In this layout it is very efficient to find all data corresponding to one row (one person). However, if for example we are interested in all persons living in Nijmegen, this representation requires an ineffective lookup because we have to go through all rows, and then scan all data to check for the city Nijmegen.
If instead we have the columnar representation then the datatype itself is the index:
Person: [ Edwin, Michael ] Country: [Nederland, USA] City: [Nijmegen, Neverland]
So if we want to know all persons living in Nijmegen, we can do that efficiently. We look up the column "City". We avoid having to search the entries of "Person" and "Country". We find Nijmegen at index 0. This is enough information to retrieve all data from that person, just by reading row 0 of the row-based column. If we are only interested in the name of the person, we can of course still use the "Person" column in the same way.
Advantages:
- By having columnar representations you can do certain type of queries more efficiently.
- Notice how the column based approach uses the data schema (not from slides, my own 2 cents)
- Compression rate goes up when e.g. city names are grouped together, due to more of the same cities being in the same window.
SMV: Query processing goes from row based in a big table to column based
2) Optimization across operators
Predicate pushdown: first do selection before join. ("down" assumes you draw the query graph upside down... which is weird)
Spark dataFrame API knows about Schema's and can figure out automatically when such predicate pushdown is needed. (Again, this "pushdown" pushes an operation to the front in the query plan)
This is better in case e.g. you want to know about restaurant visits of people from some city. Imagine you have a table with people and the city they live in, and another one with people and the restaurants they visited.
If you join these tables, you have a very big table with all restaurant visits from all restaurant-visiting people from all cities. Then filtering out all people from a particular city requires a lot of work.
If you instead first select on people from that small town, you have a very little table to join and the answers in the resulting table.
3) Runtime code generation
If optimization doesn't work well, Spark can write a program for a relatively efficient query. (Can, or can't?)
Scheduling
Idea is to be agnostic about the operators.
With dataframes this is harder, although self-defined dataframe functions are optimized, but especially hard with udfs (hdfs?).
Reminder: the five RDD components
1) Paritions 2) Dependencies (wide, narrow?) 3) Function for computing the partition (E.g. filter application on parent) 4) preferredLocation 5) partitioner
Example RDDs
Hash-join on parallel frameworks is common.
E.g. a "JoinedRDD" has a HashPartitioner.
A join B. Make hashtable of both.
Then you can let a partitioner use those hash values to assign the results to a partition, so you keep the hash tables.
Two problems:
1) Hash function might return same value for two records: a collision. So you still need to check values in that case. So you want to avoid collisions, with some scheme. 2) I missed some insight here about distribution of data / preference of hashes. * Maybe the point could have been that the partitioner might assign data in a skewed manner, so that after a join some partitions are almost empty.
Dependencies
W.r.t. blog post: E.g. map lower case --> changes the data, so the hash table is not usable anymore. BECAUSE OF THIS THE PARTITIONER is gone.
What is co-partitioning
- We know how the input tables are organized
- E.g. visitor id's
- In both tables both partition are organized from 0-9, 10-19. i.e. a range partitioning
- So for a join I only need to look at 0-9 from both tables, 10-19 from both tables, etc.
- So you order the data on the attribute you join on
- The resulting join table will keep the ordering ( REVIEW THIS )
- Fileformat Parquet to keep ordering when writing to Hadoop, to not lose the ordering.
- Columnar representation
One problem with Parquet is that you can't append rows. Adding "a row" means that at the end of each column you would have to append a single datapoint corresponding to only one feature of the row.
Narrow dependency: only one child depends on the current parent (but a child might depend on more than one parent!)
Wide dependency: multiple child RDDs depend on a single parent, across the board. If a child RDD is then lost, we need to look at all other RDDs to recompute this RDD.
Event Flow
DAG scheduler contains intelligence about data and how to minimize traffic etc, using pipelining, RDD partitioning, stages etc.
DAGScheduler submits tasks to TaskScheduler which creates task objects, that are placed on the cluster or the local runner/node.
Improving Efficiency in Spark
- Avoid shuffling.
- But if you cannot avoid them, do them early. Look at the co-partitioning example.
- Filter input early
- Risk: losing data, e.g. when language detection is faulty and you filter on Dutch
- Avoid groupByKey on Pair RDDs, because it's a full shuffle
- Look at aggregateByKey instead.
- Basically amounts to Combiner pattern from MapReduce (I assume he means in-mapper combining)
- Way more efficient because values are combined per key before shipping the data to other RDDs.
- Needs to have a partitioner assigned to know the partitioning of keys, in order to avoid wide dependencies!
Control the degree of parallellism
- Repartition
- Concentrate
- Makes sense to do when you have a lot of (almost) empty partitions
- But very expensive!
- Can increase and decrease
- Coalesce:
- Reduce number of tasks
- But more efficient: avoids data movement.
When does repartitioning make sense?
Compare RDD before and after filter. E.g. filter web on ru.nl. Then most output partitions are empty, because there's relatively little webpages. Then consequent operations are unnecessarily complex because they have to take all these extra (empty) partitions into account.
Repartition is expensive but makes sense if you are planning on doing further analysis, not when you are close to your result.
Broadcasting
If you want to perform a join with a small left hand or right hand side, you can consider broadcasting the small table to all nodes.
E.g. have a table of cities ready at every node.
Instead of shuffling all value combinations of interest over the network, you can also ship the small table to other RDDs partitions once, and then join locally. This "local" operation is a narrow dependency.
Version without broadcast: sends the info from name node to workers on each run. Broadcast skips this by recognizing that this info needs to be globally available, and kept that way. So do not re-send on re-runs.
Immutable. Access with .value()
Maintaining partitioning
Use mapValues if you want to keep the partitioning, because the keys do not change!
Otherwise the framework will use cartesian products in reduceByKey or joins etc.
pages.join(visits).map(...).reduceByKey(...)
reduceByKey does a full shuffle!
pages.join(visits).mapValues(...).reduceByKey(...)
here reduceByKey has a narrow dependency, 1 on 1. Same keys are on the same partitioning after the shuffle of "join". Aggregrated values per key therefore also end up on one partition without shuffle.
Use available Spark libraries
Spark SQL, Spark Streaming, MLlib, GraphX.
All work with the RDD abstraction, with domain specific optimalizations.
Spark.ML works on DataFrames and is recommended.
Mores slides with more information, but not essential imo.
Lecture 10: Applying Big Data in Streaming
REVIEW MICRO-BATCHING and ACCUMULATE & RETRACT
Certified Cloud Engineer --> what does that mean?
See notes about Google Dataflow paper.
The biggest problem with streaming is:
- You don't know when data arrives. This is a problem for usual batch processing because they assume bound data. That forces you to wait until all data is in before you start the batch.
Why dataflow? Other streaming systems lack one or more of the following:
- Guarantees that each data point is processed once
- Proper windowing
- Triggering mechanisms for windows
- Flexibility for processing engine: Batch, micro-batch, streaming
- Engine choice is a matter of a latency and cost tradeoff
- Streaming is lower latency, but higher cost
- Accumulate and retract most costly, but most desirably properties
Separated logic of data processing from underlying physical implementation
Goal is to balance:
- Correctness
- Latency
- Cost
Watermarks: biggest difference between stuff that happened and moment of processing. Biggest?
Data: (key, value, event-time, window-to-be-assigned)
Overlapping windows need to be merged, e.g. if you have a late arrival data point coming in.
If window is determined, timestamp is often thrown away because that info is in the window now. If you want to keep it you have to pack it in the value.
Triggers:
Watermarks:
- too fast: late arrivals not taken into account.
- your trigger is e.g. that after 1 min of processing times all events up to event time x are processed, but this disregards results coming in at 2 min of processing time.
- too slow: if things queue up the whole pipeline is delayed
Middle road: go for low-latency solution and only ensure correctness in the end (eventual correctness).
Then of course the question: what do you want to do?
- Discard if e.g. we only want to monitor
- Applications where we do not care about data of independent moments
- Accumulating: eventual correctness is guaranteed, by improving old date with latecomers. Expensive, of course.
- Accumulating and retracting: don't really get this
- E.g. transfer money while connection is gone, send later when connection is back, make sure that works with possible actions in the offline window.
Example Dataflow
Windows not based on event time, but processing time.
- batch all
- accumulate smaller batches per processing time; event time ignored
- counting trigger for every two events
But we care more about event time less about our pipeline.
Enter streaming approaches: Vertical bars: windows defined on event times
- Batch: to slow w.r.t ideal watermark
- micro-batch example. Latecomer 9 is integrated with the 5 that is on time. 8 operations.
- custom flexible watermark + rule with maximum watermark of e.g. 2 minutes (look at 3 from 12:04-06)
complex groupBy (no linear pipeline), also calculate depending paths.
Retracting avoids having to store states, and still ensure eventual correctness. you need to know where branches depend on each other, then update the result by retract the result that changed and provide a new one.
This scheme is important when you always want to be correct on smaller windows as well, not only over a whole past period.
Remarks:
Micro-batch: on top of event time windows, add a feature trigger that triggers e.g. every minute at processing time to emit intermediate results. Accumulative. Quite efficient, you have some intermediate results (vs batch), and completeness is guaranteed after the batch.
Accumulate and retract is needed when intermediate results are already used and grouped by key and by window.
"Retractions are necessary in pipelines with multiple serial GroupByKeyAndWindow operations, since the multiple results generated by a single window over subsequent trigger fires may end up on separate keys when grouped downstream."
In other words, if you want to be correct on 1) small windows rather than the whole event window, and 2) if (intermediate) results from this small window are used for further grouping (e.g. look only at ads), then retraction is relevant.
Example:
"If we are performing aggregations downstream from session creation that depend on properties of the sessions themselves, for example detecting unpopular ads (such as those which are viewed for less than five seconds in a majority of sessions), initial results may be invalidated as inputs evolve over time, e.g. as a significant number of offline mobile viewers come back online and upload session data.
Spark's implementation
Spark streaming. NOPE, too hard.
Spark Structured Streaming, built on top of Dataflow architecture.
Support idempotence: same streaming input --> same result. Allows re-computation within Spark.
awS3 --> amazon storage.
You can also host your static website there
ETL: Extraction, Transform, Load. "Get your data in the database"
Lecture 10a Streams continued
Streaming applications
- Monitoring
- Network traffic
- Datacenter telemetry
- Sensor networks
- Social media streams
- Credit card fraud detection
- Stock market analysis
- Online mining of click streams
Streaming is hard, in practice you often fall back on clever batch processing.
What is a data stream and main challenges
- Structured (e.g. tuples)
- Ordered (implicitly in event order or timestamped)
- Arriving continuously at high volume
Two main challenges:
1) Sometimes not possible to store all data 2) Sometimes not even possible to inspect all incoming data
There is no de facto best platform for streaming yet.
Stream Processing Challenges
Inherent:
- Latency requirements
- Space bounds
System challenges:
- Bursty behavior / load balancing
- This is the real problem
- This is inherently hard to predict with streaming
- Out-of-order message delivery and non-determinism
- Not inherent but due to system design WHY?
- 1) Messages may arrive out of order and 2) this order cannot be predicted.
- E.g. system reboots does not lose data, but delay it w.r.t other machines
- Consistency semantics (at most once, exactly once, at least once)
Algorithmic solutions
Efficient counting and sampling required.
Sampling
- Throw away irrelevant data
Requirement for nice statistics: each object needs to have the same probability of ending up in a particular sample.
Reservoir sampling
How to do sampling on continuous data?
Take first k elements, after that keep with s/k , which replace an existing item.
REVIEW SLIDES.
Do not collect everything in batch, compute uniform sample as a byproduct of a stream. In other words, keep the stream "up to date" when new data comes in, in such a way that the resulting sample is uniformly sampled from the stream.
Hashing
Other option: Accepting some approximations.
Approximate your data efficiently so that you can keep it in memory.
Translates a unique object to a number. The number corresponds to a memory location.
Collisions are actively used. You don't have enough memory so use hashing to distribute the data in memory using a hash value. Of course, at a particular location, there might already be data: hashing.
Pragmatic viewpoint of max entropy principle.
Main point of hashing here is making sure data is uniformly distributed over memory.
Again, the premise is that you don't have enough memory.
Three examples
1) Cardinality estimation of a set (HashSet: HLL counter) * E.g. how many unique visitors. * Assume its not feasible to keep a total count of all visitors.
2)Set membership (HashSet: Bloom Filter) * Is x a member of set S * Example: Has the webcrawler visited this page before?
3) Frequency estimation (HashMap: CMS) * How many times have we observed x? * Example: how many queries has this user issued?
CMS is a generalization of Bloom Filter.
(Ajren likes Bloom Filter the best... hint for exam?)
See slides
HyperLogLog:
Use a single good hash function to get a binary sequence that is uniformly distributed.
Hash the elements of the set.
Observe the amount of leading zeros.
If e.g. we see 3 leading zeroes in some hash, the chance that this is expected to occur is 1/8. Thus, we expect that the cardinality of the input set to the hash is 8.
Of course, if we conclude this based on a single occurrence this can be luck.
To reduce variance, use the first p digits of the hash to assign hashes to a bucket. So for p=2 we have four buckets. Then for each bucket we check the number with the most amount of leading 0's to calculate our estimate.
For the final estimate we average those estimates.
Quality of distribution of hash depends on distro of input data. You can given the input build an good hash, but this is not handy in practice.
HLL: how deep will the tree be? (which is on a logarithmic scale ) From depth of tree you can infer number of unique items.
Q: It's not quite clear what the role of the tree is.
Bloom filter:
Bit vector should be as large as the memory you can spare, to minimize error rate.
Idem for k: not too little hash functions. Explain based on below.
Contains check based on hashes. So if your application is critical you need to do a more expensive occurrence check, so make sure the check wasnt produced by a collision.
Slide on y: probability that all bits match by chance is very low. But there are never false negatives possible.
Method works best if about half the bit vectors are set to 1. (Not just simply "bigger is better", alone)
Count-Min Sketch
Error properties:
- Reasonable estimation of heavy-hitters
- Heavy hitters: term from the original paper
- Means most frequent terms in a large set
- Frequent over-estimation of tail.
- Think this refers to the tail of a frequency distribution...
So Count-Min Sketch is very good at approximating the frequency of frequent items, but not of infrequent items. This is because Count-Min Sketch never underestimates, but can easily overestimate due to collisions. If a frequency is low, then the amount of counts contributed by collisions can be relatively very large, e.g. 50%.
Constraints:
- Number of distinct events
- Distribution of events
- Error bounds
There all have to do with collisions I assume.
Huge space advantages: really small table needed.
Counts are not perfect.
Lecture 10b: Large Scale Dimensionality Reduction
Three general options for working with very large matrices
1) Distribution of matrix operations (such as SVD) 2) Approximation (of SVD) 3) Randomization (of linear algebra)
Dimensionality reduction
Project data onto a low d-dimensional subspace. Can be a good approximation. Data could potentially also be accurately expressed in fewer dimensions in the first place.
Why reduce dimensions?
- Discover hidden correlations or topics
- E.g. words that commonly occur together
- Remove redundant and noise features
- Interpretation and visualization
- Easier storage and processing
SVD
- A = Input data matrix
- m x n input data (m documents, n terms)
- U = left singular vectors
- m x r (m documents, r concepts)
- (S)igma = Singular Values
- r x r singular values on diagonal representing strength of each concept;
- r is rank of matrix A)
- Remember: rank is the amount of independent vectors (shows in echelon form).
- Rank corresponds to amount of eigenvalues.
- V = Right singular vectors
- n x r matrix (n terms, r concepts)
A = USV^T = the sum over all i, with s_iu_i(v_i)^T
- These components are unique
- U and V are column orthonormal.
- Multiplying its transpose with itself gives the identity matrix
- Sigma is diagonal
- Singular values are positive and sorted from high to low.
Latent vectors
We thus have vectors that map onto a latent space. And we have concepts that map from the latent space.
Both of these are called "concepts" or latent dimensions / factors.
So let's say we have a M(users) x N(movies) matrix.
The association between users and movies in SVD is split up into several parts.
- We have a user-to-concept similarity matrix U.
- Then we have a movie-to-concept similarity matrix V.
- Why not concept-to-movie? Or is that why you transpose V?)
- I think so, yes.
-
The singular values express the "strength" of the concept, i.e. how much of the variance in user-movie data is explained by the captured relation.
-
Rows of original matrix correspond to rows of V transposed.
- Rows of original matrix correspond to columns of U.
Latent Semantic Indexing (LSI): SVD based on word frequencies. See slide with movie example. Grouped properties, does not have a notion of semantic (i.e. it is latent)
Labeling still depends on interpretation of the user.
Best Low Rank Approximation
If you compute A = U.Sigma.V^T and B - U.S.V^T where S is Sigma with the top k singular values left,o then:
B is the best approximation of A of k ranks. Again: ranks indicate independent vectors; by nullifying singular values you limit those.
How many singular values to keep?
Goal is to keep sigma matrix small. Reduction: only keep strongest singular values on diagonal of sigma.
Sigma: variance left after projection
Heuristic: stop when sum of sigma squared ("energy") is 0.8 to 0.9, i.e. amount of variance explained. We assume that the singular values are ordered.
Indication of fit: Compare Frobenius norm of difference between matrix A and reduced matrix B is an indication of the fit / amount of reduction.
N.B. after SVD you do not reduce matrix size, but you do reduce information in it. You don't reduce matrix size because what you do is set some singular values to zero.
Limitations of SVD
- Very expensive on big matrices
- E.g. SVD expensive, but in 10-fold cross validation... 10 times SVD.
- SVD is often used in an exploratory setting to explore important data trends, but that use case is also not feasible anymore on large matrices.
- Limitation: SVD only picks up linear relations.
- What does it all mean? Not always easy to interpret, especially if you start working with many many dimensions.
Three approaches for large scale matrices
1) Do SVD in a distributed way 2) Approximate SVD 3) Randomization techniques
1) Do SVD in a distributed manner in Spark MLLib
Distribution: SVD in Spark MLLib
How do you distribute the data of the matrices? U, V, Sigma.
In other words, we can choose different partitioning schemes.
Partition by entry
Use case: Matrix is 1) very big and 2) sparse
- "Coordinate matrix" approach. Store matrix datapoints in 3-tuples. (row,column, value).
- Makes matrix factorization hard
- And ... what do you actually partition on then?
Partition by rows
Assumes row vector fits in memory
- Row-oriented distributed matrix with row indices
- Amount of column has a hard limit on max int range for indices
- Row vectors are stored in an RDD
Partition by blocks
Assumes block fits in memory
- Divide data in 1024x1024 blocks, i.e. a submatrix.
- Maintains indices to blocks.
- Blocks stored in MatrixBlock RDDs.
- I don't really see how this works
Implementations: Many matrix operation implementations need to be made for different matrices and properties.
{ Coordinate, Row, Block, LocalDense, LocalSpare } --> Already 10 required implementations for pairs.
We are assuming that we will only use the top singular values
Two prototypical cases for SVD in Spark
Spark has a computeSVD function that decides based on the input dimensions what approach to take.
1) "Tall and skinny": typical for recommendation systems, people don't see all movies. 2) "Roughly Square": you don't throw away much data.
Tall and skinny: n << m (so very many rows, but little columns )
- Compute singular values and right singular vectors V from eigenvalues and eigenvectors of "Grammian matrix" A^T*A. o
- Grammian matrix is
- n x n and thus way smaller than A, since we assumed that n is relatively low
- This is thus the cause why this approach is efficient for "tall and skinny" computations.
- symmetric
- Both positive semidefinite; eigen- and singular values are both non-negative and the same.
Note that you only compute V, and not U.
The left singular vectors U are only computed on request. This is because if you keep your input matrix A, and we have computed S and V, then U is the only unknown.
U can thus be reconstructed from the other matrices: U = A(VS^-1). This saves unnecessary computation.
Special case of tall and skinny: for n < 100, or relatively many columns (k > n/2)...
We can compute eigenvalues and eigenvectors locally on the driver. "Requires a single pass with O(n^2) storage on each executor and on the driver, and O(n^2*k) time on the driver" I don't know why, and neither do I know whether this is the "square" case
Note from class about On^2K time : for every sigma/dimension (k) we want to have you do the aforementioned computation. See slides for memory requirements. If they are not met, we can do with "normal" matrix factorization with ALS
For this condition there is an efficient method for computing the truncated SVD.
1) Compute truncated SVD of A.T * A to get Vk ( rank k ) * This requires only matrix multiplications 2) Compute SVD of AVk to get Sigma_k and Vk. (again U can be reconstructed) * Assumed that SVD of AVk is small enough to be calculated locally
If it is not possible to do this locally, there is a distributed version of this procedure.
Roughly square
No fancy algorithms. Fall back on the most efficient matrix multiplication code available: FORTRAN! Basic matrix operations are still the most efficient in FORTRAN :-)
Valuzos Brothers paper; on properties of the web.
Overview SVD
All the crucial points that were unclear to me from previous story
- If A is small carry out computations locally using old libraries and techniques
- Is A is large, separate matrix operations from eigenvalue operations
- ARPACK does eigenvalue computations
- Spark calculates matrices and vectors in a distributed manner
- If A is large but tall and skinny, then A^t o A fits on the driver!
- m >> n
- A^t o A is n x n, so small in this scenario
- Computation can be done on driver, no communication overhead of distributing the eigen-decomposition computation on the cluster
Why to avoid SVD
- Inefficient/expensive, less suited for interpretation
- Problems with sparsity caused by incomplete data
- Then finding the singular values for the little known values is likely overfitting
- Is orthonormality of U and V really needed?
Approximating SVD with Stochastic Optimization
- You do not necessarily need the exact SVD decomposition.
- You can find a matrix factorization that is good enough, e.g. using ALS (cf. recommender!)
- Can be distributed, using "mini-batches"
(SVD minus Singular values = just matrox factorization)
Example:
- Netflix movie recommendations
- using Collaborative Filtering
- Website Recommendations by Microsoft
- Gaussian non-negative matrix factorization
- News personalization by Google
- Probabilistic latent semantic indexing
Randomization techniques: The CUR decomposition.
- Pick at random k columns (C) and rows (R) from m x n matrix A
- In practice 4k each
- Define U as the "generalized inverse of their intersection" (Wait whut)
- C and R are made up of rows and columns directly, not linear combinations of them, and are those straightforward to interpret.
Relative error guarantee of CUR (relative to SVD k-rank truncated)
The Frobenius norm of A' (CUR) and A (input data) is equal or lower to the Frobenius norm of the best SVD rank-k approximation plus a fixed error margin, with a probability 1-delta.
Where does delta come from?
"Many data analysis applications deal with large matrices and involve approximating the matrix using a small number of "components." Typically, these components are linear combinations of the rows and columns of the matrix, and are thus difficult to interpret in terms of the original features of the input data. In this paper, we propose and study matrix approximations that are explicitly expressed in terms of a small number of columns and/or rows of the data matrix, and thereby more amenable to interpretation in terms of the original data."
See https://arxiv.org/abs/0708.3696
- Okay so we pick C with columns, and R with rows
- These columns and rows are both from matrix A, so they will have intersections W
- Making a drawing makes this immediately clear
- U is the generalized inverse of this intersection W (U = W+)
- Generalized inverse is such that WW+W=W
- Can be computed using SVD, but that ok since the intersection is small
Is a more loosely defined inverse than the strict and unique inverse for which holds AA^-1A=A
SVD vs CUR: remember difference w.r.t. sparsity and density.
Nice thing about CUR is that both C and R are sparse. Whereas in SVD in U and V are big and dense.
A difference in Sigma vs U is that Sigma is sparse and small and U is dense and small. Sigma is sparse by definition since it only contains entries on the diagonal. U is dense because it's the intersection on actual data points.
Because C and R correspond to columns and rows, they are interpretable.
Results / Performance
CUR achieved the same accuracy with significantly less space and time requirements.
Lecture 11 LSH: avoid counting duplicates in high-dimensional space
Problem: find near-neighbours in high-dimensional space
Why no hashing on content of websites? Content not stable enough, expensive. High chance of collisions.
Issue today: how to prevent counting duplicates (e.g. of webpages).
Arjen: also NNs do similarity calculations in a high-dimensional space where partials relations are stored AI according to Arjen: replacing things that you see with things that you saw.
Applications based: on Near duplicate detection.
- Pages with similar content / words
- Customers who purchased similar products
- Images with similar features
- Users who visited similar websites
How to do k-NN search efficiently in high dimensions?
E.g. represent a picture as a long vector of pixels. The question whether two pictures are similar is then an issue of determining how close two high-dimensional vectors are to each other according to some distance measure and threshold.
What distance measure to use?
If dimension > 20, Eucledian becomes almost meaningless because the distance is always practically the same to all other datapoints. I.e. the distances between points are almost perfectly uniformly distributed, which makes Euclidean distance as a measure for relevance inaccurate.
See: https://stats.stackexchange.com/questions/99171/why-is-euclidean-distance-not-a-good-metric-in-high-dimensions
Another application, beyond machine learning, is nearest neighbor search: given an observation of interest, find its nearest neighbors (in the sense that these are the points with the smallest distance from the query point). But in high dimensions, a curious phenomenon arises: the ratio between the nearest and farthest points approaches 1, i.e. the points essentially become uniformly distant from each other. This phenomenon can be observed for wide variety of distance metrics, but it is more pronounced for the Euclidean metric than, say, Manhattan distance metric. The premise of nearest neighbor search is that "closer" points are more relevant than "farther" points, but if all points are essentially uniformly distant from each other, the distinction is meaningless.
So we need dimensionality reduction before using a measure like Eucledian distance. So for many applications people first do dimension reduction before applying NN.
Always check distance distribution: plot all pairs with their distance in matrix, make histogram of values. Ideally, very few small distances, many equal distances. But there should be enough with small distance for a distance measure to be a meaningful indication of similarity.
Dimensionality reduction: e.g. create subspaces of 20, so that you can have a meaningful distance measure inside this cluster, with equal distance to other clusters. So we have to find a nice subspace for further analysis.
Filter-Refine approach: Solve near duplicate detection in close to O(n)
Approach: do two sequential passes.
1) Filter * Hash documents to buckets in such a way that similar documents end up in the same buckut * Assumes that the hashing procedure is cheap! Otherwise there is no improvement 2) Refine * Only compare candidates, i.e. documents that hashed to the same bucket * This comparison is still expensive, but the scale is smaller.
Distance measure we consider: Jaccard distance
Jaccard similarity is the size of intersection divides by the size of the union of two compared sets. (Distance = 1 - similarity).
Very simple rationale! What properties of the total set of points is shared between the two sets?
From Wikipedia:
The MinHash min-wise independent permutations locality sensitive hashing scheme may be used to efficiently compute an accurate estimate of the Jaccard similarity coefficient of pairs of sets, where each set is represented by a constant-sized signature derived from the minimum values of a hash function.
Problems with k-NN on scale
Okay, so why is straightforward k-NN not possible on a large dataset? (more than millions)
- Documents too large and/or too many to fit into memory
- Too many documents to consider all pairs
- Pieces of near duplicate documents may appear out of order
- imagine news articles that only show a preview. Then you e.g. need to make a set of each paragraph.
Note that the similarity problem is easier than an Information Retrieval problem because we do not really care about the contents, only whether they are similar!
Filter-refine pipeline: Min-Hash procedure with Locality-sensitive hashing
Near duplicate detection is thus done before IR. N.B. near duplicate detection is done for de-duplication of data.
Be aware that all these types of hashing are different and have different goals.
1) Shingling * Turn document into sets of stings of length k. * Hashing used for compression of shingles 2) Min-Hashing * Convert sets into signatures that preserve similarity * Integer vectors representing sets and reflecting similarity * Hashing used for representing documents in terms of signatures * Extra: Hash row indexes to approximate a decent permutation rather than actually permuting. 3) Locality-sensitive hashing * Zoom in on pairs likely to be from similar documents * Works on Min-hash signature matrices * Hash similar min-hash signatures to similar buckets * Rationale: if bands of a signature hash to the same bucket, they are more likely to be similar.
Step 1: Shingling
- n-grams --> linguistics.
- k-grams --> databases
- shingles --> Stanford speak.
But all the same: a string sequence of k tokens, can be characters or words (or something else ). In our context, the n-grams are usually defined on characters.
Set vs bag: bag is a multiset that has duplicates.
Assumption: if many shingles are shared, a document is similar.
Especially if k is defined on characters, we need large enough k, 5-10.
For k=1, all documents would be equally similar, because almost all documents contain all letters from the alphabet. Thus, a larger value for k is needed to distinguish documents that are not similar.
In a way, representing the document in terms of shingles is a hash function that hashes a document onto a set of shingles.
Compress shingles
Trick: instead of taking the shingles themselves, hash the shingles to 4 bytes. This saves a lot of space.
Let's say you have 4-shingles. Assuming that with UTF-8 the characters we use are represented by 1 byte each (8 bits). Then we can express all combinations of four characters in these 4 bytes (2^32). However, in documents almost all 4-shingles are very unlikely, so in practice this 2^32 is very sparsely inhabited, because most k-shingles will not be present.
Similar, the space of all 9-character combinations is extremely big but also extremely sparse. We can just use a more compact representation by hashing shingles onto a 4-byte hash. Hashing to 4 bytes gives a more compact representation, but due do the sparsity there will not be too many collisions.
Improvement: Rather than comparing strings for similarity, we can now determine similarity by comparing bit vectors.
We have moved from a doc-term matrix, to a doc-shingle matrix.
Smarter shingling
Approach: look at stopword plus two subsequent words.
Step 2. Min-Hashing (Filter step)
Encode sets as bit vectors
So, we represented each document as a set of k-shingles, and hashed them, so that now each document is represented as a set of hashes.
- Encode sets using 0/1 (bit, boolean) vectors.
- One dimension per element in the universal set
- I.e. we compute a total set of all shingles (shingle hashes)
- Per document we record 1 if the shingle is present in the document, 0 otherwise
- Thus we ultimately end up with a document-shingle boolean matrix containing only 1s and 0s.
We can further specify intersection and union operators to make Jaccard applicable to these bit vectors:
- Interpret set intersection as bitwise AND
- Interpret set union as bitwise OR.
Example: so Jaccard similarity between C1=10111 and C2=10011 is 3/4. (distance 1/4)
So again, we have a boolean matrix with shingles vs. documents (or the other way around). Again, such a matrix is expected to be sparse.
In this course, we use as a convention:
- Rows: elements, i.e. shingles
- Columns: set, i.e. documents
We can thus calculate similarity between documents by using bitwise Jaccard on the columns.
But this will still take too long! And memory intensive.
Instead, we are going to compare short signatures, that are hashes that preserve similarity. These signatures will be so short that now we can fit everything in memory!
Goal: What is required for this is that when similarity is high, the hashes are equal, whereas if the similarity is low, the hashes are not equal.
NOTE: this means that for each distance measure we need a (different) appropriate hash
For Jaccard, this is Min-hash
Min-hash: the hash procedure for Jaccard similarity
Requirements for the hash:
1) Compress space, signature of big documents should also fit into ram 2) "similarity" between the hashes should follow the Jaccard similarity on the bit vectors
- So if sim(C1,C2) is high, then h(c1) = h(C2) with a high probability
- and if sim(C1,C2) is low, then with high probability h(c1)!=h(c2)
Idea: hash similar documents into the same buckets
The procedure is as such:
Input: The boolean matrix of shingles vs documents
- Permute shingle row vectors, i.e. look at shingles from set (i.e. rows) in different order. (Assuming shingles are rows, could take other representation).
- Pick rows in the permuted order until and record the index of the first document (column) that contains the shingle.
- Scan through rows looking for 1s in all columns at once, and update values in the signature matrix on the go, for a one-pass implementation.
- We write down the document index of that first matching shingle (called the "min-hash").
- Repeat n (e.g. 100) times.
- So we have n independent hash functions because we use n different permutations
Results: a signature of a column, stored in a signature matrix
You must of course apply the same 100 hashes to all columns, otherwise comparing the signatures is absolutely meaningless.
Note: you do not actually permute the rows! Would be stupidly expensive. Instead, you assign an ordering to rows.
I didn't read the example picture correctly at first: you don't read the permutation from top to bottom. The number at the top does not indicate a row number that we visit the first; it represents the order of the row next to it.
Awesome property: why does min-hash preserve similarity?
From https://www.youtube.com/watch?v=96WOGPUgMfw
The probability of h(c1)=h(c2) is the same as Jaccard Sim(C1,C2)!
So e.g. if Jaccard similarity is 3/4, we will find that in 3/4 of the cases the min-hashes of two columns (i.e. documents) are the same!
Handy notation: there's three types of rows with values for c1, c2:
- a: (1, 1)
- b: (1,0)
- c: (0,1)
- d: (0,0)
Define #a as the amount of columns of type a.
Then bitwise Jaccard can be rewritten as: #a / (#a + #b + #c). Why is the probability that hashes are equal expressed with the same formula?
Take two columns.
1) If we permute over rows, we are likely to find d rows due to sparsity. 2) We at some point arrive at a row where at least one column has a 1. - If we would first arrive at a type a row, then the min-hashes agree! - If we would first arrive at a type b or c row, then only one column will get a min-hash assigned, and the other column is guaranteed to have a higher min-hash value. 3) So the chance that two columns will have the same min-hash value is the chance that the first row that is not a d-row, will be an a-row. 4) That chance is #a / (#a + #b + #c)! NICE!
Important results: So, the fraction of which the min hash signatures agree in components is the Jaccard similarity! (Signatures are still per document, so columns)
So this is a sampling approach to find the Jaccard similarity.
This hugely saved memory! We only store ~100 byte signatures! The longer the signature, the smaller the expected error.
N.B. the initial permutation is random, but from there the order of picking is deterministic.
Even cheaper: approximating a permutation of rows
Basically: hash the row on the row index to give a ranking. If you do this for all rows and rank the results, you end up with a near-perfect permutation as long as the amount of hash buckets approximates or equals the amount of rows.
Step 3: Locality-sensitivity Hashing on Signature Matrices
Okay, now we have a super efficient representation where each document has a signature. We can determine Jaccard signature by comparing the document signatures.
Now the question is: how can you find all similar (sim > threshold) documents without having to compare all columns?
In other words, is there an efficient way to find good candidates for comparison, so we don't have to compare all columns but only these subspaces?
Another filter step: focus on pairs of signatures likely to be from similar documents.
For min-has signature matrices, we can find yet another hash function that hashes similar columns to similar buckets.
LSH idea
- Pick similarity threshold
- All columns that have a signature agreement > threshold are candidates
- Because we have seen that signature agreement approximates Jaccard.
Main idea: apply many hash functions to the signatures, where each hash function places a signature in a bucket. If different hash functions put two signatures together in a bucket, they are likely similar and are thus candidates for further comparison.
Actually, two signatures are considered a candidate pair if they are hashed at least once to the same bucket.
Trade-off:
- you do not want too little buckets, because then you still have to compare a lot of signatures.
- you do not want too many buckets, because then similar signatures are less likely to end up together in a bucket
How do you achieve that similar signatures are more likely to hash into the same bucket?
1) Define bands on the signature matrix, consisting of r rows. 2) Choose as many target buckets as your memory can handle 3) Hash each band (subset of the components of a signature i.e. rows) separately. You divide all signature rows over bands, so higher b, lower r (band width). 4) If two columns are similar, then it is more likely that two bands (i.e. two subparts of that column) will be identical and thus hashed to the same bucket.
So the rationale is: for very similar signatures it is more likely that they share a band (i.e. a subpart of the signature) that is identical, and that will be hashed into the same bucket. (Don't make the band too small of course, then everything will be regarded similar)
See for details: https://www.youtube.com/watch?v=_1D35bN95Go
You can check in main memory if candidate pairs really do have similar signatures.
You can also eliminate false positives by going back through the original sets and calculating Jaccard. However, you cannot eliminate false negatives, because these sets will never be selected as a candidate. You can thus also not double check them.
ANN library for finding similar word embedding is based on locality sensitivity hashing.
You will miss some of the cases, which could be an issue for some applications.
But it's fine for web crawls: no drama if you miss some duplicates.
Potential application: discover Twitter trends. Compare all incoming on similarity of what you've seen before. Not feasible without LSH.
Important for exam:
- Know the pipeline
- How to get from shingles to min-hash