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
関数をコールし、IRIS
ore.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インタフェース