spark mllib之基本数据统计

colStats()返回一个MultivariateStatisticalSummary的实例,它包含列的最大值,最小值,平均值,方差和非零序数,以及总计数。

import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.stat.{MultivariateStatisticalSummary, Statistics}

val observations = sc.parallelize(
  Seq(
    Vectors.dense(1.0, 10.0, 100.0),
    Vectors.dense(2.0, 20.0, 200.0),
    Vectors.dense(3.0, 30.0, 300.0)
  )
)

// Compute column summary statistics.
val summary: MultivariateStatisticalSummary = Statistics.colStats(observations)
println(summary.mean)  // a dense vector containing the mean value for each column
println(summary.variance)  // column-wise variance
println(summary.numNonzeros)  // number of nonzeros in each column
结果
[2.0,20.0,200.0]
[1.0,100.0,10000.0]
[3.0,3.0,3.0]

Correlations
计算两个数据系列之间的相关性是统计学中的常见操作。 在spark.mllib中,我们提供了灵活性来计算许多系列之间的成对相关性。 支持的相关方法是Pearson和Spearman的相关性。
统计学提供了计算系列之间相关性的方法。 根据输入类型,两个RDD [Double]或RDD [Vector]分别输出Double或相关矩阵。

import org.apache.spark.mllib.linalg._
import org.apache.spark.mllib.stat.Statistics
import org.apache.spark.rdd.RDD

val seriesX: RDD[Double] = sc.parallelize(Array(1, 2, 3, 3, 5))  // a series
// must have the same number of partitions and cardinality as seriesX
val seriesY: RDD[Double] = sc.parallelize(Array(11, 22, 33, 33, 555))

// 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.
val correlation: Double = Statistics.corr(seriesX, seriesY, "pearson")
println(s"Correlation is: $correlation")

val data: RDD[Vector] = sc.parallelize(
  Seq(
    Vectors.dense(1.0, 10.0, 100.0),
    Vectors.dense(2.0, 20.0, 200.0),
    Vectors.dense(5.0, 33.0, 366.0))
)  // note that each Vector is a row and not a column

// calculate the correlation matrix using Pearson's method. Use "spearman" for Spearman's method
// If a method is not specified, Pearson's method will be used by default.
val correlMatrix: Matrix = Statistics.corr(data, "pearson")
println(correlMatrix.toString)
1.0                 0.9788834658894731  0.9903895695275673
0.9788834658894731  1.0                 0.9977483233986101
0.9903895695275673  0.9977483233986101  1.0

1.0                 0.9788834658894731  0.9903895695275673
0.9788834658894731  1.0                 0.9977483233986101
0.9903895695275673  0.9977483233986101  1.0

Stratified sampling 分层抽样
与spark.mllib中的其他统计函数不同,可以对键值对的RDD执行分层抽样方法sampleByKey和sampleByKeyExact。 对于分层采样,键可以被认为是一个标签,并且该值作为一个特定属性。 例如,密钥可以是男人或女人,或者文件ID,相应的值可以是人口中的人的年龄列表或文档中的单词列表。 sampleByKey方法将翻转硬币来决定观察是否被采样,因此需要一次通过数据,并提供预期的样本大小。 sampleByKeyExact需要比sampleByKey中使用的每层简单随机抽样更多的资源,但将提供99.99%置信度的确切采样大小。 python当前不支持sampleByKeyExact。
sampleByKeyExact()允许用户精确地采样⌈fk⋅nk⌉∀k∈K⌈fk⋅nk⌉∀k∈K项,其中fkfk是关键字kk的期望分数,nknk是关键字kk的键值对数 ,而KK是一组键。 无需更换的采样需要额外通过RDD以保证样品大小,而带有更换的采样需要两次额外的通过。

val data = sc.parallelize(
  Seq((1, 'a'), (1, 'b'), (2, 'c'), (2, 'd'), (2, 'e'), (3, 'f')))

// specify the exact fraction desired from each key
val fractions = Map(1 -> 0.1, 2 -> 0.6, 3 -> 0.3)

// Get an approximate sample from each stratum
val approxSample = data.sampleByKey(withReplacement = false, fractions = fractions)
// Get an exact sample from each stratum
val exactSample = data.sampleByKeyExact(withReplacement = false, fractions = fractions)
Array[(Int, Char)] = Array((1,b), (2,c), (2,e), (3,f))

Hypothesis testing 假设检验
假设检验是统计学中强大的工具,用于确定结果是否具有统计学意义,无论该结果是否偶然发生。 spark.mllib目前支持Pearson的卡方(χ2χ2)检验,以获得适合度和独立性。 输入数据类型确定是否进行拟合优度或独立性检验。 适合度测试需要输入类型的Vector,而独立性测试需要一个Matrix作为输入。

spark.mllib还支持输入类型RDD [LabeledPoint],通过卡方独立检验来启用特征选择。

import org.apache.spark.mllib.linalg._
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.stat.Statistics
import org.apache.spark.mllib.stat.test.ChiSqTestResult
import org.apache.spark.rdd.RDD

// a vector composed of the frequencies of events
val vec: Vector = Vectors.dense(0.1, 0.15, 0.2, 0.3, 0.25)

// 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.
val goodnessOfFitTestResult = Statistics.chiSqTest(vec)
// summary of the test including the p-value, degrees of freedom, test statistic, the method
// used, and the null hypothesis.
println(s"$goodnessOfFitTestResult\n")

// a contingency matrix. Create a dense matrix ((1.0, 2.0), (3.0, 4.0), (5.0, 6.0))
val mat: Matrix = Matrices.dense(3, 2, Array(1.0, 3.0, 5.0, 2.0, 4.0, 6.0))

// conduct Pearson's independence test on the input contingency matrix
val independenceTestResult = Statistics.chiSqTest(mat)
// summary of the test including the p-value, degrees of freedom
println(s"$independenceTestResult\n")

val obs: RDD[LabeledPoint] =
  sc.parallelize(
    Seq(
      LabeledPoint(1.0, Vectors.dense(1.0, 0.0, 3.0)),
      LabeledPoint(1.0, Vectors.dense(1.0, 2.0, 0.0)),
      LabeledPoint(-1.0, Vectors.dense(-1.0, 0.0, -0.5)
      )
    )
  ) // (feature, label) pairs.

// 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.
val featureTestResults: Array[ChiSqTestResult] = Statistics.chiSqTest(obs)
featureTestResults.zipWithIndex.foreach { case (k, v) =>
  println("Column " + (v + 1).toString + ":")
  println(k)
}  // summary of the test

此外,spark.mllib提供了对于概率分布相等的Kolmogorov-Smirnov(KS)测试1-sample, 2-sided implementation的实现。 通过提供理论分布(目前仅为正态分布支持)及其参数的名称,或根据给定理论分布计算累积分布的函数,用户可以测试其假设,即从 分配。 在用户根据正常分配(distName =“norm”)进行测试但不提供分发参数的情况下,测试将初始化为标准正态分布并记录适当的消息。

Kolmogorov-Smirnov test summary:
degrees of freedom = 0
statistic = 0.9500000000000001
pValue = 6.249999999763389E-7
Very strong presumption against null hypothesis: Sample follows theoretical distribution.

Streaming Significance Testing
spark.mllib提供了一些测试的在线实现,以支持A / B测试等用例。 这些测试可以在Spark Streaming DStream [(Boolean,Double)]上执行,其中每个元组的第一个元素指示控制组(false)或处理组(true),第二个元素是观察值。

流式significance测试支持以下参数:
peacePeriod - 从流中忽略的初始数据点数,用于减轻新奇效应。
windowSize - 执行假设检验的过去批次数。 设置为0将执行所有以前批次的累积处理。

val data = ssc.textFileStream(dataDir).map(line => line.split(",") match {
  case Array(label, value) => BinarySample(label.toBoolean, value.toDouble)
})

val streamingTest = new StreamingTest()
  .setPeacePeriod(0)
  .setWindowSize(0)
  .setTestMethod("welch")

val out = streamingTest.registerStream(data)
out.print()

Random data generation
随机数据生成对于随机算法,原型设计和性能测试很有用。 spark.mllib支持使用i.i.d.生成随机RDD。 从给定分布绘制的值:均匀,标准正常或泊松。
RandomRDD提供工厂方法来生成随机双RDD或向量RDD。 以下示例生成随机双重RDD,其值遵循标准正态分布N(0,1),然后映射到N(1,4)。

import org.apache.spark.SparkContext
import org.apache.spark.mllib.random.RandomRDDs._

val sc: SparkContext = ...

// Generate a random double RDD that contains 1 million i.i.d. values drawn from the
// standard normal distribution `N(0, 1)`, evenly distributed in 10 partitions.
val u = normalRDD(sc, 1000000L, 10)
// Apply a transform to get a random double RDD following `N(1, 4)`.
val v = u.map(x => 1.0 + 2.0 * x)

Kernel density estimation 核密度估计
核心密度估计是一种用于可视化经验概率分布的技术,而不需要对所观察到的样本的特定分布进行假设。 它计算在给定的一组点处评估的随机变量的概率密度函数的估计。 通过将特定点的经验分布的PDF表示为以每个样本为中心的正态分布的PDF的平均值来实现该估计。

KernelDensity提供从RDD样本计算核密度估计的方法。 以下示例演示如何执行此操作。

import org.apache.spark.mllib.stat.KernelDensity
import org.apache.spark.rdd.RDD

// an RDD of sample data
val data: RDD[Double] = sc.parallelize(Seq(1, 1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9))

// Construct the density estimator with the sample data and a standard deviation
// for the Gaussian kernels
val kd = new KernelDensity().setSample(data).setBandwidth(3.0)

// Find density estimates for the given values
val densities = kd.estimate(Array(-1.0, 2.0, 5.0))
 Array[Double] = Array(0.04145944023341913, 0.07902016933085627, 0.08962920127312339)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值