Matrix上的Python PCA太大而无法融入内存

时间:2015-08-24 20:30:53

标签: python pandas machine-learning scikit-learn pca

我有一个100,000行x 27,000列的csv,我试图在PCA上生成100,000行X 300列矩阵。 csv大9GB。这是我目前正在做的事情:

from sklearn.decomposition import PCA as RandomizedPCA
import csv
import sys
import numpy as np
import pandas as pd

dataset = sys.argv[1]
X = pd.DataFrame.from_csv(dataset)
Y = X.pop("Y_Level")
X = (X - X.mean()) / (X.max() - X.min())
Y = list(Y)
dimensions = 300
sklearn_pca = RandomizedPCA(n_components=dimensions)
X_final = sklearn_pca.fit_transform(X)

当我运行上面的代码时,我的程序在执行.from_csv时被杀死了。我已经能够通过将csv分成10,000组来解决这个问题;逐个读取它们,然后调用pd.concat。这允许我在被杀之前进入标准化步骤(X-X.mean())....我的数据对我的macbook空间来说太大了吗?或者有更好的方法来做到这一点。我真的很想将我拥有的所有数据用于我的机器学习应用程序。

如果我想按照下面的答案建议使用增量PCA,我会这样做吗?:

from sklearn.decomposition import IncrementalPCA
import csv
import sys
import numpy as np
import pandas as pd

dataset = sys.argv[1]
chunksize_ = 10000
#total_size is 100000
dimensions = 300

reader = pd.read_csv(dataset, sep = ',', chunksize = chunksize_)
sklearn_pca = IncrementalPCA(n_components=dimensions)
Y = []
for chunk in reader:
    y = chunk.pop("virginica")
    Y = Y + list(y)
    sklearn_pca.partial_fit(chunk)
X = ???
#This is were i'm stuck, how do i take my final pca and output it to X,
#the normal transform method takes in an X, which I don't have because I
#couldn't fit it into memory.

我无法在网上找到任何好的例子。

2 个答案:

答案 0 :(得分:12)

尝试划分您的数据或将其按批次加载到脚本中,并在每个批次上使用Incremetal PCA使用 partial_fit 方法使您的PCA适合。

from sklearn.decomposition import IncrementalPCA
import csv
import sys
import numpy as np
import pandas as pd

dataset = sys.argv[1]
chunksize_ = 5 * 25000
dimensions = 300

reader = pd.read_csv(dataset, sep = ',', chunksize = chunksize_)
sklearn_pca = IncrementalPCA(n_components=dimensions)
for chunk in reader:
    y = chunk.pop("Y")
    sklearn_pca.partial_fit(chunk)

# Computed mean per feature
mean = sklearn_pca.mean_
# and stddev
stddev = np.sqrt(sklearn_pca.var_)

Xtransformed = None
for chunk in pd.read_csv(dataset, sep = ',', chunksize = chunksize_):
    y = chunk.pop("Y")
    Xchunk = sklearn_pca.transform(chunk)
    if Xtransformed == None:
        Xtransformed = Xchunk
    else:
        Xtransformed = np.vstack((Xtransformed, Xchunk))

Useful link

答案 1 :(得分:0)

PCA需要计算相关矩阵,即100,000x100,000。如果数据存储在双精度数中,则为80 GB。我愿意打赌你的Macbook没有80 GB RAM。

对于合理大小的随机子集,PCA转换矩阵可能几乎相同。