我是python和pandas的新手,我遇到以下问题
我有一个数据集
df = pd.read_csv('/home/nikoscha/Documents/ThesisR/dataset.csv', names=['response_nn','event','user'])
我正在尝试使用以下代码创建一个csr_matrix
# Create lists of all events, users adfnd respones
events = list(np.sort(df.event_id.unique()))
users = list(np.sort(df.user_id.unique()))
responses = list(df.responses)
# Get the rows and columns for our new matrix
rows = df.user_id.astype(float)
cols = df.event_id.astype(float)
# Contruct a sparse matrix for our users and items containing number of plays
data_sparse = sp.csr_matrix((responses, (rows, cols)), shape=(len(users), len(events)))
上面的代码有效。但是当我得到训练数据集
mask = np.random.rand(len(df)) < 0.5
df = df[mask]
df = df.reset_index()
df = df.drop(['index'], axis=1)
或仅删除特定的行
df = df[df.responses != 2]
并尝试构造稀疏矩阵,但出现以下错误
ValueError:行索引超出矩阵尺寸
谁能解释我为什么?预先谢谢你
答案 0 :(得分:1)
如scipy的文档所述,当csr_matrix以以下形式初始化时:
csr_matrix((data,(row_ind,col_ind)),[shape =(M,N)])
在scipy.sparse.csr.py中:
csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
where `data`, `row_ind` and `col_ind` satisfy the
relationship `a[row_ind[k], col_ind[k]] = data[k]`.
,当csr初始化时,它将检查row_ind.max()和M之间的关系。
也在scipy.sparse.coo.py中:
if self.row.max() >= self.shape[0]:
raise ValueError('row index exceeds matrix dimensions')
if self.col.max() >= self.shape[1]:
raise ValueError('column index exceeds matrix dimensions')
if self.row.min() < 0:
raise ValueError('negative row index found')
if self.col.min() < 0:
raise ValueError('negative column index found')
因此row_ind.max(),col.ind.max()必须小于M,N
以上所有内容是因为您要使用row_ind和col.ind中的数据作为索引来构造稀疏矩阵。
即:
a = np.random.random((8,2))
row = np.hstack((a[:,0],a[:,1]))
#row[0]=9
col = np.hstack([a[:,1],a[:,0]])
matrix = csr_matrix(([1]*row.shape[0], (row,col)),shape=(a.shape[0],a.shape[0]))
在带行[0] = 9的情况下可以正常工作。希望对您有所帮助。