一, jar依赖,jsc创建。

package ML.BasicStatistics;

import com.google.common.collect.Lists;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaDoubleRDD;
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.api.java.function.DoubleFlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.mllib.linalg.Matrices;
import org.apache.spark.mllib.linalg.Matrix;
import org.apache.spark.mllib.linalg.Vector;
import org.apache.spark.mllib.linalg.Vectors;
import org.apache.spark.mllib.regression.LabeledPoint;
import org.apache.spark.mllib.stat.KernelDensity;
import org.apache.spark.mllib.stat.MultivariateStatisticalSummary;
import org.apache.spark.mllib.stat.Statistics;
import org.apache.spark.mllib.stat.test.ChiSqTestResult;
import org.apache.spark.mllib.stat.test.KolmogorovSmirnovTestResult;
import org.apache.spark.mllib.util.MLUtils;
import org.apache.spark.rdd.RDD;
import scala.Tuple2;
import scala.runtime.Statics;
import static org.apache.spark.mllib.random.RandomRDDs.*; import java.util.*; /**
* TODO
*
* @ClassName: BasicStatistics
* @author: DingH
* @since: 2019/4/3 16:11
*/
public class BasicStatistics {
public static void main(String[] args) {
System.setProperty("hadoop.home.dir","E:\\hadoop-2.6.5");
SparkConf conf = new SparkConf().setAppName("BasicStatistics").setMaster("local");
JavaSparkContext jsc = new JavaSparkContext(conf);

二。Summary statistics

        /**
* @Title: Statistics.colStats一个实例MultivariateStatisticalSummary,其中包含按列的max,min,mean,variance和非零数,以及总计数
* Summary statistics:摘要统计
*/
JavaRDD<Vector> parallelize = jsc.parallelize(Arrays.asList(
Vectors.dense(1, 0, 3),
Vectors.dense(2, 0, 4),
Vectors.dense(3, 0, 5)
));
MultivariateStatisticalSummary summary = Statistics.colStats(parallelize.rdd());
System.out.println(summary.mean());
System.out.println(summary.variance());
System.out.println(summary.numNonzeros());

三。Correlations:相关性

        /**
* @Title: Correlations:相关性
*/
JavaRDD<Tuple2<String, String>> parallelize = jsc.parallelize(Lists.newArrayList(
new Tuple2<String, String>("cat", "11"),
new Tuple2<String, String>("dog", "22"),
new Tuple2<String, String>("cat", "33"),
new Tuple2<String, String>("pig", "44") )); JavaDoubleRDD seriesX = parallelize.mapPartitionsToDouble(new DoubleFlatMapFunction<Iterator<Tuple2<String, String>>>() {
public Iterable<Double> call(Iterator<Tuple2<String, String>> tuple2Iterator) throws Exception {
ArrayList<Double> strings = new ArrayList<Double>();
while (tuple2Iterator.hasNext()){
strings.add(Double.parseDouble(tuple2Iterator.next()._2));
}
return strings;
}
});
JavaDoubleRDD seriesY = parallelize.mapPartitionsToDouble(new DoubleFlatMapFunction<Iterator<Tuple2<String, String>>>() {
public Iterable<Double> call(Iterator<Tuple2<String, String>> tuple2Iterator) throws Exception {
ArrayList<Double> strings = new ArrayList<Double>();
while (tuple2Iterator.hasNext()){
strings.add(Double.parseDouble(tuple2Iterator.next()._2)+1);
}
return strings;
}
});
//compute the correlation using Pearson's method. Enter "spearman" for Spearman's method. If a
//method is not specified, Pearson's method will be used by default.
double correlation = Statistics.corr(seriesX.srdd(), seriesY.srdd(), "pearson"); JavaRDD<Vector> parallelize11 = jsc.parallelize(Arrays.asList(
Vectors.dense(1, 0, 3),
Vectors.dense(2, 0, 4),
Vectors.dense(3, 0, 5)
));// note that each Vector is a row and not a column
Matrix correlation2 = Statistics.corr(parallelize11.rdd(), "spearman");
System.out.println(correlation2);

三,Stratified sampling:分层抽样

        /**
* @Title: Stratified sampling:分层抽样
*/
JavaRDD<Tuple2<String, String>> parallelize = jsc.parallelize(Lists.newArrayList(
new Tuple2<String, String>("cat", "11"),
new Tuple2<String, String>("dog", "22"),
new Tuple2<String, String>("cat", "33"),
new Tuple2<String, String>("pig", "44") ));
JavaPairRDD data = parallelize.mapToPair(new PairFunction<Tuple2<String, String>, String, String>() {
public Tuple2<String, String> call(Tuple2<String, String> stringStringTuple2) throws Exception {
return new Tuple2<String, String>(stringStringTuple2._1, stringStringTuple2._2);
}
}); // an RDD of any key value pairs
Map<String, Double> fractions = new HashMap<String, Double>(); // specify the exact fraction desired from each key
fractions.put("cat",0.5); //对于每个key取值的概率
fractions.put("dog",0.8);
fractions.put("pig",0.8);
// Get an exact sample from each stratum
JavaPairRDD approxSample = data.sampleByKey(false, fractions);
JavaPairRDD exactSample = data.sampleByKeyExact(false, fractions);
approxSample.foreach(new VoidFunction() {
public void call(Object o) throws Exception {
System.out.println(o);
}
});

四。Hypothesis testing  假设检验

        /**
* @Title: Hypothesis testing 假设检验
*/ Vector vec = Vectors.dense(1,2,3,4); // a vector composed of the frequencies of events // compute the goodness of fit. If a second vector to test against is not supplied as a parameter,
// the test runs against a uniform distribution.
ChiSqTestResult goodnessOfFitTestResult = Statistics.chiSqTest(vec);
// summary of the test including the p-value, degrees of freedom, test statistic, the method used,
// and the null hypothesis.
System.out.println(goodnessOfFitTestResult); Matrix mat = Matrices.dense(3,2,new double[]{1,2,3,4,5,6}); // a contingency matrix // conduct Pearson's independence test on the input contingency matrix
ChiSqTestResult independenceTestResult = Statistics.chiSqTest(mat);
// summary of the test including the p-value, degrees of freedom...
System.out.println(independenceTestResult); JavaRDD<LabeledPoint> obs = MLUtils.loadLibSVMFile(jsc.sc(), "/data...").toJavaRDD(); // an RDD of labeled points // The contingency table is constructed from the raw (feature, label) pairs and used to conduct
// the independence test. Returns an array containing the ChiSquaredTestResult for every feature
// against the label.
ChiSqTestResult[] featureTestResults = Statistics.chiSqTest(obs.rdd());
int i = 1;
for (ChiSqTestResult result : featureTestResults) {
System.out.println("Column " + i + ":");
System.out.println(result); // summary of the test
i++;
} JavaDoubleRDD data = jsc.parallelizeDoubles(Arrays.asList(0.2, 1.0,0.3));
KolmogorovSmirnovTestResult testResult = Statistics.kolmogorovSmirnovTest(data,"norm");
// summary of the test including the p-value, test statistic,
// and null hypothesis
// if our p-value indicates significance, we can reject the null hypothesis
System.out.println(testResult);

五。Random data generation

         /**
* @Title: Random data generation :uniform, standard normal, or Poisson.
*/ JavaDoubleRDD u = normalJavaRDD(jsc, 100,2);
// Apply a transform to get a random double RDD following `N(1, 4)`.
JavaRDD<Double> map = u.map(new Function<Double, Double>() {
public Double call(Double aDouble) throws Exception {
return 1.0 + 2.0 * aDouble;
}
});
map.foreach(new VoidFunction<Double>() {
public void call(Double aDouble) throws Exception {
System.out.println(aDouble);
}
});

六。Kernel density estimation

        /**
* @Title: Kernel density estimation
*/
JavaRDD<Double> data = jsc.parallelize(Arrays.asList(1.0, 2.0, 3.0));// an RDD of sample data // Construct the density estimator with the sample data and a standard deviation for the Gaussian
// kernels
KernelDensity kd = new KernelDensity()
.setSample(data)
.setBandwidth(3.0); // Find density estimates for the given values
double[] densities = kd.estimate(new double[] {-1.0, 2.0, 5.0});
for (int i = 0; i < densities.length; i++) {
System.out.println(densities[i]);
}

spark MLlib BasicStatistics 统计学基础的更多相关文章

  1. spark MLLib的基础统计部分学习

    参考学习链接:http://www.itnose.net/detail/6269425.html 机器学习相关算法,建议初学者去看看斯坦福的机器学习课程视频:http://open.163.com/s ...

  2. 【原创 Hadoop&Spark 动手实践 12】Spark MLLib 基础、应用与信用卡欺诈检测系统动手实践

    [原创 Hadoop&Spark 动手实践 12]Spark MLLib 基础.应用与信用卡欺诈检测系统动手实践

  3. Spark MLlib 机器学习

    本章导读 机器学习(machine learning, ML)是一门涉及概率论.统计学.逼近论.凸分析.算法复杂度理论等多领域的交叉学科.ML专注于研究计算机模拟或实现人类的学习行为,以获取新知识.新 ...

  4. 《Spark MLlib机器学习实践》内容简介、目录

      http://product.dangdang.com/23829918.html Spark作为新兴的.应用范围最为广泛的大数据处理开源框架引起了广泛的关注,它吸引了大量程序设计和开发人员进行相 ...

  5. Spark MLlib 之 Basic Statistics

    Spark MLlib提供了一些基本的统计学的算法,下面主要说明一下: 1.Summary statistics 对于RDD[Vector]类型,Spark MLlib提供了colStats的统计方法 ...

  6. Spark MLlib - Decision Tree源码分析

    http://spark.apache.org/docs/latest/mllib-decision-tree.html 以决策树作为开始,因为简单,而且也比较容易用到,当前的boosting或ran ...

  7. Spark入门实战系列--8.Spark MLlib(上)--机器学习及SparkMLlib简介

    [注]该系列文章以及使用到安装包/测试数据 可以在<倾情大奉送--Spark入门实战系列>获取 .机器学习概念 1.1 机器学习的定义 在维基百科上对机器学习提出以下几种定义: l“机器学 ...

  8. Spark入门实战系列--8.Spark MLlib(下)--机器学习库SparkMLlib实战

    [注]该系列文章以及使用到安装包/测试数据 可以在<倾情大奉送--Spark入门实战系列>获取 .MLlib实例 1.1 聚类实例 1.1.1 算法说明 聚类(Cluster analys ...

  9. Spark MLlib知识点学习整理

    MLlib的设计原理:把数据以RDD的形式表示,然后在分布式数据集上调用各种算法.MLlib就是RDD上一系列可供调用的函数的集合. 操作步骤: 1.用字符串RDD来表示信息. 2.运行MLlib中的 ...

随机推荐

  1. 总线复习之SPI

    SPI总线协议以ds1302为例讲解 1.1概述. 1.2根据时序图来分析. 1.3再熟读一下DS1302的数据手册和SPI总线协议的使用. 1.4结合ds1302功能实现一定的功能. 1.1概述SP ...

  2. JavaScript- BOM, DOM

    BOM Browser Object Model 浏览器对象模型, 提供与浏览器窗口进行交互的方法 它使 JavaScript 有能力与浏览器进行“对话”. BOM 最主要的对象就是 window 对 ...

  3. python学习日记(OOP访问限制)

    在Class内部,可以有属性和方法,而外部代码可以通过直接调用实例变量的方法来操作数据,这样,就隐藏了内部的复杂逻辑. 但是,从前面Student类的定义来看,外部代码还是可以自由地修改一个实例的na ...

  4. <数据结构基础学习>(三)Part 2 队列

    一.队列 Queue 队列也是一种线性结构 相比数组,队列对应的操作是数组的子集 只能从一端(队尾)添加元素,只能从另一端(队首)取出元素. (排队) 队列是一种先进先出的数据结构(先到先得)FIFO ...

  5. JDK动态代理(Proxy)的两种实现方式

    JDK自带的Proxy动态代理两种实现方式 前提条件:JDK Proxy必须实现对象接口 so,创建一个接口文件,一个实现接口对象,一个动态代理文件 接口文件:TargetInterface.java ...

  6. 常用js方法整理(个人)

    开头总要有点废话 今天想了下,还是分享下自己平时积累的一些实用性较高的js方法,供大家指点和评价.本想分篇介绍,发现有点画蛇添足.整理了下也没多少拿得出手的方法,自然有一些是网上看到的个人觉得很有实用 ...

  7. Access-Control-Allow-Origin跨域请求处理

    今天在看新项目的时候,发现很多的   Controller 中都有一个 response.setHeader("Access-Control-Allow-Origin"," ...

  8. TensorFlow迁移学习的识别花试验

    最近学习了TensorFlow,发现一个模型叫vgg16,然后搭建环境跑了一下,觉得十分神奇,而且准确率十分的高.又上了一节选修课,关于人工智能,老师让做一个关于人工智能的试验,于是觉得vgg16很不 ...

  9. 从Socket入门到BIO,PIO,NIO,multiplexing,AIO(未完待续)

    Socket入门 最简单的Server端读取Client端内容的demo public class Server { public static void main(String [] args) t ...

  10. 关于java集合的练习

    关于java集合的练习 练习一:Collection集合练习 一.产生10个1-100的随机数,并放到一个数组中,把数组中大于等于10的数字放到一个list集合中,并打印到控制台. public cl ...