10.3.6 ore.rowApply関数の使用
ore.rowApply関数は、入力データとしてore.frameを指定してRスクリプトをコールします。
ore.rowApply関数は、ore.frameを最初の引数としてユーザー定義の入力関数に渡します。ore.rowApply関数に対するrows引数には、ユーザー定義のR関数の呼出しごとに渡す行の数を指定します。最後のチャンクまたは行は、指定した数より少なくなる可能性があります。ore.rowApply関数は、1つ以上のRエンジンが同じR関数(タスク)をデータの別のパーティションで実行するデータ・パラレル実行を使用できます。
ore.rowApply関数の構文は次のとおりです。
ore.rowApply(X, FUN, ..., FUN.VALUE = NULL, FUN.NAME = NULL, rows = 1,
FUN.OWNER = NULL, parallel = getOption("ore.parallel", NULL))ore.rowApply関数は、ore.listオブジェクトまたはore.frameオブジェクトを返します。
例10-11 ore.rowApply関数の使用方法
この例では、事前にCRANからダウンロードしてあるe1071パッケージを使用します。この例では、次の操作を実行しています。
-
パッケージ
e1071をロードします。 -
irisデータセットをIRIS一時表およびore.frameオブジェクトとしてデータベースにプッシュします。 -
Naive Bayesモデル
nbmodを作成します。 -
IRISをIRIS_PREDとしてコピーし、予測を含めるためにPRED列をIRIS_PREDに追加します。 -
ore.rowApply関数をコールし、IRISore.frameをユーザー定義R関数のデータソースおよびユーザー定義R関数自体として渡します。ユーザー定義の関数は、次のことを実行します。-
パッケージ
e1071を、データベース内で稼働するRエンジンまたはエンジンで使用できるようにロードします。 -
ore.frameはファクタを定義しますが、ユーザー定義の関数にロードされたときにファクタが文字列ベクターとして表示されるため、Species列をファクタに変換します。 -
predictメソッドをコールし、データセットに追加された列に予測が含まれているresオブジェクトを返します。
-
-
モデルをクライアントのRセッションにプルします。
-
IRIS_PREDを引数FUN.VALUEとして渡しますが、この引数にore.rowApply関数が返すオブジェクトの構造を指定します。 -
ユーザー定義関数の呼出しごとに渡す行の数を指定します。
-
resのクラスを表示し、table関数をコールしてSpecies列およびresオブジェクトのPRED列を表示します。
%r
# Create a temporary R data.frame proxy object for the iris data.frame.
IRIS <- ore.push(iris)
# Build a model using a data.frame
mod <- lm(Petal.Length ~ Petal.Width + Sepal.Width + Sepal.Length, data=iris)
# Save the model to the datastore
ore.save(mod, "mod", name="ds-1", overwrite=TRUE)
# Create a user-defined function that loads a model residing in the datastore and scores the model on new data.
scoreLM.1 <- function(dat, dsname){
ore.load(dsname)
dat$Petal.Length_prediction <- predict(mod, newdata = dat)
dat[,c("Petal.Length_prediction","Petal.Length","Species")]
}
# Save the user-defined scoring function in the R script repository.
ore.scriptCreate(name = 'scoreLM.1',
FUN = scoreLM.1,
overwrite = TRUE)
# Run the scoring function in the script repository as well as specifying the desired number of parallel R engines using the parallel argument.
# View the first 6 records of the result.
res1 <- ore.rowApply(IRIS,
scoreLM.1,
dsname = "ds-1",
rows = 10,
parallel = 2)
head(res1)
# Run the function again, this time
res2 <- ore.rowApply(IRIS,
scoreLM.1,
dsname = "ds-1",
rows = 10,
parallel = 2,
FUN.VALUE = data.frame(Petal.Length_prediction=numeric(),
Petal.Length=numeric(),
Species=character()))
class(res2)
出力は、次のようなものです。
表10-8 data.frame: 6 x 3
| Petal.Length_prediction | Petal.Length | Species | |
|---|---|---|---|
| <dbl> | <dbl> | <chr> | |
| 1 | 1.484210 | 1.4 | setosa |
| 2 | 1.661389 | 1.4 | setosa |
| 3 | 1.386358 | 1.3 | setosa |
| 4 | 1.378046 | 1.5 | setosa |
| 5 | 1.346695 | 1.4 | setosa |
| 6 | 1.733905 | 1.7 | setosa |
親トピック: 埋込みRの実行用のRインタフェース