我有一个.tsv文件,我从中创建了一个pyhton字典,其中键都是movie_id 和值是功能(每部电影都有不同数量的功能)。
这是我的字典的示例:
要实现的目标:
我想从这本字典中创建一个项目特征稀疏矩阵以用于推荐系统项目。 最后,当电影具有特定功能时,我希望有一个值为 1 的二元稀疏矩阵。 像这样的事情:
我的代码:
创建字典:
def Dictionary():
d={}
l=[]
with open(filepath_mapping) as f:
for line in f.readlines():
line = line.split()
key = int(line[0])
value = [int(el) for el in line[1:]]
d[key] = value
return(d)
movie_features_dict = Dictionary()
从字典创建项目特征矩阵:
n = len(movie_features_dict)
value_lengths = [len(v) for v in movie_features_dict.values()]
d = max(value_lengths)
print(f"ITEM*FEATURES matrix shape: {n,d}\n")
item_feature_matrix = sp.dok_matrix((n,d), dtype=np.int8)
for movie_ids, features in movie_features_dict.items():
item_feature_matrix[movie_ids, features] = 1
item_feature_matrix = item_feature_matrix.tocsr()
print(item_feature_matrix.shape)
问题:
我有 22069 部电影,而具有最大特征数的电影应该有 885 个特征,所以理论上我应该有一个 22069*885 矩阵,但是使用我编写的代码,我继续拥有这个错误:
raise IndexError('index (%d) out of range' % max_indx)
IndexError: index (614734) out of range
最佳答案
基于this答案,您可以用几行代码执行以下操作:
import pandas as pd
id_to_features = {
880: [18, 23, 854, 98475, 20],
152: [1, 578, 18, 654, 23, 5, 11],
6654: [2088]
}
df = pd.DataFrame({"features": list(id_to_features.values())})
matrix = df['features'].apply(pd.value_counts).fillna(0).astype(int)
ids = list(id_to_features.keys())
matrix.index = ids
matrix = matrix.reindex(sorted(matrix.columns), axis=1)
编辑
出于好奇,我创建了一个假数据集,上面的代码在普通笔记本电脑上运行(使用 perf_counter
)需要 7 秒。
以下是生成数据集的代码:
id_to_features = {
i: [randint(1, 886) for _ in range(randint(1, 10))] for i in range(1, 22070)
}
生成的矩阵
需要使用计算得出的 78 MB 空间
matrix.memory_usage(index=True, deep=True).sum()
考虑改为 astype("int8")
,它需要 20 MB。
关于python - 如何从Python中的字典创建稀疏二进制矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74278780/