use of org.apache.spark.mllib.classification.LogisticRegressionModel in project java_study by aloyschen.
the class GbdtAndLr method train.
/*
* 获取GBDT模型组合后的特征输入到Lr模型中,训练LR模型
* @param Path: 训练数据路径
*/
public void train(String Path) {
JavaSparkContext jsc = getSc();
ArrayList<ArrayList<Integer>> treeLeafArray = new ArrayList<>();
Dataset<Row> all_data = Preprocessing(jsc, Path);
JavaRDD<LabeledPoint> gbdt_data_labelpoint = load_gbdt_data(all_data);
GradientBoostedTreesModel gbdt = train_gbdt(jsc, gbdt_data_labelpoint);
DecisionTreeModel[] decisionTreeModels = gbdt.trees();
// 获取GBDT每棵树的叶子索引
for (int i = 0; i < this.maxIter; i++) {
treeLeafArray.add(getLeafNodes(decisionTreeModels[i].topNode()));
// System.out.println("叶子索引");
// System.out.println(treeLeafArray.get(i));
}
JavaRDD<LabeledPoint> CombineFeatures = all_data.toJavaRDD().map(line -> {
double[] newvaluesDouble;
double[] features = new double[24];
// 将dataset中每列特征值放入DenseVector中
for (Integer i = 6; i < 18; i++) {
org.apache.spark.mllib.linalg.DenseVector den = null;
if (line.get(i) instanceof org.apache.spark.ml.linalg.Vector) {
den = (DenseVector) Vectors.fromML((org.apache.spark.ml.linalg.DenseVector) line.get(i));
features[i - 6] = den.toArray()[0];
} else {
features[i - 6] = Double.parseDouble(line.get(i).toString());
}
}
DenseVector numerical_vector = new DenseVector(features);
ArrayList<Double> newvaluesArray = new ArrayList<>();
for (int i = 0; i < this.maxIter; i++) {
int treePredict = predictModify(decisionTreeModels[i].topNode(), numerical_vector);
int len = treeLeafArray.get(i).size();
ArrayList<Double> treeArray = new ArrayList<>(len);
// 数组所有值初始化为0,落在的叶子节点至为1
for (int j = 0; j < len; j++) treeArray.add(j, 0d);
treeArray.set(treeLeafArray.get(i).indexOf(treePredict), 1d);
newvaluesArray.addAll(treeArray);
}
for (int i = 18; i < 29; i++) {
SparseVector onehot_data = (SparseVector) Vectors.fromML((org.apache.spark.ml.linalg.SparseVector) line.get(i));
DenseVector cat_data = onehot_data.toDense();
for (int j = 0; j < cat_data.size(); j++) {
newvaluesArray.add(cat_data.apply(j));
}
}
newvaluesDouble = newvaluesArray.stream().mapToDouble(Double::doubleValue).toArray();
DenseVector newdenseVector = new DenseVector(newvaluesDouble);
return (new LabeledPoint(Double.valueOf(line.get(1).toString()), newdenseVector));
});
JavaRDD<LabeledPoint>[] splitsLR = CombineFeatures.randomSplit(new double[] { 0.7, 0.3 });
JavaRDD<LabeledPoint> trainingDataLR = splitsLR[0];
JavaRDD<LabeledPoint> testDataLR = splitsLR[1];
System.out.println("Start train LR");
LogisticRegressionModel LR = new LogisticRegressionWithLBFGS().setNumClasses(2).run(trainingDataLR.rdd()).clearThreshold();
System.out.println("modelLR.weights().size():" + LR.weights().size());
JavaPairRDD<Object, Object> test_LR = testDataLR.mapToPair((PairFunction<LabeledPoint, Object, Object>) labeledPoint -> {
Tuple2<Object, Object> tuple2 = new Tuple2<>(LR.predict(labeledPoint.features()), labeledPoint.label());
return tuple2;
});
BinaryClassificationMetrics test_metrics = new BinaryClassificationMetrics(test_LR.rdd());
double test_auc = test_metrics.areaUnderROC();
System.out.println("test data auc_score:" + test_auc);
JavaPairRDD<Object, Object> train_LR = trainingDataLR.mapToPair((PairFunction<LabeledPoint, Object, Object>) labeledPoint -> {
Tuple2<Object, Object> tuple2 = new Tuple2<>(LR.predict(labeledPoint.features()), labeledPoint.label());
return tuple2;
});
BinaryClassificationMetrics train_metrics = new BinaryClassificationMetrics(train_LR.rdd());
double train_auc = train_metrics.areaUnderROC();
System.out.println("train data auc_score:" + train_auc);
// 不同阈值下的精确度排序,取前十个输出
JavaRDD<Tuple2<Object, Object>> precision = train_metrics.precisionByThreshold().toJavaRDD();
JavaPairRDD<Object, Object> temp = JavaPairRDD.fromJavaRDD(precision);
JavaPairRDD<Object, Object> swap = temp.mapToPair(Tuple2::swap);
JavaPairRDD<Object, Object> precision_sort = swap.sortByKey(false);
System.out.println("Precision by threshold: (Precision, Threshold)");
for (int i = 0; i < 10; i++) {
System.out.println(precision_sort.take(10).toArray()[i]);
}
}
use of org.apache.spark.mllib.classification.LogisticRegressionModel in project spring-boot-quick by vector4wang.
the class EmailFilter method main.
public static void main(String[] args) {
SparkConf conf = new SparkConf().setMaster("local").setAppName("垃圾邮件分类");
JavaSparkContext sc = new JavaSparkContext(conf);
JavaRDD<String> ham = sc.textFile("D:\\githubspace\\springbootquick\\src\\main\\resources\\ham.txt");
JavaRDD<String> spam = sc.textFile("D:\\githubspace\\springbootquick\\src\\main\\resources\\spam.txt");
final HashingTF tf = new HashingTF(10000);
JavaRDD<LabeledPoint> posExamples = spam.map(h -> new LabeledPoint(1, tf.transform(Arrays.asList(h.split(" ")))));
JavaRDD<LabeledPoint> negExamples = ham.map(s -> new LabeledPoint(0, tf.transform(Arrays.asList(s.split(" ")))));
JavaRDD<LabeledPoint> trainingData = posExamples.union(negExamples);
trainingData.cache();
LogisticRegressionWithSGD lrLearner = new LogisticRegressionWithSGD();
LogisticRegressionModel model = lrLearner.run(trainingData.rdd());
Vector posTestExample = tf.transform(Arrays.asList("O M G GET cheap stuff by sending money to ...".split(" ")));
System.out.println(posTestExample.toJson());
Vector negTestExample = tf.transform(Arrays.asList("Hi Dad, I started studying Spark the other ...".split(" ")));
System.out.println("Prediction for positive test example: " + model.predict(posTestExample));
System.out.println("Prediction for negative test example: " + model.predict(negTestExample));
}
use of org.apache.spark.mllib.classification.LogisticRegressionModel in project learning-spark by databricks.
the class MLlib method main.
public static void main(String[] args) {
SparkConf sparkConf = new SparkConf().setAppName("JavaBookExample");
JavaSparkContext sc = new JavaSparkContext(sparkConf);
// Load 2 types of emails from text files: spam and ham (non-spam).
// Each line has text from one email.
JavaRDD<String> spam = sc.textFile("files/spam.txt");
JavaRDD<String> ham = sc.textFile("files/ham.txt");
// Create a HashingTF instance to map email text to vectors of 100 features.
final HashingTF tf = new HashingTF(100);
// Each email is split into words, and each word is mapped to one feature.
// Create LabeledPoint datasets for positive (spam) and negative (ham) examples.
JavaRDD<LabeledPoint> positiveExamples = spam.map(new Function<String, LabeledPoint>() {
@Override
public LabeledPoint call(String email) {
return new LabeledPoint(1, tf.transform(Arrays.asList(email.split(" "))));
}
});
JavaRDD<LabeledPoint> negativeExamples = ham.map(new Function<String, LabeledPoint>() {
@Override
public LabeledPoint call(String email) {
return new LabeledPoint(0, tf.transform(Arrays.asList(email.split(" "))));
}
});
JavaRDD<LabeledPoint> trainingData = positiveExamples.union(negativeExamples);
// Cache data since Logistic Regression is an iterative algorithm.
trainingData.cache();
// Create a Logistic Regression learner which uses the LBFGS optimizer.
LogisticRegressionWithSGD lrLearner = new LogisticRegressionWithSGD();
// Run the actual learning algorithm on the training data.
LogisticRegressionModel model = lrLearner.run(trainingData.rdd());
// Test on a positive example (spam) and a negative one (ham).
// First apply the same HashingTF feature transformation used on the training data.
Vector posTestExample = tf.transform(Arrays.asList("O M G GET cheap stuff by sending money to ...".split(" ")));
Vector negTestExample = tf.transform(Arrays.asList("Hi Dad, I started studying Spark the other ...".split(" ")));
// Now use the learned model to predict spam/ham for new emails.
System.out.println("Prediction for positive test example: " + model.predict(posTestExample));
System.out.println("Prediction for negative test example: " + model.predict(negTestExample));
sc.stop();
}
Aggregations