如何在Python中从CSR矩阵生成向量?

时间:2018-03-28 19:13:33

标签: python numpy scipy scikit-learn keras

我试图在由CSR矩阵表示的词袋特征上训练神经网络。因为我的数据集是~100k实例,长度为~100k,所以我无法将所有向量都放入内存中。

for trainIndices, testIndices in indices.split(X):
    print("\tAnalyzing fold {}...".format(fold))
    print("\t\tIsolating training data...")
    train_X = countVectorizer.fit_transform( X[trainIndices].apply( lambda x:
                                                                    ' '.join(x)
                                                                    )
                                             )
    train_y = y[trainIndices]

    print("\t\tIsolating test data...")
    test_X = countVectorizer.transform( X[testIndices].apply( lambda x:
                                                              ' '.join(x)
                                                              )
                                        )
    test_y = y[testIndices]

    cnn = build(countVectorizer.vocabulary_.__len__())

    print("\t\tFitting training data...")

    print(type(train_X))
    generator=createGenerator(train_X, train_y)

    # implement a generator for this.
    cnn.fit_generator( generator       = generator,
                       steps_per_epoch = 10000,
                       validation_data = ( test_X, test_y )
                       )

因此我正在使用Keras' fit_generator() 方法,如果我理解正确,则将渐进数据提供给培训。我不处理图像,所以我尝试创建自己的生成器方法来产生值。但是,我不确定如何通过迭代/收益从CSR矩阵提供实例。

def createGenerator(x,y):
    for index_X, index_y in zip(x, y):
        # print(x,y)
        yield(x, y)

到目前为止,我已经尝试过转换为合并矩阵:

def createGenerator(x,y):
    cx = scipy.sparse.coo_matrix(x)
    cy = scipy.sparse.coo_matrix(y)
    print(cx)
    print(cy)
    for a,b in zip(cx.row, cy.row):
        yield(a,b)

我也尝试直接迭代CSR,这导致了ValueError:设置一个带序列的数组元素。我不确定如何生成神经网络将从CSR矩阵接受的向量。通过使用自定义生成器,我可能也完全走错了路。

0 个答案:

没有答案