def get_sparse_matrix(session, key_table, cand_lists, key=None):
result = []<EOL>cand_lists = cand_lists if isinstance(cand_lists, (list, tuple)) else [cand_lists]<EOL>for cand_list in cand_lists:<EOL><INDENT>if len(cand_list) == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>candidate_class = cand_list[<NUM_LIT:0>].__tablename__<EOL>if key:<EOL><INDENT>keys_map = {key: <NUM_LIT:0>}<EOL>key_size = len(keys_map)<EOL><DEDENT>else:<EOL><INDENT>all_keys = get_sparse_matrix_keys(session, key_table)<EOL>key_size = len(all_keys)<EOL>keys_map = {}<EOL>for (i, k) in enumerate(all_keys):<EOL><INDENT>if candidate_class in k.candidate_classes:<EOL><INDENT>keys_map[k.name] = i<EOL><DEDENT><DEDENT><DEDENT>indptr = [<NUM_LIT:0>]<EOL>indices = []<EOL>data = []<EOL>for cand in cand_list:<EOL><INDENT>values = _get_cand_values(cand, key_table)<EOL>if values:<EOL><INDENT>for cand_key, cand_value in zip(values[<NUM_LIT:0>].keys, values[<NUM_LIT:0>].values):<EOL><INDENT>if cand_key in keys_map:<EOL><INDENT>indices.append(keys_map[cand_key])<EOL>data.append(cand_value)<EOL><DEDENT><DEDENT><DEDENT>indptr.append(len(indices))<EOL><DEDENT>result.append(<EOL>csr_matrix((data, indices, indptr), shape=(len(cand_list), key_size))<EOL>)<EOL><DEDENT>return result<EOL>
Load sparse matrix of GoldLabels for each candidate_class.