2016-09-16 45 views
-1

我有一個lm模型在R,我已經訓練和序列化。內的功能,其中,I通過作爲輸入的模型和特徵向量(一個單個陣列),我有: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 !!我知道這是因爲這種解決方案的其他作品(輸入這個功能仍然是模型(爲bytearray)和一個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'; 

我在做什麼錯?這是同樣的非序列化的模型,第一個選項應該給我正確的答案以及...

+0

這是R代碼裏面?它看起來像半蟒蛇;冒號中的冒號不會以這種方式工作,也不會返回''或'+'。 – alistaire

+0

是的,它是R +僞代碼 - 你可以忽略函數聲明 實際上 - 這是在Postgres的PL/R函數中,但我不想把重點放在Postgres – strv7

+0

...所以如何僞代碼返回結果,正確與否? – alistaire

回答

1

這個問題似乎是使用newdata = as.data.frame.list(feat_vec)。正如您在previous question中所討論的那樣,這會返回醜陋的列名稱。當您撥打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 
+0

從Postgres調用R時,我看不到警告消息......但是肯定有錯誤 – strv7

+0

謝謝你的回答。對此,我真的非常感激。 雖然它仍然不適用於我,但y_hat總是返回相同的結果,而「手動」計算返回正確的預測結果。我不明白爲什麼:/ 爲什麼我需要包含col.names?這真的很重要嗎? – strv7

+0

使用randomForest解決了我的問題...謝謝!我仍然用lm得到奇怪的行爲,但是我很高興能夠與另一個迴歸模型和完全相同的代碼一起工作! – strv7

相關問題