-1

lm在 R 中有一个经过训练和序列化的模型。在一个函数内部,我将模型和特征向量(一个数组)作为输入传递,我有:

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(数组)):

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';

我究竟做错了什么??它是相同的未序列化模型,第一个选项也应该给我正确的答案......

4

1 回答 1

2

问题似乎是使用newdata = as.data.frame.list(feat_vec). 正如您在上一个问题中所讨论的,这会返回丑陋的列名。而当您调用 时predictnewdata列名必须与模型公式中的协变量名称一致。调用时应该会收到一些警告消息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 
于 2016-09-16T04:54:33.103 回答