大数据上的增量PCA

时间:2015-07-15 11:00:39

标签: python scikit-learn bigdata hdf5 pca

我刚尝试使用sklearn.decomposition中的IncrementalPCA,但它之前就像PCA和RandomizedPCA一样抛出了MemoryError。我的问题是,我试图加载的矩阵太大而无法放入RAM中。现在它作为shape~(1000000,1000)的数据集存储在hdf5数据库中,所以我有1.000.000.000 float32值。我认为IncrementalPCA批量加载数据,但显然它试图加载整个数据集,这没有帮助。这个库是如何使用的? hdf5格式是问题吗?

from sklearn.decomposition import IncrementalPCA
import h5py

db = h5py.File("db.h5","r")
data = db["data"]
IncrementalPCA(n_components=10, batch_size=1).fit(data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/software/anaconda/2.3.0/lib/python2.7/site-packages/sklearn/decomposition/incremental_pca.py", line 165, in fit
    X = check_array(X, dtype=np.float)
  File "/software/anaconda/2.3.0/lib/python2.7/site-packages/sklearn/utils/validation.py", line 337, in check_array
    array = np.atleast_2d(array)
  File "/software/anaconda/2.3.0/lib/python2.7/site-packages/numpy/core/shape_base.py", line 99, in atleast_2d
    ary = asanyarray(ary)
  File "/software/anaconda/2.3.0/lib/python2.7/site-packages/numpy/core/numeric.py", line 514, in asanyarray
    return array(a, dtype, copy=False, order=order, subok=True)
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper (-------src-dir-------/h5py/_objects.c:2458)
  File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper (-------src-dir-------/h5py/_objects.c:2415)
  File "/software/anaconda/2.3.0/lib/python2.7/site-packages/h5py/_hl/dataset.py", line 640, in __array__
    arr = numpy.empty(self.shape, dtype=self.dtype if dtype is None else dtype)
MemoryError

感谢您的帮助

1 个答案:

答案 0 :(得分:20)

您的程序可能无法尝试将整个数据集加载到RAM中。每个浮点数为32位32×1,000,000×1000为3.7 GiB。这在仅具有4 GiB RAM的机器上可能是个问题。要检查它实际上是否存在问题,请尝试单独创建此大小的数组:

>>> import numpy as np
>>> np.zeros((1000000, 1000), dtype=np.float32)

如果您看到MemoryError,则需要更多内存,或者您需要一次处理一个数据集。

对于h5py数据集,我们应该避免将整个数据集传递给我们的方法,而是传递数据集的切片。一次一个。

由于我没有您的数据,让我从创建相同大小的随机数据集开始:

import h5py
import numpy as np
h5 = h5py.File('rand-1Mx1K.h5', 'w')
h5.create_dataset('data', shape=(1000000,1000), dtype=np.float32)
for i in range(1000):
    h5['data'][i*1000:(i+1)*1000] = np.random.rand(1000, 1000)
h5.close()

它会创建一个漂亮的3.8 GiB文件。

现在,如果我们在Linux中,我们可以限制程序可用的内存:

$ bash
$ ulimit -m $((1024*1024*2))
$ ulimit -m
2097152

现在,如果我们尝试运行您的代码,我们将获得MemoryError。 (按Ctrl-D退出新的bash会话并稍后重置限制)

让我们尝试解决问题。我们将创建一个IncrementalPCA对象,并多次调用其.partial_fit()方法,每次都提供不同的数据集切片。

import h5py
import numpy as np
from sklearn.decomposition import IncrementalPCA

h5 = h5py.File('rand-1Mx1K.h5')
data = h5['data'] # it's ok, the dataset is not fetched to memory yet

n = data.shape[0] # how many rows we have in the dataset
chunk_size = 1000 # how many rows we feed to IPCA at a time, the divisor of n
icpa = IncrementalPCA(n_components=10, batch_size=16)

for i in range(0, n//chunk_size):
    ipca.partial_fit(data[i*chunk_size : (i+1)*chunk_size])

它似乎对我有用,如果我查看top报告的内容,内存分配将保持在200M以下。