交叉验证R中的序数逻辑回归(使用rpy2)

时间:2016-07-17 00:05:50

标签: r regression cross-validation python scikit-learn

我正在尝试在Python中创建预测模型,通过交叉验证比较几种不同的回归模型。为了适应序数逻辑模型(MASS.polr),我必须通过rpy2与R进行交互,如下所示:

from rpy2.robjects.packages import importr
import rpy2.robjects as ro

df = pd.DataFrame()
df = df.append(pd.DataFrame({"y":25,"X":7},index=[0]))
df = df.append(pd.DataFrame({"y":50,"X":22},index=[0]))
df = df.append(pd.DataFrame({"y":25,"X":15},index=[0]))
df = df.append(pd.DataFrame({"y":75,"X":27},index=[0]))
df = df.append(pd.DataFrame({"y":25,"X":12},index=[0]))
df = df.append(pd.DataFrame({"y":25,"X":13},index=[0]))

# Loads R packages. 
base = importr('base')
mass = importr('MASS')

# Converts df to an R dataframe. 
from rpy2.robjects import pandas2ri
pandas2ri.activate()
ro.globalenv["rdf"] = pandas2ri.py2ri(df) 

# Makes R recognise y as a factor. 
ro.r("""rdf$y <- as.factor(rdf$y)""")

# Fits regression. 
formula = "y ~ X"    
ordlog = mass.polr(formula, data=base.as_symbol("rdf"))
ro.globalenv["ordlog"] = ordlog
print(base.summary(ordlog))

到目前为止,我主要使用sklearn.cross_validation.test_train_splitsklearn.metrics.accuracy_score比较我的模型,得到0到1之间的数字,表示训练集模型在预测测试集值时的准确性

我如何使用rpy2MASS.polr复制此测试?

1 个答案:

答案 0 :(得分:2)

最终通过使用rms.lrm重新设置模型来解决问题,validate()提供\o函数(在this example后解释)。