├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── src
└── main
│ └── scala
│ └── ru
│ └── ispras
│ └── pu4spark
│ ├── ProbabilisticClassifierConfig.scala
│ ├── PositiveUnlabeledLearner.scala
│ ├── TraditionalPULearner.scala
│ ├── TwoStepPULearner.scala
│ └── GradualReductionPULearner.scala
├── gradlew.bat
├── README.md
├── gradlew
└── LICENSE
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'pu4spark'
2 |
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ispras/pu4spark/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Mar 11 14:01:32 EAT 2018
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.4.1-bin.zip
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 | *.log
3 |
4 | .idea
5 | build/
6 | out/
7 | .gradle
8 | .cache-*
9 |
10 |
11 | # sbt specific
12 | .cache
13 | .history
14 | .lib/
15 | dist/*
16 | target/
17 | lib_managed/
18 | src_managed/
19 | project/boot/
20 | project/plugins/project/
21 |
22 | # Scala-IDE specific
23 | .scala_dependencies
24 | .worksheet
25 |
26 | #needed for hiveContext
27 | metastore_db
28 |
--------------------------------------------------------------------------------
/src/main/scala/ru/ispras/pu4spark/ProbabilisticClassifierConfig.scala:
--------------------------------------------------------------------------------
1 | package ru.ispras.pu4spark
2 |
3 | import org.apache.spark.ml.classification._
4 | import org.apache.spark.mllib.linalg.Vector
5 |
6 | /**
7 | * @author Nikita Astrakhantsev (astrakhantsev@ispras.ru)
8 | */
9 | sealed trait ProbabilisticClassifierConfig
10 |
11 | case class LogisticRegressionConfig(maxIter: Int = 100,
12 | regParam: Double = 1.0e-8,
13 | elasticNetParam: Double = 0.0)
14 | extends ProbabilisticClassifierConfig {
15 | def build(): ProbabilisticClassifier[Vector, LogisticRegression, LogisticRegressionModel] = {
16 | new LogisticRegression()
17 | .setLabelCol(ProbabilisticClassifierConfig.labelName).setFeaturesCol(ProbabilisticClassifierConfig.featuresName)
18 | .setMaxIter(maxIter).setRegParam(regParam).setElasticNetParam(elasticNetParam)
19 | }
20 | }
21 |
22 | case class RandomForestConfig(numTrees: Int = 512)
23 | extends ProbabilisticClassifierConfig {
24 | def build(): ProbabilisticClassifier[Vector, RandomForestClassifier, RandomForestClassificationModel] = {
25 | new RandomForestClassifier()
26 | .setLabelCol(ProbabilisticClassifierConfig.labelName).setFeaturesCol(ProbabilisticClassifierConfig.featuresName)
27 | .setNumTrees(numTrees)
28 | }
29 | }
30 |
31 | object ProbabilisticClassifierConfig {
32 | val labelName = "label"
33 | val featuresName = "indexedFeatures"
34 | val subclasses = List(classOf[LogisticRegressionConfig], classOf[RandomForestConfig])
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/scala/ru/ispras/pu4spark/PositiveUnlabeledLearner.scala:
--------------------------------------------------------------------------------
1 | package ru.ispras.pu4spark
2 |
3 | import org.apache.spark.sql.DataFrame
4 |
5 | /**
6 | * Performs positive unlabeled (PU) learning, i.e. training a binary classifier in a semi-supervised way
7 | * from only positive and unlabeled examples
8 | *
9 | * @author Nikita Astrakhantsev (astrakhantsev@ispras.ru)
10 | */
11 | trait PositiveUnlabeledLearner {
12 |
13 | /**
14 | * Updates dataframe by applying positive-unlabeled learning (append column with result of classification).
15 | *
16 | * @param df dataframe containing, among others, column with labels and features to be used in PU-learning
17 | * @param labelColumnName name for column containing 1 - positives and 0 - unlabeled marks for each instance
18 | * @param featuresColumnName name for 1 column containing features array (e.g. after VectorAssembler)
19 | * @param finalLabel name for column containing labels of final classification (1 for positive and -1 for negatives)
20 | * @return dataframe with new column corresponding to final classification
21 | */
22 | def weight(df: DataFrame,
23 | labelColumnName: String = "featuresCol",
24 | featuresColumnName: String = "labelCol",
25 | finalLabel: String = "finalLabel"): DataFrame
26 | }
27 |
28 | /**
29 | * Subclasses should be case classes in order to be easily serializable (e.g. to JSON)
30 | */
31 | trait PositiveUnlabeledLearnerConfig {
32 | def build(): PositiveUnlabeledLearner
33 | }
34 |
35 | /**
36 | * Needed for serialization by json4s (should be passed to org.json4s.ShortTypeHints)
37 | */
38 | object PositiveUnlabeledLearnerConfig {
39 | val subclasses = List(classOf[TraditionalPULearnerConfig], classOf[GradualReductionPULearnerConfig])
40 | }
41 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # pu4spark
2 | A library for [Positive-Unlabeled Learning](https://en.wikipedia.org/wiki/One-class_classification#PU_learning)
3 | for Apache Spark MLlib (ml package)
4 |
5 | ## Implemented algorithms
6 |
7 | ### Traditional PU
8 | Original Positive-Unlabeled learning algorithm; firstly proposed in
9 | > Liu, B., Dai, Y., Li, X. L., Lee, W. S., & Philip, Y. (2002).
10 | Partially supervised classification of text documents.
11 | In ICML 2002, Proceedings of the nineteenth international conference on machine learning. (pp. 387–394).
12 |
13 | ### Gradual Reduction PU (aka PU-LEA)
14 | Modified Positive-Unlabeled learning algorithm;
15 | main idea is to gradually refine set of positive examples.
16 | Pseudocode was taken from:
17 | >Fusilier, D. H., Montes-y-Gómez, M., Rosso, P., & Cabrera, R. G. (2015).
18 | Detecting positive and negative deceptive opinions using PU-learning.
19 | Information Processing & Management, 51(4), 433-443.
20 |
21 | ## Requirements
22 |
23 | Spark 1.5+
24 |
25 | (Spark 2+ was not tested,
26 | but should work if replace `SparkContext` by `SparkSession`
27 | and `mllib.linalg.Vector` by `ml.linalg.Vector`)
28 |
29 | ## Linking
30 |
31 | The library is published into Maven central and JCenter.
32 | Add the following lines depending on your build system.
33 |
34 | ### Gradle
35 |
36 | ```gradle
37 | compile 'ru.ispras:pu4spark:0.3'
38 | ```
39 |
40 | ### Maven
41 |
42 | ```xml
43 |
44 | ru.ispras
45 | pu4spark
46 | 0.3
47 |
48 | ```
49 |
50 | ### SBT
51 |
52 | ```
53 | libraryDependencies += "ru.ispras" % "pu4spark" % "0.3"
54 | ```
55 |
56 | ## Building from Sources
57 |
58 | Build library with gradle:
59 |
60 | ```shell
61 | ./gradlew jar
62 | ```
63 |
64 | ## Usage example
65 |
66 |
67 | ```scala
68 | val inputLabelName = "category"
69 | val srcFeaturesName = "srcFeatures"
70 | val outputLabel = "outputLabel"
71 |
72 | val puLearnerConfig = TraditionalPULearnerConfig(0.05, 1, LogisticRegressionConfig())
73 | val puLearner = puLearnerConfig.build()
74 | val df = ... //needed df that contains at least the following columns:
75 | // binary label for positive and unlabel (inputLabelName)
76 | // and features assembled as vector (featuresName)
77 |
78 | val weightedDF = puLearner.weight(preparedDf, inputLabelName, srcFeaturesName, outputLabel)
79 | ```
80 | Returned dataframe contains probability estimation for each instance in the column `outputLabel`.
81 |
82 | Features can be assembled to one column by using [VectorAssembler](https://spark.apache.org/docs/1.6.2/ml-features.html#vectorassembler):
83 | ```scala
84 | val assembler = new VectorAssembler()
85 | .setInputCols(df.columns.filter(c => c != rowName)) //keep here only feature columns
86 | .setOutputCol(featuresName)
87 | val pipeline = new Pipeline().setStages(Array(assembler))
88 | val preparedDf = pipeline.fit(df).transform(df)
89 | ```
90 |
--------------------------------------------------------------------------------
/src/main/scala/ru/ispras/pu4spark/TraditionalPULearner.scala:
--------------------------------------------------------------------------------
1 | package ru.ispras.pu4spark
2 |
3 | import org.apache.logging.log4j.LogManager
4 | import org.apache.spark.ml.classification.{LogisticRegressionModel, ProbabilisticClassificationModel, ProbabilisticClassifier}
5 | import org.apache.spark.mllib.linalg.Vector
6 | import org.apache.spark.sql.DataFrame
7 | import org.apache.spark.sql.functions._
8 |
9 | /**
10 | * Original Positive-Unlabeled learning algorithm; firstly proposed in
11 | * Liu, B., Dai, Y., Li, X. L., Lee, W. S., & Philip, Y. (2002).
12 | * Partially supervised classification of text documents.
13 | * In ICML 2002, Proceedings of the nineteenth international conference on machine learning. (pp. 387–394).
14 | *
15 | * Pseudocode was taken from:
16 | * Fusilier, D. H., Montes-y-Gómez, M., Rosso, P., & Cabrera, R. G. (2015).
17 | * Detecting positive and negative deceptive opinions using PU-learning.
18 | * Information Processing & Management, 51(4), 433-443.
19 | *
20 | * @author Nikita Astrakhantsev (astrakhantsev@ispras.ru)
21 | */
22 | class TraditionalPULearner[
23 | E <: ProbabilisticClassifier[Vector, E, M],
24 | M <: ProbabilisticClassificationModel[Vector, M]](
25 | relNegThreshold: Double,
26 | maxIters: Int,
27 | classifier: ProbabilisticClassifier[Vector, E, M]) extends TwoStepPULearner[E,M](classifier) {
28 | val log = LogManager.getLogger(getClass)
29 |
30 | override def weight(df: DataFrame, labelColumnName: String, featuresColumnName: String, finalLabel: String): DataFrame = {
31 | val oneStepPUDF: DataFrame = zeroStep(df, labelColumnName, featuresColumnName, finalLabel)
32 | .drop("probability").drop("prediction").drop("rawPrediction").drop(ProbabilisticClassifierConfig.labelName)
33 |
34 | val confAdder = new RelNegConfidenceThresholdAdder(relNegThreshold)
35 |
36 | val prevLabel = "prevLabel"
37 | val curLabel = "curLabel"
38 |
39 | // replace all zeros with labels for undefined
40 | var curDF = replaceZerosByUndefLabel(oneStepPUDF, labelColumnName, prevLabel, TraditionalPULearner.undefLabel)
41 |
42 | for (i <- 1 to maxIters) {
43 | //replace weights by binary column for further learning (induce labels for curLabDF)
44 | val curLabelColumn = confAdder.binarizeUDF(curDF(finalLabel), curDF(prevLabel))
45 |
46 | curDF = curDF.withColumn(curLabel, curLabelColumn).cache()
47 | val newRelNegCount = curDF
48 | //unlabeled in previous iterations && negative in current iteration
49 | .filter(curDF(prevLabel) === TraditionalPULearner.undefLabel && curDF(curLabel) === TraditionalPULearner.relNegLabel)
50 | .count()
51 |
52 | log.debug(s"newRelNegCount: $newRelNegCount")
53 | if (newRelNegCount == 0) {
54 | return curDF
55 | }
56 |
57 | //learn new classifier
58 | val curLabDF = curDF.filter(curDF(curLabel) !== TraditionalPULearner.undefLabel) //keep only positives and relnegs
59 |
60 | val newPreparedDf = indexLabelColumn(curLabDF, curLabel, ProbabilisticClassifierConfig.labelName,
61 | Seq(TraditionalPULearner.relNegLabel.toString, "1.0"))
62 |
63 | val model = classifier.fit(newPreparedDf)
64 |
65 | // log.debug(s"Coefficients: ${model.asInstanceOf[LogisticRegressionModel].coefficients} " +
66 | // s"Intercept: ${model.asInstanceOf[LogisticRegressionModel].intercept}")
67 |
68 | //apply classifier to still unlabeled data
69 | val labUnlabDF = model.transform(curDF)
70 | curDF = labUnlabDF.withColumn(finalLabel, getPOne(labUnlabDF("probability")))
71 | .drop("probability").drop("prediction").drop("rawPrediction").drop(ProbabilisticClassifierConfig.labelName)
72 | curDF = curDF.drop(prevLabel)
73 | .withColumnRenamed(curLabel, prevLabel)
74 | }
75 | curDF
76 | }
77 | }
78 |
79 | private class RelNegConfidenceThresholdAdder(threshold: Double) extends Serializable {
80 | def binarize(probPred: Double, prevLabel: Int): Int = if (prevLabel == TraditionalPULearner.undefLabel) { // unlabeled
81 | if (probPred < threshold) {
82 | TraditionalPULearner.relNegLabel
83 | } else {
84 | TraditionalPULearner.undefLabel
85 | }
86 | } else {
87 | prevLabel // keep as it was (positive or reliable negatives, i.e. 1 or 0)
88 | }
89 |
90 | val binarizeUDF = udf(binarize(_: Double, _: Int))
91 | }
92 |
93 | object TraditionalPULearner {
94 | val relNegLabel = 0
95 | val undefLabel = -1
96 | }
97 |
98 | case class TraditionalPULearnerConfig(relNegThreshold: Double = 0.5,
99 | maxIters: Int = 1,
100 | classifierConfig: ProbabilisticClassifierConfig = LogisticRegressionConfig()
101 | ) extends PositiveUnlabeledLearnerConfig {
102 | override def build(): PositiveUnlabeledLearner = {
103 | classifierConfig match {
104 | case lrc: LogisticRegressionConfig => new TraditionalPULearner(relNegThreshold, maxIters, lrc.build())
105 | case rfc: RandomForestConfig => new TraditionalPULearner(relNegThreshold, maxIters, rfc.build())
106 | }
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/main/scala/ru/ispras/pu4spark/TwoStepPULearner.scala:
--------------------------------------------------------------------------------
1 | package ru.ispras.pu4spark
2 |
3 | import org.apache.spark.ml.Pipeline
4 | import org.apache.spark.ml.attribute.NominalAttribute
5 | import org.apache.spark.ml.classification.{ProbabilisticClassificationModel, ProbabilisticClassifier}
6 | import org.apache.spark.ml.feature.VectorIndexer
7 | import org.apache.spark.mllib.linalg.Vector
8 | import org.apache.spark.sql.DataFrame
9 | import org.apache.spark.sql.functions.{col, udf, when}
10 | import org.apache.spark.sql.types.DoubleType
11 |
12 | /**
13 | * Performs PU learning in a 2-step manner:
14 | * on the first step, choose between all unlabeled examples those are negative with high probability
15 | * (so called, reliable negatives),
16 | * so that at the second step use them along with positive examples for training binary classifier.
17 | *
18 | * @author Nikita Astrakhantsev (astrakhantsev@ispras.ru)
19 | */
20 | abstract class TwoStepPULearner[
21 | E <: ProbabilisticClassifier[Vector, E, M],
22 | M <: ProbabilisticClassificationModel[Vector, M]](
23 | classifier: ProbabilisticClassifier[Vector, E, M]) extends PositiveUnlabeledLearner {
24 |
25 | /**
26 | * Extracts probability instead of binary prediction
27 | */
28 | val getPOne = udf((v: Vector) => v(1))
29 |
30 | /**
31 | * Train binary classifier by considering all unlabeled data as negative data,
32 | * then apply it to all unlabeled data in order to have some measure of reliability of these negatives.
33 | *
34 | * @param df dataframe to work with
35 | * @param labelColumnName name for column containing positive or unlabeled label
36 | * @param featuresColumnName name for column containing features as a vector (e.g. after VectorAssembler)
37 | * @param finalLabel name for column that will contain required measure of reliability of these negatives
38 | * @return updated dataframe with finalLabel column
39 | */
40 | def zeroStep(df: DataFrame, labelColumnName: String, featuresColumnName: String, finalLabel: String): DataFrame = {
41 | val dfWithMeta = indexLabelColumn(df, labelColumnName, ProbabilisticClassifierConfig.labelName, Seq("0", "1"))
42 |
43 | //scaler seems to not improve results
44 | //StandardScaler with mean scaling requires DenseVectors, while VectorAssembler can return only SparseVectors
45 | // val scaler = new MinMaxScaler().setInputCol(srcFeaturesName).setOutputCol(scaledFeaturesName)
46 |
47 | // RF requires that (from Spark example, 'Automatically identify categorical features, and index them')
48 | val featureIndexer = new VectorIndexer()
49 | .setInputCol(featuresColumnName)
50 | .setOutputCol(ProbabilisticClassifierConfig.featuresName)
51 | .setMaxCategories(4) //features with > 4 distinct values are treated as continuous.
52 |
53 | val pipeline = new Pipeline().setStages(Array(featureIndexer))
54 | val preparedDf = pipeline.fit(dfWithMeta).transform(dfWithMeta)
55 |
56 | val model: M = classifier.fit(preparedDf)
57 | val predictions: DataFrame = model.transform(preparedDf)
58 | val res = predictions.withColumn(finalLabel, getPOne(predictions("probability")))
59 | res
60 | }
61 |
62 | /**
63 | * Adds meta-information to label column and casts it to DoubleType, so that it can be used for training.
64 | * StringIndexer can't be used, because it assigns index based on labels frequency.
65 | *
66 | *
67 | * @param df dataframe to index label
68 | * @param inputCol name of column with original label
69 | * @param outputCol name of column with indexed label
70 | * @param values labels to support
71 | * @return dataframe with indexed label
72 | */
73 | def indexLabelColumn(df: DataFrame, inputCol: String, outputCol: String, values: Seq[String]): DataFrame = {
74 | val meta = NominalAttribute
75 | .defaultAttr
76 | .withName(inputCol)
77 | .withValues(values.head, values.tail: _*)
78 | .toMetadata
79 |
80 | df.withColumn(outputCol, col(inputCol).as(outputCol, meta).cast(DoubleType))
81 | }
82 |
83 | /**
84 | * Replaces one value in column by another and renames this column.
85 | * It is used to change labels from zero to special value indicating undefined.
86 | *
87 | * @param df dataframe to replace value
88 | * @param origColName name of column with original label
89 | * @param newColName name of column with replaced label
90 | * @param value2replace value from that column that should be used instead of existing value
91 | * (i.e. if the value differs from value2keep, than it would be replaced by value2replace
92 | * @param value2keep value that should be kept
93 | * @return dataframe with replaced values
94 | */
95 | def replaceZerosByUndefLabel(df: DataFrame,
96 | origColName: String,
97 | newColName: String,
98 | value2replace: Double,
99 | value2keep: Double = 1): DataFrame = {
100 | df.withColumn(newColName,
101 | when(col(origColName).equalTo(value2keep), value2keep).otherwise(value2replace))
102 | .drop(origColName)
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/src/main/scala/ru/ispras/pu4spark/GradualReductionPULearner.scala:
--------------------------------------------------------------------------------
1 | package ru.ispras.pu4spark
2 |
3 | import org.apache.logging.log4j.LogManager
4 | import org.apache.spark.ml.classification.{ProbabilisticClassificationModel, ProbabilisticClassifier}
5 | import org.apache.spark.mllib.linalg.Vector
6 | import org.apache.spark.sql.DataFrame
7 | import org.apache.spark.sql.functions._
8 |
9 | /**
10 | * Modified Positive-Unlabeled learning algorithm; main idea is to gradually refine set of positive examples
11 | *
12 | * Pseudocode was taken from:
13 | * Fusilier, D. H., Montes-y-Gómez, M., Rosso, P., & Cabrera, R. G. (2015).
14 | * Detecting positive and negative deceptive opinions using PU-learning.
15 | * Information Processing & Management, 51(4), 433-443.
16 | *
17 | * @author Nikita Astrakhantsev (astrakhantsev@ispras.ru)
18 | */
19 | class GradualReductionPULearner[
20 | E <: ProbabilisticClassifier[Vector, E, M],
21 | M <: ProbabilisticClassificationModel[Vector, M]](
22 | relNegThreshold: Double,
23 | classifier: ProbabilisticClassifier[Vector, E, M]) extends TwoStepPULearner[E,M](classifier) {
24 |
25 | val log = LogManager.getLogger(getClass)
26 |
27 | override def weight(df: DataFrame, labelColumnName: String, featuresColumnName: String, finalLabel: String): DataFrame = {
28 | val oneStepPUDF: DataFrame = zeroStep(df, labelColumnName, featuresColumnName, finalLabel)
29 | .drop("probability").drop("prediction").drop("rawPrediction").drop(ProbabilisticClassifierConfig.labelName)
30 |
31 | val prevLabel = "prevLabel"
32 | val curLabel = "curLabel"
33 | var curDF = replaceZerosByUndefLabel(oneStepPUDF, labelColumnName, prevLabel, GradualReductionPULearner.undefLabel)
34 |
35 | val confAdder = new GradRelNegConfidenceThresholdAdder(relNegThreshold, GradualReductionPULearner.undefLabel)
36 |
37 | //replace weights by binary column for further learning (induce labels for curLabDF)
38 | val curLabelColumn = confAdder.binarizeUDF(curDF(finalLabel), curDF(prevLabel))
39 |
40 | curDF = curDF.withColumn(curLabel, curLabelColumn).cache()
41 | var newRelNegCount = curDF
42 | //unlabeled in previous iterations && negative in current iteration
43 | .filter(curDF(prevLabel) === GradualReductionPULearner.undefLabel && curDF(curLabel) === GradualReductionPULearner.relNegLabel)
44 | .count()
45 |
46 | log.debug(s"newRelNegCount: $newRelNegCount")
47 | var prevNewRelNegCount = newRelNegCount
48 | val totalPosCount = curDF.filter(curDF(curLabel) === GradualReductionPULearner.posLabel).count()
49 | var totalRelNegCount = curDF.filter(curDF(curLabel) === GradualReductionPULearner.relNegLabel).count()
50 |
51 | var prevGain = Long.MaxValue
52 | var curGain = newRelNegCount
53 |
54 | do {
55 | //learn new classifier
56 | val curLabDF = curDF.filter(curDF(curLabel) !== GradualReductionPULearner.undefLabel)
57 |
58 | val newPreparedDf = indexLabelColumn(curLabDF, curLabel, ProbabilisticClassifierConfig.labelName,
59 | Seq(GradualReductionPULearner.relNegLabel.toString, GradualReductionPULearner.posLabel.toString))
60 |
61 | val model = classifier.fit(newPreparedDf)
62 |
63 | //apply classifier to all data (however, we are interested in ReliableNegatives data only, see confAdder)
64 | val labUnlabDF = model.transform(curDF)
65 | curDF = labUnlabDF.withColumn(finalLabel, getPOne(labUnlabDF("probability")))
66 | .drop("probability").drop("prediction").drop("rawPrediction").drop(ProbabilisticClassifierConfig.labelName)
67 | curDF = curDF.drop(prevLabel)
68 | .withColumnRenamed(curLabel, prevLabel)
69 |
70 | val innerConfAdder = new GradRelNegConfidenceThresholdAdder(relNegThreshold, GradualReductionPULearner.relNegLabel)
71 | val curLabelColumn = innerConfAdder.binarizeUDF(curDF(finalLabel), curDF(prevLabel))
72 |
73 | curDF = curDF.withColumn(curLabel, curLabelColumn).cache()
74 | prevNewRelNegCount = newRelNegCount
75 | newRelNegCount = curDF
76 | //negative in current iteration
77 | .filter(curDF(curLabel) === GradualReductionPULearner.relNegLabel)
78 | .count()
79 | totalRelNegCount = curDF.filter(curDF(curLabel) === GradualReductionPULearner.relNegLabel).count()
80 | prevGain = curGain
81 | curGain = prevNewRelNegCount - totalRelNegCount
82 | log.debug(s"newRelNegCount: $newRelNegCount, prevNewRelNegCount: $prevNewRelNegCount, totalRelNegCount: $totalRelNegCount")
83 | log.debug(s"curGain: $curGain, prevGain: $prevGain")
84 | } while (curGain > 0 && curGain < prevGain && totalPosCount < totalRelNegCount)
85 | curDF
86 | }
87 | }
88 |
89 | private class GradRelNegConfidenceThresholdAdder(threshold: Double, labelToConsider: Int) extends Serializable {
90 | def binarize(probPred: Double, prevLabel: Int): Int = if (prevLabel == labelToConsider) {
91 | if (probPred < threshold) {
92 | GradualReductionPULearner.relNegLabel
93 | } else {
94 | GradualReductionPULearner.undefLabel
95 | }
96 | } else {
97 | prevLabel // keep as it was //(1 or -1 in case of unlabeled classification)
98 | }
99 |
100 | val binarizeUDF = udf(binarize(_: Double, _: Int))
101 | }
102 |
103 | object GradualReductionPULearner {
104 | val relNegLabel = 0
105 | val posLabel = 1
106 | val undefLabel = -1
107 | }
108 |
109 | case class GradualReductionPULearnerConfig(relNegThreshold: Double = 0.5,
110 | classifierConfig: ProbabilisticClassifierConfig) extends PositiveUnlabeledLearnerConfig {
111 | override def build(): PositiveUnlabeledLearner = {
112 | classifierConfig match {
113 | case lrc: LogisticRegressionConfig => new GradualReductionPULearner(relNegThreshold, lrc.build())
114 | case rfc: RandomForestConfig => new GradualReductionPULearner(relNegThreshold, rfc.build())
115 | }
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------