2015-04-20 31 views
2

我試圖加速比使用熊貓和R.熊貓與rpy2和多

假設我有以下的數據幀的過程:

import pandas as pd 
from random import randint 
df = pd.DataFrame({'mpg': [randint(1, 9) for x in xrange(10)], 
        'wt': [randint(1, 9)*10 for x in xrange(10)], 
        'cyl': [randint(1, 9)*100 for x in xrange(10)]}) 
df 
    mpg wt cyl 
0 3 40 100 
1 6 30 200 
2 7 70 800 
3 3 50 200 
4 7 50 400 
5 4 10 400 
6 3 70 500 
7 8 30 200 
8 3 40 800 
9 6 60 200 

然後,我用rpy2模型的一些數據:

import rpy2.robjects.packages as rpackages 
import rpy2.robjects as robjects 
from rpy2.robjects import pandas2ri 
pandas2ri.activate() 

base = rpackages.importr('base') 
stats = rpackages.importr('stats') 

formula = 'mpg ~ wt + cyl' 
fit_full = stats.lm(formula, data=df) 

在此之後我做一些預測:

rfits = stats.predict(fit_full, newdata=df) 

這段代碼對於一個小數據幀運行沒有問題,但實際上我有一個數百萬行的大數據框,我試圖用其他rpy2模型加速預測部分,但不幸的是這需要很長時間來處理。

我試圖用首次多道庫完成這個任務沒有成功:

import multiprocessing as mp 

pool = mp.Pool(processes=4) 
rfits = pool.map(predict(fit_full, newdata=df)) 

但可能是我做錯了什麼,因爲我看不到任何的速度提高。

我認爲這裏的主要問題是因爲我試圖將pool.map應用於rpy2函數而不是Python預定義的函數。可能有一些解決方法,但不使用多處理庫,但我看不到任何解決方案。

任何幫助將不勝感激。提前致謝。

+0

什麼是您的CPU使用率是什麼樣子?你的代碼是否實際使用全部4個內核? –

+0

不,完全沒有,它仍然只使用1個內核。 – npires

+1

[This](http://stackoverflow.com/q/15639779/1461210)可能是相關的,然後 –

回答

1

您是否嘗試過使用StatsModels?

Fitting models using R-style formulas 自0.5.0版本,statsmodels 允許用戶使用R-樣式公式,以適應統計模型。 在內部,statsmodels使用patsy包將公式和 數據轉換爲在模型擬閤中使用的矩陣。公式 框架相當強大;本教程只是表面上的劃痕。 公式語言的完整描述可以在帕奇發現 文檔

import statsmodels.formula.api as smf 

formula = 'mpg ~ wt + cyl' 
model = smf.ols(formula=formula, data=df) 
params = model.fit().params 

>>> params 
params 
Intercept 5.752803 
wt   0.037770 
cyl   -0.004112 

>>> model.predict(params, exog=df) 
array([ 1725.83759267, 2876.50148582, 575.25352613, 1150.6605447 , 
     1150.51281171, 3451.54178359, 575.53800931, 575.4146529 , 
     2876.58372342, 5177.46831077]) 
+0

是的,我知道statsmodels,但實際上我需要使用gam(廣義相加模型),我相信它尚未在statsmodels中實現。 – npires

+2

正確。這是他們的'沙盒'的一部分http://statsmodels.sourceforge.net/devel/sandbox.html – Alexander

+0

哇!我不知道!我會在測試後給出反饋!謝謝。 – npires