Python—将稀疏文件读入稀疏矩阵的最佳方法

Python—将稀疏文件读入稀疏矩阵的最佳方法,python,numpy,matrix,scipy,sparse-matrix,Python,Numpy,Matrix,Scipy,Sparse Matrix,想知道是否有更有效的方法将文件内容加载到稀疏矩阵中。 下面的代码从一个大文件(8GB)中读取数据,该文件大部分为零值(非常稀疏),然后对每一行读取数据进行一些处理。 我想对它高效地执行算术运算,所以我尝试将这些行存储为稀疏矩阵。 由于文件中的行数事先未知,而且数组/矩阵也不是动态的,因此我必须首先将其存储在列表中,然后将其转换为csr_矩阵。 此阶段(“X=csr\u矩阵(X)”)需要大量时间和内存。 有什么建议吗 import numpy as np from scipy.sparse imp

想知道是否有更有效的方法将文件内容加载到稀疏矩阵中。 下面的代码从一个大文件(8GB)中读取数据,该文件大部分为零值(非常稀疏),然后对每一行读取数据进行一些处理。 我想对它高效地执行算术运算,所以我尝试将这些行存储为稀疏矩阵。 由于文件中的行数事先未知,而且数组/矩阵也不是动态的,因此我必须首先将其存储在列表中,然后将其转换为csr_矩阵。 此阶段(“
X=csr\u矩阵(X)
”)需要大量时间和内存。
有什么建议吗

import numpy as np
from scipy.sparse import csr_matrix
from datetime import datetime as time

global header_names; header_names = []

def readOppFromFile(filepath):

    print "Read Opportunities From File..." + str(time.now())

    # read file header - feature names separated with commas
    global header_names

    with open(filepath, "r") as f:

        i=0

        header_names  = f.readline().rstrip().split(',')

        for line in f: 


            # replace empty string with 0 in comma-separated string. In addition, clean null values (replace with 0)
            yield [(x.replace('null', '0') if x else 0) for x in line.rstrip().split(',')]
            i += 1

        print "Number of opportunities read from file: %s" % str(i) 

def processOpportunities(opp_data):

    print "Process Opportunities ..." + str(time.now())

    # Initialization 
    X = []
    targets_array = []

    global header_names

    for opportunity in opp_data:

        # Extract for each opportunity it's target variable, save it in a special array and then remove it  
        target = opportunity[-1] # Only last column
        targets_array.append(target)
        del opportunity[-1] # Remove last column

        X.append(opportunity)     

   print " Starting to transform to a sparse matrix" + str(time.now())
    X = csr_matrix(X)
    print "Finished transform to a sparse matrix " + str(time.now())

    # The target variable of each impression
    targets_array = np.array(targets_array, dtype=int)
    print "targets_array" + str(time.now())        

    return X, targets_array

def main():


    print "STRAT -----> " + str(time.now())
    running_time = time.now()

    opps_data = readOppFromFile(inputfilename)

    features, target = processOpportunities(opps_data)

if __name__ == '__main__':

    """ ################### GLOBAL VARIABLES ############################ """     
    inputfilename = 'C:/somefolder/trainingset.working.csv'

    """ ################### START PROGRAM ############################ """     
    main()
更新: 矩阵的维数不是恒定的,它们取决于输入文件,并且在程序的每次运行中可能会发生变化。
有关我输入的小样本,请参见。

如果手动跟踪非零,则可以直接构造稀疏矩阵:

X_data = []
X_row, X_col = [], []
targets_array = []

for row_idx, opportunity in enumerate(opp_data):
    targets_array.append(int(opportunity[-1]))
    row = np.array(map(int, opportunity[:-1]))
    col_inds, = np.nonzero(row)
    X_col.extend(col_inds)
    X_row.extend([row_idx]*len(col_inds))
    X_data.extend(row[col_inds])

print " Starting to transform to a sparse matrix" + str(time.now())
X = coo_matrix((X_data, (X_row, X_col)), dtype=int)
print "Finished transform to a sparse matrix " + str(time.now())
这将以COO格式构造矩阵,很容易转换为您喜欢的任何格式:

X = X.tocsr()

什么决定了稀疏矩阵的边界?只是文件中的行数?您还可以共享一个指向巨型文件的非常小版本的链接,以便任何人都可以复制和测试吗?此维度由输入文件设置,但在每次运行中可能会发生变化。在这里查看我的输入文件的示例版本:谢谢。我看看能不能解决一些问题。我一直想尝试在numpy中使用稀疏矩阵。但是,您可以检查数据文件是否与上面的代码一起工作吗?我得到
ValueError:int()的无效文本,基数为10:'da7f5cb5-2189-40cc-8a42-9fdedc29f925'
oh,因为我在这里的代码中省略了一个函数,它只获取每个opportunity(在执行“opp_数据中的opportunity”之前)的数值。