一, 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. CentOS 7安装MongoDB

    1 下载安装包 wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-3.2.4.tgz 2 解压 .tgz 3 将解压包 ...

  2. Go语言公开或未公开的标识符

    Go语言公开或未公开的标识符的基本概念 Go语言支持从包里公开或者隐藏标志符,通过这个特性,可以让用户按照自己的规则控制标识符的可见性. Go语言中的可见性,是通过声明类型的大小写来进行区别的. 例如 ...

  3. 来自多校的一个题——数位DP+卡位

    n<=1e9就要考虑倍增.矩阵乘法这种了 假设L=0 考虑枚举二进制下,所有X与R的LCP长度,前len高位 对于第len+1位,假设R的这一位是1 如果一个x的这一位是0了,那么后面可以随便填 ...

  4. Pandas系列(五)-分类数据处理

    内容目录 1. 创建对象 2. 常用操作 3. 内存使用量的陷阱 一.创建对象 1.基本概念:分类数据直白来说就是取值为有限的,或者说是固定数量的可能值.例如:性别.血型. 2.创建分类数据:这里以血 ...

  5. 版本控制工具之git

    git存储区域详解 命令快速总结 初始化 git init 当前文件夹初始化 代码提交 git add file/. 自动检测工作区修改的内容提交到暂存区 git status 查看当前文件夹工作区的 ...

  6. go 的包

  7. mysql 端口修改

    mysql 修改端口 1.  停止mysql服务 2.  打开文件夹下my.ini文件.(E:\mysql-5.7-3307) 修改文件中的port值,注意两个地方: [client]default- ...

  8. 第十一节: EF的三种模式(一) 之 DBFirst模式(SQLServer和MySQL两套方案)

    一. 简介 EF连接数据库有三种模式,分别是DBFirst.ModelFirst.CodeFirst,分别适用于不同的开发场景. 该章节,将主要介绍EF的DBFirst连接SQLServer数据库和M ...

  9. 第二十三节: EF性能篇(三)之基于开源组件 Z.EntityFrameWork.Plus.EF6解决EF性能问题

    一. 开篇说明 EF的性能问题一直以来经常被人所吐槽,究其原因在于“复杂的操作在生成SQL阶段耗时长,且执行效率不高”,但并不是没有办法解决,从EF本身举几个简单的优化例子: ①:如果仅是查询数据,并 ...

  10. [物理学与PDEs]第1章第3节 真空中的 Maxwell 方程组, Lorentz 力 3.2 Lorentz 力

    1. Lorentz 假定, 不论带电体的运动状态如何, 其所受的力密度 (单位体积所受的力) 为 $$\bex {\bf F}=\rho {\bf E}+{\bf j}\times{\bf B} = ...