构建稀疏矩阵Python Scipy.sparse时出错

时间:2015-12-06 21:32:22

标签: python scipy sparse-matrix

在我的代码中,我正在迭代并创建三个列表:

data,row,col

构造一个稀疏矩阵(它表示一个评级矩阵,用户u的评级项目i的评级为1到5),之后检查我的稀疏矩阵时,我在报告的评级中出现了奇怪的错误:某些值大于5这是不可能的(我检查了文件,没有大于5的评级,我也检查了数据列表中的值,没有大于5的值,所以错误可能是使用sparse.coo_matrix构建矩阵时(),

请参阅下面的代码:

from scipy import sparse
import numpy as np

row = []
column = []
data= []

with open(filename, 'r') as f:
    for line in f:
        if not line[0].isdigit():
            continue
        line = line.strip()
        elem = line.split(',')

        userid = int(elem[0].strip())
        businessid = int(elem[1].strip())
        rating = float(elem[2].strip())

        row.append(userid)
        column.append(businessid)
        data.append(rating)

#data = np.array(data)

"""checking if any rating in the file is greater than 5,
and there is not"""
for rating in data:
    if rating > 5:
        print rating

total = sparse.coo_matrix((data, (row, column)),dtype=float).tocsr()

""" Here I'm checking to see if 
there is any rating over than 5 in the sparse matrix
and there is!"""
row = total.nonzero()[0]
column = total.nonzero()[1]

for u in range(len(row)):
    indr = row[u]
    indc = column[u]
    if total[indr, indc] > 5:
        print '---'
        print total[indr, indc]
        print indr
        print indc

这是我文件的开头:

user,item,rating
480,0,5
16890,0,2
5768,0,4
319,1,1
4470,1,4
7555,1,5
8768,1,5

在构建矩阵时,您是否知道我为什么会出现此错误?

非常感谢!

1 个答案:

答案 0 :(得分:1)

From the docs for to_csr

  

重复的条目将汇总在一起

(我不知道为什么会这样做。)