Skip to content
Closed
Changes from 19 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
91fd7e6
Add new algorithm PrefixSpan and test file.
zhangjiajin Jul 7, 2015
575995f
Modified the code according to the review comments.
zhangjiajin Jul 8, 2015
951fd42
Delete Prefixspan.scala
zhangjiajin Jul 8, 2015
a2eb14c
Delete PrefixspanSuite.scala
zhangjiajin Jul 8, 2015
89bc368
Fixed a Scala style error.
zhangjiajin Jul 8, 2015
1dd33ad
Modified the code according to the review comments.
zhangjiajin Jul 9, 2015
4c60fb3
Fix some Scala style errors.
zhangjiajin Jul 9, 2015
ba5df34
Fix a Scala style error.
zhangjiajin Jul 9, 2015
574e56c
Add new object LocalPrefixSpan, and do some optimization.
zhangjiajin Jul 10, 2015
ca9c4c8
Modified the code according to the review comments.
zhangjiajin Jul 11, 2015
22b0ef4
Add feature: Collect enough frequent prefixes before projection in Pr…
zhangjiajin Jul 14, 2015
078d410
fix a scala style error.
zhangjiajin Jul 14, 2015
4dd1c8a
initialize file before rebase.
zhangjiajin Jul 15, 2015
a8fde87
Merge branch 'master' of https://github.com/apache/spark
zhangjiajin Jul 15, 2015
6560c69
Add feature: Collect enough frequent prefixes before projection in Pr…
zhangjiajin Jul 15, 2015
baa2885
Modified the code according to the review comments.
zhangjiajin Jul 15, 2015
095aa3a
Modified the code according to the review comments.
zhangjiajin Jul 16, 2015
b07e20c
Merge branch 'master' of https://github.com/apache/spark into Collect…
zhangjiajin Jul 16, 2015
d2250b7
remove minPatternsBeforeLocalProcessing, add maxSuffixesBeforeLocalPr…
zhangjiajin Jul 18, 2015
64271b3
Modified codes according to comments.
zhangjiajin Jul 27, 2015
6e149fa
Fix splitPrefixSuffixPairs
Jul 28, 2015
01c9ae9
Add getters
Jul 28, 2015
cb2a4fc
Inline code for readability
Jul 28, 2015
da0091b
Use lists for prefixes to reuse data
Jul 28, 2015
1235cfc
Use Iterable[Array[_]] over Array[Array[_]] for database
Jul 28, 2015
c2caa5c
Readability improvements and comments
Jul 28, 2015
87fa021
Improve extend prefix readability
Jul 28, 2015
ad23aa9
Merge pull request #1 from feynmanliang/SPARK-8998-collectBeforeLocal
zhangjiajin Jul 29, 2015
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 116 additions & 23 deletions mllib/src/main/scala/org/apache/spark/mllib/fpm/PrefixSpan.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

package org.apache.spark.mllib.fpm

import scala.collection.mutable.ArrayBuffer

import org.apache.spark.Logging
import org.apache.spark.annotation.Experimental
import org.apache.spark.rdd.RDD
Expand All @@ -43,6 +45,8 @@ class PrefixSpan private (
private var minSupport: Double,
private var maxPatternLength: Int) extends Logging with Serializable {

private val maxSuffixesBeforeLocalProcessing: Long = 10000
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is really maxProjectedDBSizeBeforeLocalProcessing since you are counting the number of total items in the projected db not just number of suffixes

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK


/**
* Constructs a default instance with default parameters
* {minSupport: `0.1`, maxPatternLength: `10`}.
Expand Down Expand Up @@ -82,20 +86,106 @@ class PrefixSpan private (
logWarning("Input data is not cached.")
}
val minCount = getMinCount(sequences)
val lengthOnePatternsAndCounts =
getFreqItemAndCounts(minCount, sequences).collect()
val prefixAndProjectedDatabase = getPrefixAndProjectedDatabase(
lengthOnePatternsAndCounts.map(_._1), sequences)
val groupedProjectedDatabase = prefixAndProjectedDatabase
.map(x => (x._1.toSeq, x._2))
val lengthOnePatternsAndCounts = getFreqItemAndCounts(minCount, sequences)
val prefixSuffixPairs = getPrefixSuffixPairs(
lengthOnePatternsAndCounts.map(_._1).collect(), sequences)
var patternsCount: Long = lengthOnePatternsAndCounts.count()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove patternsCount since it's no longer necessary and saves one scan of dataset

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK

var allPatternAndCounts = lengthOnePatternsAndCounts.map(x => (ArrayBuffer(x._1), x._2))
var (smallPrefixSuffixPairs, largePrefixSuffixPairs) =
splitPrefixSuffixPairs(prefixSuffixPairs)
largePrefixSuffixPairs.persist(StorageLevel.MEMORY_AND_DISK)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We actually pass over prefixSuffixPairs more than largePrefixSuffixPairs. How does perf change when you persist prefixSuffixPairs instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, I tested, and the prefixSuffixPairs.persist (7s) is better than largePrefixSuffixPairs.persist (11s) .

var patternLength: Int = 1
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need patternLength anymore?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK

while (patternLength < maxPatternLength &&
largePrefixSuffixPairs.count() != 0) {
val (nextPatternAndCounts, nextPrefixSuffixPairs) =
getPatternCountsAndPrefixSuffixPairs(minCount, largePrefixSuffixPairs)
patternsCount = nextPatternAndCounts.count()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK

largePrefixSuffixPairs.unpersist()
val splitedPrefixSuffixPairs = splitPrefixSuffixPairs(nextPrefixSuffixPairs)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: split**_t**_ed

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, instead of ._1 and ._2 below, why not just assign like in L94 here as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK

largePrefixSuffixPairs = splitedPrefixSuffixPairs._2
largePrefixSuffixPairs.persist(StorageLevel.MEMORY_AND_DISK)
smallPrefixSuffixPairs = smallPrefixSuffixPairs ++ splitedPrefixSuffixPairs._1
allPatternAndCounts = allPatternAndCounts ++ nextPatternAndCounts
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: ++=

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK

patternLength = patternLength + 1
}
if (smallPrefixSuffixPairs.count() > 0) {
val projectedDatabase = smallPrefixSuffixPairs
.map(x => (x._1.toSeq, x._2))
.groupByKey()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This assumes that all the values (suffixes) associated to a key (prefix) will fit on an executor, but I don't think that patternsCount > minPatternsBeforeShuffle will guarantee that. Better to count the suffixes for each prefix using aggregateByKey before doing local processing.

.map(x => (x._1.toArray, x._2.toArray))
val nextPatternAndCounts = getPatternsInLocal(minCount, projectedDatabase)
allPatternAndCounts = allPatternAndCounts ++ nextPatternAndCounts
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: ++=

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK

}
allPatternAndCounts.map { case (pattern, count) => (pattern.toArray, count) }
}


/**
* Split prefix suffix pairs to two parts:
* suffixes' size less than maxSuffixesBeforeLocalProcessing and
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Prefixes with projected databases larger than maxSuffixesBeforeLocalProcessing" and ...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK

* suffixes' size more than maxSuffixesBeforeLocalProcessing
* @param prefixSuffixPairs prefix (length n) and suffix pairs,
* @return small size prefix suffix pairs and big size prefix suffix pairs
* (RDD[prefix, suffix], RDD[prefix, suffix ])
*/
private def splitPrefixSuffixPairs(
prefixSuffixPairs: RDD[(ArrayBuffer[Int], Array[Int])]):
(RDD[(ArrayBuffer[Int], Array[Int])], RDD[(ArrayBuffer[Int], Array[Int])]) = {
val suffixSizeMap = prefixSuffixPairs
.map(x => (x._1, x._2.length))
.reduceByKey(_ + _)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about

    val prefixToSuffixSize = prefixSuffixPairs
      .aggregateByKey(0)(
        seqOp = { case (count, suffix) => count + suffix.length },
        combOp = { _ + _ })
      .collect()
      .toMap
    val smallPrefixes = prefixToSuffixSize
      .filter(_._2 <= maxSuffixesBeforeLocalProcessing)
      .keys
      .toSet
    val smallPairs = prefixSuffixPairs.filter { case (prefix, _) => smallPrefixes.contains(prefix) }
    (smallPairs, prefixSuffixPairs.subtract(smallPairs))

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@feynmanliang I compared these two methods. I find your method's running time more than mine. And the result is not correct. I don't know why it was so, please check it, thank you.

.map(x => (x._2 <= maxSuffixesBeforeLocalProcessing, Set(x._1)))
.reduceByKey(_ ++ _)
.collect
.toMap
val small = if (suffixSizeMap.contains(true)) {
prefixSuffixPairs.filter(x => suffixSizeMap(true).contains(x._1))
} else {
prefixSuffixPairs.filter(x => false)
}
val large = if (suffixSizeMap.contains(false)) {
prefixSuffixPairs.filter(x => suffixSizeMap(false).contains(x._1))
} else {
prefixSuffixPairs.filter(x => false)
}
(small, large)
}

/**
* Get the pattern and counts, and prefix suffix pairs
* @param minCount minimum count
* @param prefixSuffixPairs prefix (length n) and suffix pairs,
* @return pattern (length n+1) and counts, and prefix (length n+1) and suffix pairs
* (RDD[pattern, count], RDD[prefix, suffix ])
*/
private def getPatternCountsAndPrefixSuffixPairs(
minCount: Long,
prefixSuffixPairs: RDD[(ArrayBuffer[Int], Array[Int])]):
(RDD[(ArrayBuffer[Int], Long)], RDD[(ArrayBuffer[Int], Array[Int])]) = {
val prefixAndFrequentItemAndCounts = prefixSuffixPairs
.flatMap { case (prefix, suffix) => suffix.distinct.map(y => ((prefix, y), 1L)) }
.reduceByKey(_ + _)
.filter(_._2 >= minCount)
val patternAndCounts = prefixAndFrequentItemAndCounts
.map { case ((prefix, item), count) => (prefix :+ item, count) }
val prefixToFrequentNextItemsMap = prefixAndFrequentItemAndCounts
.keys
.groupByKey()
.map(x => (x._1.toArray, x._2.toArray))
val nextPatterns = getPatternsInLocal(minCount, groupedProjectedDatabase)
val lengthOnePatternsAndCountsRdd =
sequences.sparkContext.parallelize(
lengthOnePatternsAndCounts.map(x => (Array(x._1), x._2)))
val allPatterns = lengthOnePatternsAndCountsRdd ++ nextPatterns
allPatterns
.mapValues(_.toSet)
.collect()
.toMap
val nextPrefixSuffixPairs = prefixSuffixPairs
.filter(x => prefixToFrequentNextItemsMap.contains(x._1))
.flatMap { case (prefix, suffix) =>
val frequentNextItems = prefixToFrequentNextItemsMap(prefix)
val filteredSuffix = suffix.filter(frequentNextItems.contains(_))
frequentNextItems.flatMap { item =>
val suffix = LocalPrefixSpan.getSuffix(item, filteredSuffix)
if (suffix.isEmpty) None
else Some(prefix :+ item, suffix)
}
}
(patternAndCounts, nextPrefixSuffixPairs)
}

/**
Expand All @@ -122,37 +212,40 @@ class PrefixSpan private (
}

/**
* Get the frequent prefixes' projected database.
* Get the frequent prefixes and suffix pairs.
* @param frequentPrefixes frequent prefixes
* @param sequences sequences data
* @return prefixes and projected database
* @return prefixes and suffix pairs.
*/
private def getPrefixAndProjectedDatabase(
private def getPrefixSuffixPairs(
frequentPrefixes: Array[Int],
sequences: RDD[Array[Int]]): RDD[(Array[Int], Array[Int])] = {
sequences: RDD[Array[Int]]): RDD[(ArrayBuffer[Int], Array[Int])] = {
val filteredSequences = sequences.map { p =>
p.filter (frequentPrefixes.contains(_) )
}
filteredSequences.flatMap { x =>
frequentPrefixes.map { y =>
val sub = LocalPrefixSpan.getSuffix(y, x)
(Array(y), sub)
(ArrayBuffer(y), sub)
}.filter(_._2.nonEmpty)
}
}

/**
* calculate the patterns in local.
* @param minCount the absolute minimum count
* @param data patterns and projected sequences data data
* @param data prefixes and projected sequences data data
* @return patterns
*/
private def getPatternsInLocal(
minCount: Long,
data: RDD[(Array[Int], Array[Array[Int]])]): RDD[(Array[Int], Long)] = {
data.flatMap { case (prefix, projDB) =>
LocalPrefixSpan.run(minCount, maxPatternLength, prefix.toList, projDB)
.map { case (pattern: List[Int], count: Long) => (pattern.toArray.reverse, count) }
data: RDD[(Array[Int], Array[Array[Int]])]): RDD[(ArrayBuffer[Int], Long)] = {
data.flatMap {
case (prefix, projDB) =>
LocalPrefixSpan.run(minCount, maxPatternLength, prefix.toList.reverse, projDB)
.map { case (pattern: List[Int], count: Long) =>
(pattern.toArray.reverse.to[ArrayBuffer], count)
}
}
}
}