Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
单阵列R线性模型(lm)预测函数_R_Postgresql_Lm_Predict_Plr - Fatal编程技术网

单阵列R线性模型(lm)预测函数

单阵列R线性模型(lm)预测函数,r,postgresql,lm,predict,plr,R,Postgresql,Lm,Predict,Plr,我在R中有一个lm模型,我已经对它进行了训练和序列化。在函数中,我将模型和特征向量(一个数组)作为输入传递,我有: 我做错了什么??这是同一个未序列化的模型,第一个选项也应该给我正确的答案…问题似乎在于使用newdata=as.data.frame.list(feat\u vec)。正如在中所讨论的,这将返回难看的列名。调用predict时,newdata的列名必须与模型公式中的协变量名称一致。当您调用predict时,应该会收到一些警告消息 ## example data set.seed(0

我在R中有一个
lm
模型,我已经对它进行了训练和序列化。在函数中,我将模型和特征向量(一个数组)作为输入传递,我有:


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

问题似乎在于使用
newdata=as.data.frame.list(feat\u 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 

这是R码吗?它看起来像半条蟒蛇;冒号在R中不起作用,
返回
+
。是的,它是R+伪代码-实际上可以忽略函数声明-这在Postgres中的PL/R函数中,但我不想关注Postgres…那么伪代码如何返回结果,正确与否?我对我的问题做了一些编辑,希望现在一切都清楚了。第一个选项返回错误的数字,而第二个选项返回正确的预测!我没有任何错误,不管有多好,但仍然不负责。我从Postgres打电话给R时看不到警告消息。。。但肯定有什么不对谢谢你的回答。我真的很感激。但它对我仍然不起作用,y__hat总是返回相同的结果,而“手动”计算返回正确的预测。我不明白为什么:/为什么我需要包括列名??这真的很重要吗?这解决了我在使用randomForest时遇到的问题。。。谢谢我仍然得到了lm的奇怪行为,但很高兴我得到了它与另一个回归模型和完全相同的代码一起工作!
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';
## 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