简体   繁体   English

使用Rpy2清除R内存

[英]Clear R memory using Rpy2

I have a bunch of R functions which I need to call through python. 我有一堆需要通过python调用的R函数。 However, I reach memory errors when I try to allocate a large matrix. 但是,当我尝试分配一个大矩阵时,出现内存错误。 The same functions run fine on RStudio on the same computer. 相同的功能可以在同一台计算机上的RStudio上正常运行。 Here is a code chunk which crashes: 这是一个崩溃的代码块:

#python:
import rpy2.robjects as ro 
import gc
gc.collect()
ro.r.source("calibration_functions.R")
result1 = ro.r.func1()  #Does some calculations, works fine.
result2 = ro.r.func2(result1) #Crashes at this step

#R code:
func2 <- function(result1){
  preds_mat = matrix(data=NA, nrow = 263310, ncol = 1000)
  # do something...
  return(preds_mat)
}

The error I get is: RRuntimeError: Error: cannot allocate vector of size 1004.4 Mb 我得到的错误是:RRuntimeError:错误:无法分配大小为1004.4 Mb的向量

How can I clean the R memory? 如何清洁R记忆? gc() or gc.collect() doesn't work. gc()或gc.collect()不起作用。

清洁R存储器:

rm(list = ls())

(...) (...)

The same functions run fine on RStudio on the same computer. 相同的功能可以在同一台计算机上的RStudio上正常运行。

May be the same function, but likely with differences in memory usage from other applications. 可能具有相同的功能,但可能与其他应用程序的内存使用有所不同。

Your R function func2() returns the following object size: 您的R函数func2()返回以下对象大小:

> object.size(func2(1))
1053240200 bytes

This is about 1.05Gb. 这大约是1.05Gb。

The error I get is: RRuntimeError: Error: cannot allocate vector of size 1004.4 Mb 我得到的错误是:RRuntimeError:错误:无法分配大小为1004.4 Mb的向量

The error observed is likely occurring either because of what is happening in the unspecified function func1() , or because something has changed between the execution in RStudio and the execution in rpy2. 观察到的错误很可能是由于未指定的函数func1()发生了什么,还是因为RStudio中的执行与rpy2中的执行之间发生了某些变化。

I typically deal with the issue by allocating more memory 我通常通过分配更多的内存来解决此问题

from rpy2 import robjects
R = robjects.r


R('memory.limit()')
R('memory.limit(size = 10000)') ## in MB
R('memory.limit()')

…
R('gc()')## trigger garbage collection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM