[英]R linear model (lm) predict function with one single array
我在R中有一個經過訓練和序列化的lm
模型。 在一個函數內部,我將模型和特征向量(一個單個數組)作為輸入傳遞,我有:
CREATE OR REPLACE FUNCTION lm_predict(
feat_vec float[],
model bytea
)
RETURNS float
AS
$$
#R-code goes here.
mdl <- unserialize(model)
# class(feat_vec) outputs "array"
y_hat <- predict.lm(mdl, newdata = as.data.frame.list(feat_vec))
return (y_hat)
$$ LANGUAGE 'plr';
這將返回錯誤的y_hat
! 我知道這一點是因為這個其他解決方案有效(此函數的輸入仍然是模型(在feat_vec
數組中)和一個feat_vec
(數組)):
CREATE OR REPLACE FUNCTION lm_predict(
feat_vec float[],
model bytea
)
RETURNS float
AS
$$
#R-code goes here.
mdl <- unserialize(model)
coef = mdl$coefficients
y_hat = coef[1] + as.numeric(coef[-1]%*%feat_vec)
return (y_hat)
$$ LANGUAGE 'plr';
我究竟做錯了什么?? 這是相同的非序列化模型,第一個選項也應該給我正確的答案...
問題似乎是使用newdata = as.data.frame.list(feat_vec)
。 如您在上一個問題中所討論的,這將返回難看的列名。 當您調用predict
, newdata
列名稱必須與模型公式中的協變量名稱一致。 調用predict
時,您應該收到一些警告消息。
## example data
set.seed(0)
x1 <- runif(20)
x2 <- rnorm(20)
y <- 0.3 * x1 + 0.7 * x2 + rnorm(20, sd = 0.1)
## linear model
model <- lm(y ~ x1 + x2)
## new data
feat_vec <- c(0.4, 0.6)
newdat <- as.data.frame.list(feat_vec)
# X0.4 X0.6
#1 0.4 0.6
## prediction
y_hat <- predict.lm(model, newdata = newdat)
#Warning message:
#'newdata' had 1 row but variables found have 20 rows
您需要的是
newdat <- as.data.frame.list(feat_vec,
col.names = attr(model$terms, "term.labels"))
# x1 x2
#1 0.4 0.6
y_hat <- predict.lm(model, newdata = newdat)
# 1
#0.5192413
這與您可以手動計算的內容相同:
coef = model$coefficients
unname(coef[1] + sum(coef[-1] * feat_vec))
#[1] 0.5192413
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.