Skip to content
Closed
Show file tree
Hide file tree
Changes from 32 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
710f257
initial fpm
YY-OnCall Jun 15, 2016
b8d117d
add ass rule
YY-OnCall Jun 16, 2016
bc9b830
Merge remote-tracking branch 'upstream/master' into mlfpm
hhbyyh Jul 10, 2016
5764e59
Merge remote-tracking branch 'upstream/master' into mlfpm
hhbyyh Jul 11, 2016
1ca4e45
Merge remote-tracking branch 'upstream/master' into mlfpm
hhbyyh Jul 11, 2016
c30dd7c
refine code
hhbyyh Jul 11, 2016
c0b5291
Merge remote-tracking branch 'upstream/master' into mlfpm
hhbyyh Oct 8, 2016
77e1f93
Merge remote-tracking branch 'upstream/master' into mlfpm
hhbyyh Oct 10, 2016
2f1a08c
add ut
hhbyyh Oct 10, 2016
388adaf
Merge remote-tracking branch 'upstream/master' into mlfpm
YY-OnCall Oct 10, 2016
7eabd31
Merge remote-tracking branch 'upstream/master' into mlfpm
hhbyyh Oct 14, 2016
3730e1b
Merge remote-tracking branch 'upstream/master' into mlfpm
YY-OnCall Oct 19, 2016
3a000df
Merge remote-tracking branch 'upstream/master' into mlfpm
hhbyyh Nov 2, 2016
e5574be
refine and add unit test
hhbyyh Nov 2, 2016
ed1f91e
Merge remote-tracking branch 'upstream/master' into mlfpm
YY-OnCall Dec 16, 2016
2afdf48
Merge branch 'mlfpm' of https://github.com/hhbyyh/spark into mlfpm
YY-OnCall Dec 16, 2016
63eaf08
fpgrowth version
YY-OnCall Dec 16, 2016
0837b55
Merge remote-tracking branch 'upstream/master' into mlfpm
YY-OnCall Jan 19, 2017
3273b76
add numPartitions and change version
YY-OnCall Jan 19, 2017
d4d8ac2
Merge remote-tracking branch 'upstream/master' into mlfpm
YY-OnCall Jan 24, 2017
fbac43f
Merge remote-tracking branch 'upstream/master' into mlfpm
YY-OnCall Jan 31, 2017
57c9437
use association rules to transform
YY-OnCall Jan 31, 2017
049e1a3
make AssociationRules private and use join
YY-OnCall Feb 8, 2017
5d7881c
Merge remote-tracking branch 'upstream/master' into mlfpm
YY-OnCall Feb 15, 2017
e141776
make assocationrules static and support generic
YY-OnCall Feb 15, 2017
140885d
Merge remote-tracking branch 'upstream/master' into mlfpm
YY-OnCall Feb 19, 2017
06e5c69
Merge remote-tracking branch 'upstream/master' into mlfpm
YY-OnCall Feb 20, 2017
dfdf85d
transform optimize and code refine
YY-OnCall Feb 20, 2017
453ae5b
Merge remote-tracking branch 'upstream/master' into mlfpm
YY-OnCall Feb 20, 2017
5050bd3
Merge remote-tracking branch 'upstream/master' into mlfpm
YY-OnCall Feb 21, 2017
d8e4884
add numpartitions
YY-OnCall Feb 23, 2017
bfcef4a
remove sort
YY-OnCall Feb 24, 2017
3d7ed0b
back to broadcast
YY-OnCall Feb 25, 2017
9940c47
ut minor rename
YY-OnCall Feb 25, 2017
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
347 changes: 347 additions & 0 deletions mllib/src/main/scala/org/apache/spark/ml/fpm/FPGrowth.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,347 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.spark.ml.fpm

import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

import org.apache.hadoop.fs.Path

import org.apache.spark.annotation.{Experimental, Since}
import org.apache.spark.ml.{Estimator, Model}
import org.apache.spark.ml.param._
import org.apache.spark.ml.param.shared.{HasFeaturesCol, HasPredictionCol}
import org.apache.spark.ml.util._
import org.apache.spark.mllib.fpm.{AssociationRules => MLlibAssociationRules,
FPGrowth => MLlibFPGrowth}
import org.apache.spark.mllib.fpm.FPGrowth.FreqItemset
import org.apache.spark.sql._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._

/**
* Common params for FPGrowth and FPGrowthModel
*/
private[fpm] trait FPGrowthParams extends Params with HasFeaturesCol with HasPredictionCol {

/**
* Minimal support level of the frequent pattern. [0.0, 1.0]. Any pattern that appears
* more than (minSupport * size-of-the-dataset) times will be output
* Default: 0.3
* @group param
*/
@Since("2.2.0")
val minSupport: DoubleParam = new DoubleParam(this, "minSupport",
"the minimal support level of a frequent pattern",
ParamValidators.inRange(0.0, 1.0))
setDefault(minSupport -> 0.3)

/** @group getParam */
@Since("2.2.0")
def getMinSupport: Double = $(minSupport)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

MLLib's FPGrowth have a param numPartitions, will it be included here?

/**
* Number of partitions (>=1) used by parallel FP-growth. By default the param is not set, and
* partition number of the input dataset is used.
* @group expertParam
*/
@Since("2.2.0")
val numPartitions: IntParam = new IntParam(this, "numPartitions",
"Number of partitions used by parallel FP-growth", ParamValidators.gtEq[Int](1))

/** @group expertGetParam */
@Since("2.2.0")
def getNumPartitions: Int = $(numPartitions)

/**
* Minimal confidence for generating Association Rule.
* Note that minConfidence has no effect during fitting.
* Default: 0.8
* @group param
*/
@Since("2.2.0")
val minConfidence: DoubleParam = new DoubleParam(this, "minConfidence",
"minimal confidence for generating Association Rule",
ParamValidators.inRange(0.0, 1.0))
setDefault(minConfidence -> 0.8)

/** @group getParam */
@Since("2.2.0")
def getMinConfidence: Double = $(minConfidence)

/**
* Validates and transforms the input schema.
* @param schema input schema
* @return output schema
*/
@Since("2.2.0")
protected def validateAndTransformSchema(schema: StructType): StructType = {
val inputType = schema($(featuresCol)).dataType
require(inputType.isInstanceOf[ArrayType],
s"The input column must be ArrayType, but got $inputType.")
SchemaUtils.appendColumn(schema, $(predictionCol), schema($(featuresCol)).dataType)
}
}

/**
* :: Experimental ::
* A parallel FP-growth algorithm to mine frequent itemsets. The algorithm is described in
* <a href="http://dx.doi.org/10.1145/1454008.1454027">Li et al., PFP: Parallel FP-Growth for Query
* Recommendation</a>. PFP distributes computation in such a way that each worker executes an
* independent group of mining tasks. The FP-Growth algorithm is described in
* <a href="http://dx.doi.org/10.1145/335191.335372">Han et al., Mining frequent patterns without
* candidate generation</a>. Note null values in the feature column are ignored during fit().
*

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Here or elsewhere, comment that null featuresCol values are ignored during fit() and are treated as empty sets during transform().

* @see <a href="http://en.wikipedia.org/wiki/Association_rule_learning">
* Association rule learning (Wikipedia)</a>
*/
@Since("2.2.0")
@Experimental
class FPGrowth @Since("2.2.0") (
@Since("2.2.0") override val uid: String)
extends Estimator[FPGrowthModel] with FPGrowthParams with DefaultParamsWritable {

@Since("2.2.0")
def this() = this(Identifiable.randomUID("fpgrowth"))

/** @group setParam */
@Since("2.2.0")
def setMinSupport(value: Double): this.type = set(minSupport, value)

/** @group expertSetParam */
@Since("2.2.0")
def setNumPartitions(value: Int): this.type = set(numPartitions, value)

/** @group setParam */
@Since("2.2.0")
def setMinConfidence(value: Double): this.type = set(minConfidence, value)

/** @group setParam */
@Since("2.2.0")
def setFeaturesCol(value: String): this.type = set(featuresCol, value)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I perfer use setInputCol and inputCol instead of this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks. Let's collect more feedback about it.


/** @group setParam */
@Since("2.2.0")
def setPredictionCol(value: String): this.type = set(predictionCol, value)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ditto, setOutputCol


@Since("2.2.0")
override def fit(dataset: Dataset[_]): FPGrowthModel = {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Add Since annotation

transformSchema(dataset.schema, logging = true)
genericFit(dataset)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Call transformSchema first to do schema validation.

}

private def genericFit[T: ClassTag](dataset: Dataset[_]): FPGrowthModel = {
val data = dataset.select($(featuresCol))
val items = data.where(col($(featuresCol)).isNotNull).rdd.map(r => r.getSeq[T](0).toArray)
val mllibFP = new MLlibFPGrowth().setMinSupport($(minSupport))
if (isSet(numPartitions)) {
mllibFP.setNumPartitions($(numPartitions))
}
val parentModel = mllibFP.run(items)
val rows = parentModel.freqItemsets.map(f => Row(f.items, f.freq))

val schema = StructType(Seq(
StructField("items", dataset.schema($(featuresCol)).dataType, nullable = false),
StructField("freq", LongType, nullable = false)))
val frequentItems = dataset.sparkSession.createDataFrame(rows, schema)
copyValues(new FPGrowthModel(uid, frequentItems)).setParent(this)
}

@Since("2.2.0")
override def transformSchema(schema: StructType): StructType = {
validateAndTransformSchema(schema)
}

@Since("2.2.0")
override def copy(extra: ParamMap): FPGrowth = defaultCopy(extra)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Since annotation

}


@Since("2.2.0")
object FPGrowth extends DefaultParamsReadable[FPGrowth] {

@Since("2.2.0")
override def load(path: String): FPGrowth = super.load(path)
}

/**
* :: Experimental ::
* Model fitted by FPGrowth.
*
* @param freqItemsets frequent items in the format of DataFrame("items"[Seq], "freq"[Long])
*/
@Since("2.2.0")
@Experimental
class FPGrowthModel private[ml] (
@Since("2.2.0") override val uid: String,
@transient val freqItemsets: DataFrame)
extends Model[FPGrowthModel] with FPGrowthParams with MLWritable {

/** @group setParam */
@Since("2.2.0")
def setMinConfidence(value: Double): this.type = set(minConfidence, value)

/** @group setParam */
@Since("2.2.0")
def setFeaturesCol(value: String): this.type = set(featuresCol, value)

/** @group setParam */
@Since("2.2.0")
def setPredictionCol(value: String): this.type = set(predictionCol, value)

/**
* Get association rules fitted by AssociationRules using the minConfidence. Returns a dataframe
* with three fields, "antecedent", "consequent" and "confidence", where "antecedent" and
* "consequent" are Array[T] and "confidence" is Double.
*/
@Since("2.2.0")
@transient lazy val associationRules: DataFrame = {
val freqItems = freqItemsets

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

No need for this temp val

AssociationRules.getAssociationRulesFromFP(freqItems, "items", "freq", $(minConfidence))
}

/**
* The transform method first generates the association rules according to the frequent itemsets.
* Then for each association rule, it will examine the input items against antecedents and
* summarize the consequents as prediction. The prediction column has the same data type as the
* input column(Array[T]) and will not contain existing items in the input column.
* Note that internally it uses Cartesian join and may exhaust memory for large datasets. The null
* values in the feature columns are treated as empty sets.
*/
@Since("2.2.0")
override def transform(dataset: Dataset[_]): DataFrame = {
transformSchema(dataset.schema, logging = true)
genericTransform(dataset)
}

private def genericTransform[T](dataset: Dataset[_]): DataFrame = {
// use index to perform the join and aggregateByKey, and keep the original order after join.
val indexToItems = dataset.select($(featuresCol)).rdd.map(r => r.getSeq[T](0))
.zipWithIndex().map(_.swap)
val rulesRDD = associationRules.select("antecedent", "consequent").rdd
.map(r => (r.getSeq[T](0), r.getSeq[T](1)))

val indexToConsequents = indexToItems.cartesian(rulesRDD).map {
case ((id, items), (antecedent, consequent)) =>
val consequents = if (items != null) {
val itemSet = items.toSet
if (antecedent.forall(itemSet.contains)) {
consequent.filterNot(itemSet.contains)
} else {
Seq.empty
}
} else {
Seq.empty
}
(id, consequents)
}.aggregateByKey(new ArrayBuffer[T])((ar, seq) => ar ++= seq, (ar, seq) => ar ++= seq)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

How about using an OpenHashSet here to avoid collecting duplicates during aggregation?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I tried OpenHashSet and it's about %15 slower than ArrayBuffer.

.aggregateByKey(new OpenHashSet[T])((set, seq) => {
seq.foreach(t => set.add(t))
set
} , (set1, set2) => set1.union(set2))

@jkbradley jkbradley Feb 23, 2017

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Huh, that's surprising to me. Maybe it depends on how many duplicates are introduced. Let's leave it as is then.

Just curious: What dataset did you test it on?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

random number... The duplicate number should be small.

.map { case (index, cons) => (index, cons.distinct) }

val rowAndConsequents = dataset.toDF().rdd.zipWithIndex().map(_.swap)
.join(indexToConsequents)
.map(_._2).map(t => Row.merge(t._1, Row(t._2)))
val mergedSchema = dataset.schema.add(StructField($(predictionCol),
dataset.schema($(featuresCol)).dataType, dataset.schema($(featuresCol)).nullable))
dataset.sparkSession.createDataFrame(rowAndConsequents, mergedSchema)
}

@Since("2.2.0")
override def transformSchema(schema: StructType): StructType = {
validateAndTransformSchema(schema)
}

@Since("2.2.0")
override def copy(extra: ParamMap): FPGrowthModel = {
val copied = new FPGrowthModel(uid, freqItemsets)
copyValues(copied, extra).setParent(this.parent)
}

@Since("2.2.0")
override def write: MLWriter = new FPGrowthModel.FPGrowthModelWriter(this)
}

@Since("2.2.0")
object FPGrowthModel extends MLReadable[FPGrowthModel] {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Add Since annotation to object


@Since("2.2.0")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

newline

override def read: MLReader[FPGrowthModel] = new FPGrowthModelReader

@Since("2.2.0")
override def load(path: String): FPGrowthModel = super.load(path)

/** [[MLWriter]] instance for [[FPGrowthModel]] */
private[FPGrowthModel]
class FPGrowthModelWriter(instance: FPGrowthModel) extends MLWriter {

override protected def saveImpl(path: String): Unit = {
DefaultParamsWriter.saveMetadata(instance, path, sc)
val dataPath = new Path(path, "data").toString
instance.freqItemsets.write.parquet(dataPath)
}
}

private class FPGrowthModelReader extends MLReader[FPGrowthModel] {

/** Checked against metadata when loading model */
private val className = classOf[FPGrowthModel].getName

override def load(path: String): FPGrowthModel = {
val metadata = DefaultParamsReader.loadMetadata(path, sc, className)
val dataPath = new Path(path, "data").toString
val frequentItems = sparkSession.read.parquet(dataPath)
val model = new FPGrowthModel(metadata.uid, frequentItems)
DefaultParamsReader.getAndSetParams(model, metadata)
model
}
}
}

private[fpm] object AssociationRules {

/**
* Computes the association rules with confidence above minConfidence.
* @param dataset DataFrame("items", "freq") containing frequent itemset obtained from
* algorithms like [[FPGrowth]].
* @param itemsCol column name for frequent itemsets
* @param freqCol column name for frequent itemsets count
* @param minConfidence minimum confidence for the result association rules
* @return a DataFrame("antecedent", "consequent", "confidence") containing the association
* rules.
*/
def getAssociationRulesFromFP[T: ClassTag](
dataset: Dataset[_],
itemsCol: String,
freqCol: String,
minConfidence: Double): DataFrame = {

val freqItemSetRdd = dataset.select(itemsCol, freqCol).rdd
.map(row => new FreqItemset(row.getSeq[T](0).toArray, row.getLong(1)))
val rows = new MLlibAssociationRules()
.setMinConfidence(minConfidence)
.run(freqItemSetRdd)
.map(r => Row(r.antecedent, r.consequent, r.confidence))

val dt = dataset.schema(itemsCol).dataType
val schema = StructType(Seq(
StructField("antecedent", dt, nullable = false),
StructField("consequent", dt, nullable = false),
StructField("confidence", DoubleType, nullable = false)))
val rules = dataset.sparkSession.createDataFrame(rows, schema)
rules
}
}
Loading