使用 python 和 rpy2 绘制拟合模型的预测值

Plotting predicted values from a fitted model using python and rpy2

我无法使用 rpy2 绘制观察值与预测值。下面的 R 代码有效:

                                                 #==============================#
                                                 # Set up the data.             #
                                                 #==============================#
yTmp <- seq(1,20)
y <- NULL
x1Tmp <- seq(1,20)
x1 <- NULL
x2Tmp <- seq(1,20)
x2 <- NULL
for (i in 1:20)
{
    y[i] = yTmp[i] + runif(1, 0, 1)
    x1[i] = x1Tmp[i] + runif(1, 0, 1)
    x2[i] = x2Tmp[i] + runif(1, 0, 1)
}
                                                #==============================#
                                                # Fit the model.               #
                                                #==============================#
fittedModel <- lm(y ~ x1 + x2)
                                                #==============================#
                                                # Plot the observed vs predicted
                                                #==============================#
png(filename="fittedModel_R.png")
plot(fittedModel$fitted.values, y)
dev.off()

这会生成一个很好的观察图与预测图(我会 post 但我需要至少 10 个声誉才能 post 图像)。

我曾尝试使用 rpy2 重现它,但我无法弄清楚如何让拟合值很好地发挥作用。下面的代码与上面的 R 代码一样,但不起作用:

#!/usr/bin/env python
                                                #==============================#
                                                # Set up packages.             #
                                                #==============================#
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
import random
import string
stats = importr('stats')
from rpy2.robjects import Formula
lattice = importr('lattice')
rprint = robjects.globalenv.get("print")
grdevices = importr('grDevices')
                                                #==============================#
                                                # Set up the data.             #
                                                #==============================#
y = robjects.FloatVector(())
x1 = robjects.FloatVector(())
x2 = robjects.FloatVector(())
for i in range(1,20):
    yValue = i + random.random()
    y.rx[i] = yValue
    x1Value = i + random.random()
    x1.rx[i] = x1Value
    x2Value = i + random.random()
    x2.rx[i] = x2Value
robjects.globalenv["y"] = y
robjects.globalenv["x1"] = x1
robjects.globalenv["x2"] = x2
                                                #==============================#
                                                # Fit the model.               #
                                                #==============================#
fittedModel = stats.lm("y ~ x1 + x2")
                                                #==============================#
                                                # Attempt to extract the fitted 
                                                # values from the model and put
                                                # on a vector.                 #
                                                #==============================#
robjects.globalenv['predicted'] = robjects.Vector(fittedModel.rx('fitted.values'))
                                                #==============================#
                                                # Plot the observed vs predicted
                                                #==============================#
grdevices.png(file = "fittedModel_RPY2.png", width = 512, height = 512)
formula = Formula('y ~ predicted')
p = lattice.xyplot(formula)
rprint(p)
grdevices.dev_off()

这会产生一个错误:

/usr/local/lib/python2.7/dist-packages/rpy2/robjects/functions.py:106: UserWarning: Error in order(as.numeric(x)) : (list) object cannot be coerced to type 'double'

res = super(Function, self).call(*new_args, **new_kwargs) Traceback (most recent call last): File "./testRPY2.py", line 45, in p = lattice.xyplot(formula) File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/functions.py", line 178, in call return super(SignatureTranslatedFunction, self).call(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/functions.py", line 106, in call res = super(Function, self).call(*new_args, **new_kwargs) rpy2.rinterface.RRuntimeError: Error in order(as.numeric(x)) :
(list) object cannot be coerced to type 'double'

问题肯定出在预测值上,因为更改公式以绘制 y 对 y 会生成一个漂亮的图:

formula = Formula('y ~ y')

我曾多次尝试将 python 中的数据强制转换为可绘制格式,包括转换为 python 中的字符串、进行操作并作为浮动向量发送回 rpy2。但我真的不明白为什么它不起作用,必须有更好的方法。非常感谢任何对我的问题的见解和帮助。

如果对predicted有疑问,可以尝试

print(type(robjects.globalenv['predicted']))

或更长的输出:

print(robjects.globalenv['predicted'])

您会发现在 R 中没有所谓的原子向量,这几乎可以肯定来自创建 predicted 的一行:

robjects.globalenv['predicted'] = robjects.Vector(fittedModel.rx('fitted.values'))

方法.rx()对应R的[.rx2()对应R的[[。你会想要后者。

文档中的介绍有一个用 R 的简短示例 lm()http://rpy.sourceforge.net/rpy2/doc-2.6/html/introduction.html#linear-models