增量PCA

时间:2017-02-03 09:14:03

标签: scikit-learn pca

我从未使用过sklearn中存在的增量PCA,我对它的参数感到有点困惑,而且无法找到它们的好解释。

我看到构造函数中有batch_size,但是,当使用partial_fit方法时,您可以再次只传递部分数据,我发现了以下方法:

n = df.shape[0]
chunk_size = 100000
iterations = n//chunk_size

ipca = IncrementalPCA(n_components=40, batch_size=1000)

for i in range(0, iterations):
    ipca.partial_fit(df[i*chunk_size : (i+1)*chunk_size].values)

ipca.partial_fit(df[iterations*chunk_size : n].values)

现在,我不明白的是 - 当使用部分拟合时,batch_size是否可以扮演任何角色?它们如何相关?

此外,如果两者都被考虑,当我想在增加内存占用时增加精度时,我应该如何正确地改变它们的值(反过来,以降低精度的代价降低内存消耗)?

2 个答案:

答案 0 :(得分:2)

docs说:

  

batch_size:int或None,(默认=无)

The number of samples to use for each batch. Only used when calling fit...

此参数不在partial_fit中使用,其中批量大小由用户控制。

较大的批次会增加内存消耗,较小的批次会减少内存消耗。 这也写在文档中:

  

此算法具有恒定的内存复杂性,按批次大小的顺序,允许使用np.memmap文件而无需将整个文件加载到内存中。

尽管有一些检查和参数启发式,整个fit - 函数看起来像这样:

for batch in gen_batches(n_samples, self.batch_size_):
    self.partial_fit(X[batch], check_input=False)

答案 1 :(得分:0)

以下是一些基于https://github.com/kevinhughes27/pyIPCA的增量PCA代码,它是CCIPCA方法的一种实现。

import scipy.sparse as sp
import numpy as np
from scipy import linalg as la
import scipy.sparse as sps
from sklearn import datasets

class CCIPCA:    
    def __init__(self, n_components, n_features, amnesic=2.0, copy=True):
        self.n_components = n_components
        self.n_features = n_features
        self.copy = copy
        self.amnesic = amnesic
        self.iteration = 0
        self.mean_ = None
        self.components_ = None
        self.mean_ = np.zeros([self.n_features], np.float)
        self.components_ = np.ones((self.n_components,self.n_features)) / \
                           (self.n_features*self.n_components)

    def partial_fit(self, u):
        n = float(self.iteration)
        V = self.components_

        # amnesic learning params
        if n <= int(self.amnesic):
            w1 = float(n+2-1)/float(n+2)    
            w2 = float(1)/float(n+2)    
        else:
            w1 = float(n+2-self.amnesic)/float(n+2)    
            w2 = float(1+self.amnesic)/float(n+2)

        # update mean
        self.mean_ = w1*self.mean_ + w2*u

        # mean center u        
        u = u - self.mean_

        # update components
        for j in range(0,self.n_components):

            if j > n: pass            
            elif j == n: V[j,:] = u
            else:       
                # update the components
                V[j,:] = w1*V[j,:] + w2*np.dot(u,V[j,:])*u / la.norm(V[j,:])
                normedV = V[j,:] / la.norm(V[j,:])
                normedV = normedV.reshape((self.n_features, 1))
                u = u - np.dot(np.dot(u,normedV),normedV.T)

        self.iteration += 1
        self.components_ = V / la.norm(V)

        return

    def post_process(self):        
        self.explained_variance_ratio_ = np.sqrt(np.sum(self.components_**2,axis=1))
        idx = np.argsort(-self.explained_variance_ratio_)
        self.explained_variance_ratio_ = self.explained_variance_ratio_[idx]
        self.components_ = self.components_[idx,:]
        self.explained_variance_ratio_ = (self.explained_variance_ratio_ / \
                                          self.explained_variance_ratio_.sum())
        for r in range(0,self.components_.shape[0]):
            d = np.sqrt(np.dot(self.components_[r,:],self.components_[r,:]))
            self.components_[r,:] /= d

您可以使用

进行测试

将pandas导入为pd,ccipca

df = pd.read_csv('iris.csv')
df = np.array(df)[:,:4].astype(float)
pca = ccipca.CCIPCA(n_components=2,n_features=4)
S  = 10
print df[0, :]
for i in range(150): pca.partial_fit(df[i, :])
pca.post_process()

得到的特征向量/值不会与批量PCA完全相同。结果是近似值,但它们很有用。