构建稀疏矩阵Python时出错石梁

2024-04-18 19:41:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

数据,行,列

为了构造一个稀疏矩阵(它表示一个评级矩阵,用户u将项目i的评级从1到5),我在事后检查稀疏矩阵时发现报告的评级中有奇怪的错误:有些值大于5,这是不可能的(我检查了文件,没有评级大于5,我还检查了数据列表中的值,没有大于5的值,因此错误可能是在使用稀疏.coo\u矩阵()

请参见下面的代码:

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

你知道为什么我在构建矩阵时会出现这个错误吗?你知道吗

非常感谢!你知道吗


Tags: indataifislinecolumn矩阵row