ナイーブベイズ - spark.mllib

ナイーブベイズ は特徴の各ペア間の独立性を仮定する、単純な多クラス分類アルゴリズムです。ナイーブベイズはとても効率的に訓練することができます。Within a single pass to the training data, it computes the conditional probability distribution of each feature given label, and then it applies Bayes’ theorem to compute the conditional probability distribution of label given an observation and use it for prediction.

spark.mllib多項ナイーブベイズ および ベルヌーイナイーブベイズをサポートします。これらの漏れるは一般的に文章の分類に使われます。Within that context, each observation is a document and each feature represents a term whose value is the frequency of the term (in multinomial naive Bayes) or a zero or one indicating whether the term was found in the document (in Bernoulli naive Bayes). 特徴値は非負数でなければなりません。モデルのタイプは任意のパラメータ"multinomial" あるいは"bernoulli"を使って選択されます。デフォルトは"multinomial"です。パラメータ $\lambda$ (デフォルトは $1.0$)を設定することで加法スムージング を使うことができます。文章の分類の場合、入力特徴ベクトルは通常sparse で、まばらさを利用するために入力としてsparseベクトルが提供されなければなりません。訓練データは一度しか使われないため、それをキャッシュする必要はありません。

NaiveBayes は多項ナイーブベイズを実装します。LabeledPointのRDDと任意のスムージングパラメータlambda を入力として、任意のモデルのタイプパラメータ(デフォルトは"multinomial")を取り、評価および予想のために使用することができるNaiveBayesModelを出力します。

APIの詳細はNaiveBayes Scala ドキュメント および NaiveBayesModel Scala ドキュメント を参照してください。

import org.apache.spark.mllib.classification.{NaiveBayes, NaiveBayesModel}
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint

val data = sc.textFile("data/mllib/sample_naive_bayes_data.txt")
val parsedData = data.map { line =>
  val parts = line.split(',')
  LabeledPoint(parts(0).toDouble, Vectors.dense(parts(1).split(' ').map(_.toDouble)))
}

// Split data into training (60%) and test (40%).
val splits = parsedData.randomSplit(Array(0.6, 0.4), seed = 11L)
val training = splits(0)
val test = splits(1)

val model = NaiveBayes.train(training, lambda = 1.0, modelType = "multinomial")

val predictionAndLabel = test.map(p => (model.predict(p.features), p.label))
val accuracy = 1.0 * predictionAndLabel.filter(x => x._1 == x._2).count() / test.count()

// Save and load model
model.save(sc, "target/tmp/myNaiveBayesModel")
val sameModel = NaiveBayesModel.load(sc, "target/tmp/myNaiveBayesModel")
例の完全なコードは Spark のリポジトリの "examples/src/main/scala/org/apache/spark/examples/mllib/NaiveBayesExample.scala" で見つかります。

NaiveBayes は多項ナイーブベイズを実装します。LabeledPointのScala RDDと任意のスムージングパラメータlambda を入力として取り、評価および予想のために使用することができるNaiveBayesModelを出力します。

APIの詳細はNaiveBayes Java ドキュメント および NaiveBayesModel Java ドキュメント を参照してください。

import scala.Tuple2;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.mllib.classification.NaiveBayes;
import org.apache.spark.mllib.classification.NaiveBayesModel;
import org.apache.spark.mllib.regression.LabeledPoint;
import org.apache.spark.mllib.util.MLUtils;

String path = "data/mllib/sample_naive_bayes_data.txt";
JavaRDD<LabeledPoint> inputData = MLUtils.loadLibSVMFile(jsc.sc(), path).toJavaRDD();
JavaRDD<LabeledPoint>[] tmp = inputData.randomSplit(new double[]{0.6, 0.4}, 12345);
JavaRDD<LabeledPoint> training = tmp[0]; // training set
JavaRDD<LabeledPoint> test = tmp[1]; // test set
final NaiveBayesModel model = NaiveBayes.train(training.rdd(), 1.0);
JavaPairRDD<Double, Double> predictionAndLabel =
  test.mapToPair(new PairFunction<LabeledPoint, Double, Double>() {
    @Override
    public Tuple2<Double, Double> call(LabeledPoint p) {
      return new Tuple2<Double, Double>(model.predict(p.features()), p.label());
    }
  });
double accuracy = predictionAndLabel.filter(new Function<Tuple2<Double, Double>, Boolean>() {
  @Override
  public Boolean call(Tuple2<Double, Double> pl) {
    return pl._1().equals(pl._2());
  }
}).count() / (double) test.count();

// Save and load model
model.save(jsc.sc(), "target/tmp/myNaiveBayesModel");
NaiveBayesModel sameModel = NaiveBayesModel.load(jsc.sc(), "target/tmp/myNaiveBayesModel");
例の完全なコードは Spark のリポジトリの "examples/src/main/java/org/apache/spark/examples/mllib/JavaNaiveBayesExample.java" で見つかります。

NaiveBayes は多項ナイーブベイズを実装します。LabeledPointのRDDと任意のスムージングパラメータlambda を入力として取り、評価および予想のために使用することができるNaiveBayesModelを出力します。

Python API はまだモデルの保存/ロードをサポートしていませんが、将来的にサポートされるでしょう。

APIについての詳細はNaiveBayes Python ドキュメント およびNaiveBayesModel Python ドキュメントを参照してください。

from pyspark.mllib.classification import NaiveBayes, NaiveBayesModel
from pyspark.mllib.linalg import Vectors
from pyspark.mllib.regression import LabeledPoint


def parseLine(line):
    parts = line.split(',')
    label = float(parts[0])
    features = Vectors.dense([float(x) for x in parts[1].split(' ')])
    return LabeledPoint(label, features)

data = sc.textFile('data/mllib/sample_naive_bayes_data.txt').map(parseLine)

# Split data aproximately into training (60%) and test (40%)
training, test = data.randomSplit([0.6, 0.4], seed=0)

# Train a naive Bayes model.
model = NaiveBayes.train(training, 1.0)

# Make prediction and test accuracy.
predictionAndLabel = test.map(lambda p: (model.predict(p.features), p.label))
accuracy = 1.0 * predictionAndLabel.filter(lambda (x, v): x == v).count() / test.count()

# Save and load model
model.save(sc, "target/tmp/myNaiveBayesModel")
sameModel = NaiveBayesModel.load(sc, "target/tmp/myNaiveBayesModel")
例の完全なコードは Spark のリポジトリの "examples/src/main/python/mllib/naive_bayes_example.py" で見つかります。
TOP
inserted by FC2 system