Contenu connexe
Similaire à Rユーザのためのspark入門
Similaire à Rユーザのためのspark入門 (20)
Plus de Shintaro Fukushima
Plus de Shintaro Fukushima (20)
Rユーザのためのspark入門
- 5. Apache Sparkの概要
■ OSSのインメモリ処理の分散並列基盤.
■ RDDという分散コレクションに対して,
map, filter, reduceなどのデータ処理を繰り返して
目的のデータを得る処理モデル.
※ RDD: Resilient Distributed Dataset
■ 2009年,UC Berkeley(当時)のMatei Zaharia氏が
関数プログラミング言語Scalaを用いて開発.
5
- 18. データの入出力・変換
■ jsonファイル
■ read.df関数で読み込みHiveSQL上のテーブルに
変換
■ SQLによりデータ抽出可能
18
> people <- read.df(sqlContext, “./examples/src/main/resources/
> people.json", "json")
> head(people)
## age name
##1 NA Michael
##2 30 Andy
##3 19 Justin
> printSchema(people)
# root
# |-- age: integer (nullable = true)
# |-- name: string (nullable = true)
- 19. データの入出力・変換
■ Hiveとの連携
■ HDFSに蓄積されたデータの抽出
19
> hiveContext <- sparkRHive.init(sc)
> sql(hiveContext, "CREATE TABLE IF NOT EXISTS src (key INT, value
STRING)")
> sql(hiveContext, "LOAD DATA LOCAL INPATH ‘examples/src/main/
resources/kv1.txt' INTO TABLE src")
> # クエリはHiveQLで表現可能
> results <- hiveContext.sql("FROM src SELECT key, value")
> # 返り値はRのデータフレームで返される
> head(results)
## key value
## 1 238 val_238
## 2 86 val_86
## 3 311 val_311
- 20. DataFrameオブジェクトの作成
■ createDataFrame関数によりRのデータフレームから作成
20
> iris.df <- createDataFrame(sqlContext, iris)
> iris.df
DataFrame[Sepal_Length:double, Sepal_Width:double,
Petal_Length:double, Petal_Width:double, Species:string]
> class(iris.df)
[1] "DataFrame"
attr(,"package")
[1] “SparkR"
> head(iris.df, 3)
Sepal_Length Sepal_Width Petal_Length Petal_Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
- 21. DataFrameオブジェクトの操作
■ 行の抽出(filter関数)
21
> library(magrittr)
> head(filter(iris.df, iris.df$Sepal_Length >= 5.0), 3)
Sepal_Length Sepal_Width Petal_Length Petal_Width Species
1 5.1 3.5 1.4 0.2 setosa
2 5.0 3.6 1.4 0.2 setosa
3 5.4 3.9 1.7 0.4 setosa
> # パイプ処理も可能
> iris.df %>% filter(iris.df$Sepal_Length >= 5.0) %>% head(3)
> # NSE(Non Standard Evaluation)は使えない
> iris.df %>% filter(Sepal_Length >= 5.0) %>% head(3)
以下にエラー filter(., Sepal_Length >= 5) :
引数 'condition' の評価中にエラーが起きました (関数 'filter' に対するメソッ
ドの選択時): エラー: オブジェクト 'Sepal_Length' がありません
magrittrパッケージを使用
(dplyrを読み込むと名前の衝突が起きて,
面倒なことに・・・)
- 22. データフレームの操作
■ 列の抽出
22
> head(select(iris.df, iris.df$Species), 3)
Species
1 setosa
2 setosa
3 setosa
> # パイプ処理も可能
> iris.df %>% select(iris.df$Species) %>% head(3)
> # NSE(Non Standard Evaluation)は使えない
> iris.df %>% select(Species) %>% head(3)
以下にエラー select(., Species) :
引数 'col' の評価中にエラーが起きました (関数 'select' に対するメソッドの選
択時): エラー: オブジェクト 'Species' がありません
- 32. Scalaのファイルを覗いてみる
${SPARK_HOME}/examples/src/main/scala/org/apache/spark/examples/mllib/
DecisionTreeRunner.scala
32
case class Params(
input: String = null,
testInput: String = "",
dataFormat: String = "libsvm",
algo: Algo = Classification,
maxDepth: Int = 5,
impurity: ImpurityType = Gini,
maxBins: Int = 32,
minInstancesPerNode: Int = 1,
minInfoGain: Double = 0.0,
numTrees: Int = 1,
featureSubsetStrategy: String = "auto",
fracTest: Double = 0.2,
useNodeIdCache: Boolean = false,
checkpointDir: Option[String] = None,
checkpointInterval: Int = 10) extends AbstractParams[Params]
def main(args: Array[String]) {
- 33. ランダムフォレストを用いたホールドアウト検定
■ 現状は,あえてSparkRを使う理由はない気がする
33
scala> import org.apache.spark.SparkContext
scala> import org.apache.spark.mllib.tree.RandomForest
scala> import org.apache.spark.mllib.util.MLUtils
scala> import
org.apache.spark.mllib.evaluation.BinaryClassificationMetrics
scala> import org.apache.spark.mllib.evaluation.MulticlassMetrics
scala> // データのロード
scala> val sc = new SparkContext("local", "RandomForest")
scala> val data = MLUtils.loadLibSVMFile(sc,
"data/mllib/sample_libsvm_data.txt")
scala> // 訓練データとテストデータへの分割
scala> val splits = data.randomSplit(Array(0.7, 0.3))
scala> val (trainingData, testData) = (splits(0), splits(1))
- 34. ランダムフォレストを用いたホールドアウト検定
■ 現状は,あえてSparkRを使う理由はないかも
34
scala> // ランダムフォレストを用いた予測モデルの構築
scala> val numClasses = 2 // クラス数
scala> val categoricalFeaturesInfo = Map[Int, Int]() // カテゴリ変数の
情報
scala> val numTrees = 500 // 構築する決定木の個数
scala> val featureSubsetStrategy = "auto" // 特徴量選択のアルゴリズム
scala> val impurity = "gini" // 不純度に用いる指標
scala> val maxDepth = 5 // 木の最大の深さ
scala> val maxBins = 32
scala> val model = RandomForest.trainClassifier(trainingData,
numClasses, categoricalFeaturesInfo, numTrees,
featureSubsetStrategy, impurity, maxDepth, maxBins)
- 35. ランダムフォレストを用いたホールドアウト検定
■ 現状は,あえてSparkRを使う必要はないかも.
35
scala> // テストデータに対する予測モデルの評価
val labelAndPreds = testData.map { point =>
val prediction = model.predict(point.features)
(point.label, prediction)
}
scala> // 混合行列
scala> val metrics = new MulticlassMetrics(labelAndPreds)
scala> metrics.confusionMatrix
res20: org.apache.spark.mllib.linalg.Matrix =
13.0 1.0
0.0 17.0
scala> metrics.precision
res21: Double = 0.9285714
正例と予測
実績が正例
適合率
(precision)