推荐算法模块

目录

推荐算法模块#

推荐系统算法和工具。

Cornac 工具#

recommenders.models.cornac.cornac_utils.predict(model, data, usercol='userID', itemcol='itemID', predcol='prediction')[source]#

计算 Cornac 推荐模型在数据上的预测。可用于计算 RMSE 等评分指标。

参数:
  • model (cornac.models.Recommender) – Cornac 的推荐模型

  • data (pandas.DataFrame) – 用于预测的数据

  • usercol (str) – 用户列的名称

  • itemcol (str) – 物品列的名称

返回值:

包含 usercol、itemcol、predcol 列的数据框

返回类型:

pandas.DataFrame

recommenders.models.cornac.cornac_utils.predict_ranking(model, data, usercol='userID', itemcol='itemID', predcol='prediction', remove_seen=False)[source]#

计算 Cornac 推荐模型在数据中所有用户和物品上的预测。可用于计算 NDCG 等排序指标。

参数:
  • model (cornac.models.Recommender) – Cornac 的推荐模型

  • data (pandas.DataFrame) – 用于获取用户和物品的数据

  • usercol (str) – 用户列的名称

  • itemcol (str) – 物品列的名称

  • remove_seen (bool) – 用于移除训练数据中已见过的 (用户, 物品) 对的标志

返回值:

包含 usercol、itemcol、predcol 列的数据框

返回类型:

pandas.DataFrame

DeepRec 工具#

基础模型#

class recommenders.models.deeprec.models.base_model.BaseModel(hparams, iterator_creator, graph=None, seed=None)[source]#

模型的基础类

__init__(hparams, iterator_creator, graph=None, seed=None)[source]#

初始化模型。创建所有 deeprec 模型所需的通用逻辑,例如损失函数、参数集。

参数:
  • hparams (object) – 一个 HParams 对象,包含全部超参数。

  • iterator_creator (object) – 用于加载数据的迭代器。

  • graph (object) – 可选的图。

  • seed (int) – 随机种子。

eval(sess, feed_dict)[source]#

使用当前模型评估 feed_dict 中的数据。

参数:
  • sess (object) – 模型会话对象。

  • feed_dict (dict) – 用于评估的输入值。这是一个将图元素映射到值的字典。

返回值:

评估结果的列表,包括总损失值、数据损失值、预测分数和真实标签。

返回类型:

list

fit(train_file, valid_file, test_file=None)[source]#

使用 train_file 训练模型。每个 epoch 在 valid_file 上评估模型以观察训练状态。如果 test_file 不是 None,也会对其进行评估。

参数:
  • train_file (str) – 训练数据集。

  • valid_file (str) – 验证集。

  • test_file (str) – 测试集。

返回值:

self 的一个实例。

返回类型:

object

group_labels(labels, preds, group_keys)[source]#

根据 group keys 中的值将 labelspreds 划分为若干组。

参数:
  • labels (list) – 真实标签列表。

  • preds (list) – 预测分数列表。

  • group_keys (list) – 分组键列表。

返回值:

  • 分组后的标签。

  • 分组后的预测。

返回类型:

list, list

infer(sess, feed_dict)[source]#

给定特征数据 (在 feed_dict 中),使用当前模型获取预测分数。

参数:
  • sess (object) – 模型会话对象。

  • feed_dict (dict) – 要预测的实例。这是一个将图元素映射到值的字典。

返回值:

给定实例的预测分数。

返回类型:

list

load_model(model_path=None)[source]#

加载现有模型。

参数:

model_path – 模型路径。

抛出:

IOError – 如果恢复操作失败。

predict(infile_name, outfile_name)[source]#

对给定数据进行预测,并将预测分数输出到文件。

参数:
  • infile_name (str) – 输入文件名,格式与训练/验证/测试文件相同。

  • outfile_name (str) – 输出文件名,每行是一个预测分数。

返回值:

self 的一个实例。

返回类型:

object

run_eval(filename)[source]#

评估给定文件并返回一些评估指标。

参数:

filename (str) – 将要评估的文件名。

返回值:

包含评估指标的字典。

返回类型:

dict

train(sess, feed_dict)[source]#

使用 feed_dict 中的训练数据进行一次优化步骤。

参数:
  • sess (object) – 模型会话对象。

  • feed_dict (dict) – 用于训练模型的输入值。这是一个将图元素映射到值的字典。

返回值:

一个值列表,包括更新操作、总损失、数据损失和合并的 summary。

返回类型:

list

序列化基础模型#

class recommenders.models.deeprec.models.sequential.sequential_base_model.SequentialBaseModel(hparams, iterator_creator, graph=None, seed=None)[source]#

序列化模型的基础类

__init__(hparams, iterator_creator, graph=None, seed=None)[source]#

初始化模型。创建所有序列化模型所需的通用逻辑,例如损失函数、参数集。

参数:
  • hparams (HParams) – 一个 HParams 对象,包含全部超参数。

  • iterator_creator (object) – 用于加载数据的迭代器。

  • graph (object) – 可选的图。

  • seed (int) – 随机种子。

fit(train_file, valid_file, valid_num_ngs, eval_metric='group_auc')[source]#

使用 train_file 训练模型。每个 epoch 在 valid_file 上评估模型以观察训练状态。如果 test_file 不是 None,也会对其进行评估。

参数:
  • train_file (str) – 训练数据集。

  • valid_file (str) – 验证集。

  • valid_num_ngs (int) – 验证数据中每个正例对应的负例数量。

  • eval_metric (str) – 控制早停的指标。例如:“auc”、“group_auc”等。

返回值:

self 的一个实例。

返回类型:

object

predict(infile_name, outfile_name)[source]#

对给定数据进行预测,并将预测分数输出到文件。

参数:
  • infile_name (str) – 输入文件名。

  • outfile_name (str) – 输出文件名。

返回值:

self 的一个实例。

返回类型:

object

run_eval(filename, num_ngs)[source]#

评估给定文件并返回一些评估指标。

参数:
  • filename (str) – 将要评估的文件名。

  • num_ngs (int) – 每个正例的负采样数量。

返回值:

包含评估指标的字典。

返回类型:

dict

迭代器#

class recommenders.models.deeprec.io.iterator.BaseIterator[source]#

抽象基础迭代器类

abstract gen_feed_dict(data_dict)[source]#

抽象方法。构造一个将图元素映射到值的字典。

参数:

data_dict (dict) – 一个将字符串名称映射到 numpy 数组的字典。

abstract load_data_from_file(infile)[source]#

抽象方法。从文件读取和解析数据。

参数:

infile (str) – 文本输入文件。文件中的每一行是一个实例。

abstract parser_one_line(line)[source]#

抽象方法。将一个字符串行解析为特征值。

参数:

line (str) – 表示一个实例的字符串。

class recommenders.models.deeprec.io.iterator.FFMTextIterator(hparams, graph, col_spliter=' ', ID_spliter='%')[source]#

基于 FFM 格式的模型(如 xDeepFM)的数据加载器。迭代器不会将全部数据加载到内存中。相反,它按 mini-batch 将数据加载到内存中,以便可以使用大文件作为输入数据。

__init__(hparams, graph, col_spliter=' ', ID_spliter='%')[source]#

初始化迭代器。为模型创建必要的占位符。

参数:
  • hparams (object) – 全局超参数。其中包含一些关键设置,例如特征数量和字段数量。

  • graph (object) – 运行中的图。所有创建的占位符都将添加到此图中。

  • col_spliter (str) – 一行中的列分隔符。

  • ID_spliter (str) – 一行中的 ID 分隔符。

gen_feed_dict(data_dict)[source]#

构造一个将图元素映射到值的字典。

参数:

data_dict (dict) – 一个将字符串名称映射到 numpy 数组的字典。

返回值:

一个将图元素映射到 numpy 数组的字典。

返回类型:

dict

load_data_from_file(infile)[source]#

从文件读取和解析数据。

参数:

infile (str) – 文本输入文件。文件中的每一行是一个实例。

返回值:

一个迭代器,生成解析结果,格式为图的 feed_dict

返回类型:

object

parser_one_line(line)[source]#

将一个字符串行解析为特征值。

参数:

line (str) – 表示一个实例的字符串。

返回值:

解析结果,包括 labelfeaturesimpression_id

返回类型:

list

class recommenders.models.deeprec.io.dkn_iterator.DKNTextIterator(hparams, graph, col_spliter=' ', ID_spliter='%')[source]#

DKN 模型的数据加载器。DKN 需要一种特殊的数据格式,其中每个实例包含一个标签、候选新闻文章和用户点击过的新闻文章。文章由标题词和标题实体表示。词和实体是对齐的。

迭代器不会将全部数据加载到内存中。相反,它按 mini-batch 将数据加载到内存中,以便可以使用大文件作为输入数据。

__init__(hparams, graph, col_spliter=' ', ID_spliter='%')[source]#

初始化迭代器。为模型创建必要的占位符。

参数:
  • hparams (object) – 全局超参数。其中包含一些关键设置,例如特征数量和字段数量。

  • graph (object) – 运行中的图。所有创建的占位符都将添加到此图中。

  • col_spliter (str) – 一行中的列分隔符。

  • ID_spliter (str) – 一行中的 ID 分隔符。

gen_feed_dict(data_dict)[source]#

构造一个将图元素映射到值的字典。

参数:

data_dict (dict) – 一个将字符串名称映射到 numpy 数组的字典。

返回值:

一个将图元素映射到 numpy 数组的字典。

返回类型:

dict

gen_infer_feed_dict(data_dict)[source]#

构造一个将图元素映射到值的字典。

参数:

data_dict (dict) – 一个将字符串名称映射到 numpy 数组的字典。

返回值:

一个将图元素映射到 numpy 数组的字典。

返回类型:

dict

load_data_from_file(infile)[source]#

从文件读取和解析数据。

参数:

infile (str) – 文本输入文件。文件中的每一行是一个实例。

生成:

obj, list, int

  • 一个迭代器,生成解析结果,格式为图的 feed_dict

  • 曝光 ID 列表。

  • 一个 batch 中数据的大小。

load_infer_data_from_file(infile)[source]#

从文件读取并解析数据,用于推断文档嵌入。

参数:

infile (str) – 文本输入文件。文件中的每一行是一个实例。

生成:

obj, list, int

  • 一个迭代器,生成解析结果,格式为图的 feed_dict

  • 曝光 ID 列表。

  • 一个 batch 中数据的大小。

parser_one_line(line)[source]#

将一个字符串行解析为特征值。

参数:

line (str) – 表示一个实例的字符串

返回值:

解析结果,包括 labelcandidate_news_indexclick_news_indexcandidate_news_entity_indexclick_news_entity_indeximpression_id

返回类型:

list

class recommenders.models.deeprec.io.dkn_item2item_iterator.DKNItem2itemTextIterator(hparams, graph)[source]#
__init__(hparams, graph)[source]#

这个新的迭代器用于 DKN 的项到项推荐版本。可以在这个 notebook 中找到教程。

与用户到项推荐相比,我们不需要用户行为模块。因此占位符可以从原始的 DKNTextIterator 中简化。

参数:
  • hparams (object) – 全局超参数。

  • graph (object) – 运行中的图。

load_data_from_file(infile)[source]#

此函数将根据新闻文章 ID 查找 news_word_index 字典和 news_entity_index 字典,返回一个包含特征的数据 mini-batch。

参数:

infile (str) – 文件路径。infile 的每一行是一个新闻文章 ID。

生成:

dict, list, int

  • 一个将图元素映射到 numpy 数组的字典。

  • 包含新闻文章 ID 的列表。

  • 一个 batch 中数据的大小。

class recommenders.models.deeprec.io.nextitnet_iterator.NextItNetIterator(hparams, graph, col_spliter='\t')[source]#

NextItNet 模型的数据加载器。

NextItNet 需要一种特殊的数据格式。在训练阶段,每个实例将生成 (sequence_length * train_num_ngs) 个目标项和标签,以使 NextItNet 输出序列中除了最后一个项之外的每个项的预测。

__init__(hparams, graph, col_spliter='\t')[source]#

初始化迭代器。为模型创建必要的占位符。与 sequential iterator 不同。

参数:
  • hparams (object) – 全局超参数。其中包含一些关键设置,例如特征数量和字段数量。

  • graph (object) – 运行中的图。所有创建的占位符都将添加到此图中。

  • col_spliter (str) – 一行中的列分隔符。

class recommenders.models.deeprec.io.sequential_iterator.SequentialIterator(hparams, graph, col_spliter='\t')[source]#
__init__(hparams, graph, col_spliter='\t')[source]#

初始化迭代器。为模型创建必要的占位符。

参数:
  • hparams (object) – 全局超参数。其中包含一些关键设置,例如特征数量和字段数量。

  • graph (object) – 运行中的图。所有创建的占位符都将添加到此图中。

  • col_spliter (str) – 一行中的列分隔符。

gen_feed_dict(data_dict)[source]#

构造一个将图元素映射到值的字典。

参数:

data_dict (dict) – 一个将字符串名称映射到 numpy 数组的字典。

返回值:

一个将图元素映射到 numpy 数组的字典。

返回类型:

dict

load_data_from_file(infile, batch_num_ngs=0, min_seq_length=1)[source]#

从文件读取和解析数据。

参数:
  • infile (str) – 文本输入文件。文件中的每一行是一个实例。

  • batch_num_ngs (int) – 在此 batch 中负采样的数量。0 表示无需在此进行负采样。

  • min_seq_length (int) – 序列的最小长度。长度小于 min_seq_length 的序列将被忽略。

生成:

object – 一个迭代器,生成解析结果,格式为图的 feed_dict

parse_file(input_file)[source]#

将文件解析为列表,以便用于下游任务。

参数:

input_file – 尚未解析过的 train、valid 或 test 文件之一。

返回值:

包含解析结果的列表。

返回类型:

list

parser_one_line(line)[source]#

将一个字符串行解析为特征值。

参数:

line (str) – 表示一个实例的字符串。此字符串包含 Tab 分隔的值,包括:label、user_hash、item_hash、item_cate、operation_time、item_history_sequence、item_cate_history_sequence 和 time_history_sequence。

返回值:

解析结果,包括 labeluser_iditem_iditem_cateitem_history_sequencecate_history_sequencecurrent_timetime_difftime_from_first_actiontime_to_now

返回类型:

list

数据处理工具#

class recommenders.models.deeprec.DataModel.ImplicitCF.ImplicitCF(train, test=None, adj_dir=None, col_user='userID', col_item='itemID', col_rating='rating', col_prediction='prediction', seed=None)[source]#

使用隐式反馈的 GCN 模型的数据处理类。

初始化训练集和测试集,创建归一化邻接矩阵并为训练 epoch 采样数据。

__init__(train, test=None, adj_dir=None, col_user='userID', col_item='itemID', col_rating='rating', col_prediction='prediction', seed=None)[source]#

构造函数

参数:
  • adj_dir (str) – 保存/加载邻接矩阵的目录。如果为 None,将创建邻接矩阵但不会保存。

  • train (pandas.DataFrame) – 至少包含 (col_user, col_item, col_rating) 列的训练数据。

  • test (pandas.DataFrame) – 至少包含 (col_user, col_item, col_rating) 列的测试数据。test 可以为 None,此时我们只处理训练数据。

  • col_user (str) – 用户列名。

  • col_item (str) – 物品列名。

  • col_rating (str) – 评分列名。

  • seed (int) – 种子。

create_norm_adj_mat()[source]#

创建归一化邻接矩阵。

返回值:

归一化邻接矩阵。

返回类型:

scipy.sparse.csr_matrix

get_norm_adj_mat()[source]#

如果存在则加载归一化邻接矩阵,否则创建(并保存)它。

返回值:

归一化邻接矩阵。

返回类型:

scipy.sparse.csr_matrix

train_loader(batch_size)[source]#

每个 batch 采样训练数据。为每个用户采样一个正向物品和一个负向物品。

参数:

batch_size (int) – 用户的 batch 大小。

返回值:

  • 采样的用户。

  • 采样的正向物品。

  • 采样的负向物品。

返回类型:

numpy.ndarray, numpy.ndarray, numpy.ndarray

工具#

class recommenders.models.deeprec.deeprec_utils.HParams(hparams_dict)[source]#

用于存储 DeepRec 算法超参数的类。

__init__(hparams_dict)[source]#

从超参数值字典创建 HParams 对象。

参数:

hparams_dict (dict) – 包含模型超参数的字典。

__repr__()[source]#

返回 repr(self)。

values()[source]#

以字典形式返回超参数值。

返回值:

包含超参数值的字典。

返回类型:

dict

recommenders.models.deeprec.deeprec_utils.cal_metric(labels, preds, metrics)[source]#

计算指标。

可用选项包括:auc, rmse, logloss, acc (准确率), f1, mean_mrr, ndcg (格式如:ndcg@2;4;6;8), hit (格式如:hit@2;4;6;8), group_auc

参数:
  • labels (array-like) – 标签。

  • preds (array-like) – 预测值。

  • metrics (list) – 指标名称列表。

返回值:

指标。

返回类型:

dict

示例

>>> cal_metric(labels, preds, ["ndcg@2;4;6", "group_auc"])
{'ndcg@2': 0.4026, 'ndcg@4': 0.4953, 'ndcg@6': 0.5346, 'group_auc': 0.8096}
recommenders.models.deeprec.deeprec_utils.check_nn_config(f_config)[source]#

检查神经网络配置。

参数:

f_config (dict) – 神经网络配置。

抛出:

ValueError – 如果参数不正确。

recommenders.models.deeprec.deeprec_utils.check_type(config)[source]#

检查配置参数是否为正确的类型

参数:

config (dict) – 配置字典。

抛出:

TypeError – 如果参数类型不正确。

recommenders.models.deeprec.deeprec_utils.create_hparams(flags)[source]#

创建模型超参数。

参数:

flags (dict) – 包含模型要求的字典。

返回值:

超参数对象。

返回类型:

HParams

recommenders.models.deeprec.deeprec_utils.dcg_score(y_true, y_score, k=10)[source]#

计算 k 处的 DCG 分数指标。

参数:
  • y_true (np.ndarray) – 真实标签。

  • y_score (np.ndarray) – 预测标签。

返回值:

DCG 分数。

返回类型:

np.ndarray

recommenders.models.deeprec.deeprec_utils.download_deeprec_resources(azure_container_url, data_path, remote_resource_name)[source]#

下载资源。

参数:
  • azure_container_url (str) – Azure 容器的 URL。

  • data_path (str) – 下载资源的路径。

  • remote_resource_name (str) – 资源的名称。

recommenders.models.deeprec.deeprec_utils.flat_config(config)[source]#

将从 YAML 文件加载的配置展平为扁平字典。

参数:

config (dict) – 从 YAML 文件加载的配置。

返回值:

配置字典。

返回类型:

dict

recommenders.models.deeprec.deeprec_utils.hit_score(y_true, y_score, k=10)[source]#

计算 k 处的命中分数指标。

参数:
  • y_true (np.ndarray) – 真实标签。

  • y_score (np.ndarray) – 预测标签。

返回值:

命中分数。

返回类型:

np.ndarray

recommenders.models.deeprec.deeprec_utils.load_dict(filename)[source]#

加载词汇表。

参数:

filename (str) – 用户、物品或类别词汇表的文件名。

返回值:

已保存的词汇表。

返回类型:

dict

recommenders.models.deeprec.deeprec_utils.load_yaml(filename)[source]#

加载 YAML 文件。

参数:

filename (str) – 文件名。

返回值:

字典。

返回类型:

dict

recommenders.models.deeprec.deeprec_utils.mrr_score(y_true, y_score)[source]#

计算 MRR 分数指标。

参数:
  • y_true (np.ndarray) – 真实标签。

  • y_score (np.ndarray) – 预测标签。

返回值:

MRR 分数。

返回类型:

numpy.ndarray

recommenders.models.deeprec.deeprec_utils.ndcg_score(y_true, y_score, k=10)[source]#

计算 k 处的 NDCG 分数指标。

参数:
  • y_true (np.ndarray) – 真实标签。

  • y_score (np.ndarray) – 预测标签。

返回值:

NDCG 分数。

返回类型:

numpy.ndarray

recommenders.models.deeprec.deeprec_utils.prepare_hparams(yaml_file=None, **kwargs)[source]#

准备模型超参数并检查所有参数值是否正确。

参数:

yaml_file (str) – 作为配置的 YAML 文件。

返回值:

超参数对象。

返回类型:

HParams

DKN#

class recommenders.models.deeprec.models.dkn.DKN(hparams, iterator_creator)[source]#

DKN 模型 (Deep Knowledge-Aware Network)

引用:

H. Wang, F. Zhang, X. Xie and M. Guo, “DKN: Deep Knowledge-Aware Network for News Recommendation”, in Proceedings of the 2018 World Wide Web Conference on World Wide Web, 2018.

__init__(hparams, iterator_creator)[source]#

DKN 的初始化步骤。与 BaseModel 相比,DKN 需要两种不同的预计算嵌入:词嵌入和实体嵌入。创建这两个嵌入变量后,将调用 BaseModel 的 __init__ 方法。

参数:
  • hparams (object) – 全局超参数。

  • iterator_creator (object) – DKN 数据加载器类。

infer_embedding(sess, feed_dict)[source]#

使用当前模型在 feed_dict 中推断文档嵌入。

参数:
  • sess (object) – 模型会话对象。

  • feed_dict (dict) – 用于评估的输入值。这是一个将图元素映射到值的字典。

返回值:

一个批次中的新闻嵌入。

返回类型:

list

run_get_embedding(infile_name, outfile_name)[source]#

使用当前模型推断文档嵌入。

参数:
  • infile_name (str) – 输入文件名,格式为 [Newsid] [w1,w2,w3…] [e1,e2,e3…]

  • outfile_name (str) – 输出文件名,格式为 [Newsid] [embedding]

返回值:

self 的一个实例。

返回类型:

object

DKN item-to-item#

class recommenders.models.deeprec.models.dkn_item2item.DKNItem2Item(hparams, iterator_creator)[source]#

使用 DKN 进行物品到物品推荐的类。参阅 microsoft/recommenders

eval(sess, feed_dict)[source]#

使用当前模型评估 feed_dict 中的数据。

参数:
  • sess (object) – 模型会话对象。

  • feed_dict (dict) – 用于评估的输入值。这是一个将图元素映射到值的字典。

返回值:

包含预测和标签数组的元组。

返回类型:

numpy.ndarray, numpy.ndarray

run_eval(filename)[source]#

评估给定文件并返回一些评估指标。

参数:

filename (str) – 将要评估的文件名。

返回值:

包含评估指标的字典。

返回类型:

dict

xDeepFM#

class recommenders.models.deeprec.models.xDeepFM.XDeepFMModel(hparams, iterator_creator, graph=None, seed=None)[source]#

xDeepFM 模型

引用:

J. Lian, X. Zhou, F. Zhang, Z. Chen, X. Xie, G. Sun, “xDeepFM: Combining Explicit and Implicit Feature Interactions for Recommender Systems”, in Proceedings of the 24th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining, KDD 2018, London, 2018.

LightGCN#

class recommenders.models.deeprec.models.graphrec.lightgcn.LightGCN(hparams, data, seed=None)[source]#

LightGCN 模型

引用:

He, Xiangnan, Kuan Deng, Xiang Wang, Yan Li, Yongdong Zhang, and Meng Wang. “LightGCN: Simplifying and Powering Graph Convolution Network for Recommendation.” arXiv preprint arXiv:2002.02126, 2020.

__init__(hparams, data, seed=None)[source]#

初始化模型。创建参数、占位符、嵌入和损失函数。

参数:
  • hparams (HParams) – 一个 HParams 对象,包含完整的超参数集。

  • data (object) – 一个 recommenders.models.deeprec.DataModel.ImplicitCF 对象,加载和处理数据。

  • seed (int) – 种子。

fit()[source]#

在 self.data.train 上拟合模型。如果 eval_epoch 不为 -1,则每隔 eval_epoch 轮在 self.data.test 上评估模型以观察训练状态。

infer_embedding(user_file, item_file)[source]#

将用户和物品嵌入导出到 CSV 文件。

参数:
  • user_file (str) – 保存用户嵌入的文件路径。

  • item_file (str) – 保存物品嵌入的文件路径。

load(model_path=None)[source]#

加载现有模型。

参数:

model_path – 模型路径。

抛出:

IOError – 如果恢复操作失败。

recommend_k_items(test, top_k=10, sort_top_k=True, remove_seen=True, use_id=False)[source]#

为测试集中的所有用户推荐 Top K 物品。

参数:
  • test (pandas.DataFrame) – 测试数据。

  • top_k (int) – 推荐的 Top 物品数量。

  • sort_top_k (bool) – 是否对 Top K 结果进行排序的标志。

  • remove_seen (bool) – 从推荐中移除训练集中已见过物品的标志。

返回值:

为每个用户推荐的 Top k 物品。

返回类型:

pandas.DataFrame

run_eval()[source]#

在 self.data.test 上运行评估。

返回值:

self.metrics 中所有指标的结果。

返回类型:

dict

score(user_ids, remove_seen=True)[source]#

为测试用户的所有物品评分。

参数:
  • user_ids (np.array) – 要测试的用户。

  • remove_seen (bool) – 从推荐中移除训练集中已见过物品的标志。

返回值:

用户对所有物品的兴趣值。

返回类型:

numpy.ndarray

A2SVD#

class recommenders.models.deeprec.models.sequential.asvd.A2SVDModel(hparams, iterator_creator, graph=None, seed=None)[source]#

A2SVD 模型 (Attentive Asynchronous Singular Value Decomposition)

它通过注意力模块扩展了 ASVD。

引用:

ASVD: Y. Koren, “Factorization Meets the Neighborhood: a Multifaceted Collaborative Filtering Model”, in Proceedings of the 14th ACM SIGKDD international conference on Knowledge discovery and data mining, pages 426–434, ACM, 2008.

A2SVD: Z. Yu, J. Lian, A. Mahmoody, G. Liu and X. Xie, “Adaptive User Modeling with Long and Short-Term Preferences for Personailzed Recommendation”, in Proceedings of the 28th International Joint Conferences on Artificial Intelligence, IJCAI’19, Pages 4213-4219, AAAI Press, 2019.

Caser#

class recommenders.models.deeprec.models.sequential.caser.CaserModel(hparams, iterator_creator, seed=None)[source]#

Caser 模型

引用:

J. Tang and K. Wang, “Personalized top-n sequential recommendation via convolutional sequence embedding”, in Proceedings of the Eleventh ACM International Conference on Web Search and Data Mining, ACM, 2018.

__init__(hparams, iterator_creator, seed=None)[source]#

Caser 变量的初始化

参数:
  • hparams (HParams) – 一个 HParams 对象,包含完整的超参数集。

  • iterator_creator (object) – 用于加载数据的迭代器。

GRU#

NextItNet#

class recommenders.models.deeprec.models.sequential.nextitnet.NextItNetModel(hparams, iterator_creator, graph=None, seed=None)[source]#

NextItNet 模型

引用:

Yuan, Fajie, et al. “A Simple Convolutional Generative Network for Next Item Recommendation”, in Web Search and Data Mining, 2019.

注意

它需要数据集具有很强的序列性。

RNN Cells#

实现 RNN Cells 的模块。

此模块提供了许多常用的基本 RNN 单元,例如 LSTM (长短期记忆) 或 GRU (门控循环单元),以及允许为输入添加 dropout、投影或嵌入的许多运算符。MultiRNNCell 类支持构建多层单元,也可以通过多次调用 rnn 操作来实现。

class recommenders.models.deeprec.models.sequential.rnn_cell_implement.Time4ALSTMCell(*args, **kwargs)[source]#
call(inputs, state)[source]#

Time4ALSTMCell 的调用方法。

参数:
  • inputs – 一个形状为 [batch_size, input_size] 的二维 Tensor。

  • state – 一个形状为 [batch_size, state_size] 的二维 Tensor。

返回值:

  • 一个形状为 [batch_size, output_size] 的二维 Tensor。

  • 一个形状为 [batch_size, state_size] 的二维 Tensor。

返回类型:

一个包含以下内容的元组

property output_size#

此单元格产生的输出的大小。

类型:

整数或 TensorShape

property state_size#

此单元格使用的状态的大小。

它可以由整数、TensorShape 或整数或 TensorShape 的元组表示。

class recommenders.models.deeprec.models.sequential.rnn_cell_implement.Time4LSTMCell(*args, **kwargs)[源代码]#
call(inputs, state)[源代码]#

Time4LSTMCell 的调用方法。

参数:
  • inputs – 一个形状为 [batch_size, input_size] 的二维 Tensor。

  • state – 一个形状为 [batch_size, state_size] 的二维 Tensor。

返回值:

  • 一个形状为 [batch_size, output_size] 的二维 Tensor。

  • 一个形状为 [batch_size, state_size] 的二维 Tensor。

返回类型:

一个包含以下内容的元组

property output_size#

此单元格产生的输出的大小。

类型:

整数或 TensorShape

property state_size#

此单元格使用的状态的大小。

它可以由整数、TensorShape 或整数或 TensorShape 的元组表示。

SUM#

SLIRec#

class recommenders.models.deeprec.models.sequential.sli_rec.SLI_RECModel(hparams, iterator_creator, graph=None, seed=None)[源代码]#

SLI Rec 模型

引用:

Z. Yu, J. Lian, A. Mahmoody, G. Liu and X. Xie, “Adaptive User Modeling with Long and Short-Term Preferences for Personailzed Recommendation”, in Proceedings of the 28th International Joint Conferences on Artificial Intelligence, IJCAI’19, Pages 4213-4219, AAAI Press, 2019.

FastAI 工具函数#

recommenders.models.fastai.fastai_utils.cartesian_product(*arrays)[源代码]#

在 fastai 算法中计算笛卡尔积。这是一个辅助函数。

参数:

arrays (tuple of numpy.ndarray) – 输入数组

返回值:

乘积

返回类型:

numpy.ndarray

recommenders.models.fastai.fastai_utils.hide_fastai_progress_bar()[源代码]#

隐藏 fastai 进度条

recommenders.models.fastai.fastai_utils.score(learner, test_df, user_col='userID', item_col='itemID', prediction_col='prediction', top_k=None)[源代码]#

对提供的所有用户+项目进行评分,如果 top_k>0,则每个用户只保留 top_k 个项目

参数:
  • learner (object) – 模型。

  • test_df (pandas.DataFrame) – 测试 DataFrame。

  • user_col (str) – 用户列名。

  • item_col (str) – 项目列名。

  • prediction_col (str) – 预测列名。

  • top_k (int) – 推荐的 Top 物品数量。

返回值:

推荐结果

返回类型:

pandas.DataFrame

LightFM 工具函数#

recommenders.models.lightfm.lightfm_utils.compare_metric(df_list, metric='prec', stage='test')[源代码]#

将 DataFrame 列表合并并准备成整洁格式的函数。

参数:
  • df_list (list) – DataFrame 列表

  • metrics (str) – 要提取的指标名称,可选

  • stage (str) – 要提取的模型拟合阶段名称,可选

返回值:

Metrics

返回类型:

pandas.DataFrame

recommenders.models.lightfm.lightfm_utils.model_perf_plots(df)[源代码]#

绘制模型性能指标的函数。

参数:

df (pandas.DataFrame) – 整洁格式的 DataFrame,包含 [‘epoch’,’level’,’value’] 列

返回值:

matplotlib 坐标轴

返回类型:

object

recommenders.models.lightfm.lightfm_utils.prepare_all_predictions(data, uid_map, iid_map, interactions, model, num_threads, user_features=None, item_features=None)[源代码]#

准备所有预测以进行评估的函数。:param data: 加载的所有用户、项目和评分的 DataFrame :type data: pandas df :param uid_map: 用于将内部用户索引映射到外部 ID 的键。 :type uid_map: dict :param iid_map: 用于将内部项目索引映射到外部 ID 的键。 :type iid_map: dict :param interactions: 用户-项目交互 :type interactions: np.float32 coo_matrix :param model: 已拟合的 LightFM 模型 :type model: LightFM instance :param num_threads: 并行计算线程数 :type num_threads: int :param user_features: 用户在特征上的权重 :type user_features: np.float32 csr_matrix :param item_features: 项目在特征上的权重 :type item_features: np.float32 csr_matrix

返回值:

所有预测

返回类型:

pandas.DataFrame

recommenders.models.lightfm.lightfm_utils.prepare_test_df(test_idx, uids, iids, uid_map, iid_map, weights)[源代码]#

准备测试 DataFrame 以进行评估的函数

参数:
  • test_idx (slice) – 测试索引的切片

  • uids (numpy.ndarray) – 内部用户索引数组

  • iids (numpy.ndarray) – 内部项目索引数组

  • uid_map (dict) – 用于将内部用户索引映射到外部 ID 的键。

  • iid_map (dict) – 用于将内部项目索引映射到外部 ID 的键。

  • weights (numpy.float32 coo_matrix) – 用户-项目交互

返回值:

选择用于测试的用户-项目对

返回类型:

pandas.DataFrame

recommenders.models.lightfm.lightfm_utils.similar_items(item_id, item_features, model, N=10)[源代码]#

根据 lyst/lightfm#244 返回 top N 个相似项目的函数

参数:
  • item_id (int) – 用作参考的项目 ID

  • item_features (scipy sparse CSR matrix) – 项目特征矩阵

  • model (LightFM instance) – 已拟合的 LightFM 模型

  • N (int) – 要返回的 top N 个相似项目的数量

返回值:

评分最高的 top N 个最相似项目

返回类型:

pandas.DataFrame

recommenders.models.lightfm.lightfm_utils.similar_users(user_id, user_features, model, N=10)[源代码]#

根据 lyst/lightfm#244 返回 top N 个相似用户的函数

参数

user_id (int): 用作参考的用户 ID user_features (scipy sparse CSR matrix): 用户特征矩阵 model (LightFM instance): 已拟合的 LightFM 模型 N (int): 要返回的 top N 个相似用户的数量

返回值:

评分最高的 top N 个最相似用户

返回类型:

pandas.DataFrame

recommenders.models.lightfm.lightfm_utils.track_model_metrics(model, train_interactions, test_interactions, k=10, no_epochs=100, no_threads=8, show_plot=True, **kwargs)[源代码]#

记录模型在每个 epoch 的性能,将性能格式化为整洁格式,绘制性能图并输出性能数据的函数。

参数:
  • model (LightFM instance) – 已拟合的 LightFM 模型

  • train_interactions (scipy sparse COO matrix) – 训练交互集

  • test_interactions (scipy sparse COO matrix) – 测试交互集

  • k (int) – 推荐数量,可选

  • no_epochs (int) – 运行的 epoch 数量,可选

  • no_threads (int) – 使用的并行线程数,可选

  • **kwargs – 要传递的其他关键字参数

返回值:

  • 已拟合模型的性能跟踪

  • 已拟合模型

  • 方法的副作用

返回类型:

pandas.DataFrame, LightFM model, matplotlib 坐标轴

LightGBM 工具函数#

class recommenders.models.lightgbm.lightgbm_utils.NumEncoder(cate_cols, nume_cols, label_col, threshold=10, thresrate=0.99)[源代码]#

通过顺序标签编码、顺序计数编码和二元编码将所有类别特征编码为数值特征。此外,它还过滤低频类别并填充缺失值。

fit_transform(df)[源代码]#

输入训练集 (pandas.DataFrame) 并返回转换后的 2 个 numpy.ndarray (x,y)。

参数:

df (pandas.DataFrame) – 输入 DataFrame

返回值:

新特征和标签。

返回类型:

numpy.ndarray, numpy.ndarray

transform(df)[源代码]#

输入测试/验证集 (pandas.DataFrame) 并返回转换后的 2 个 numpy.ndarray (x,y)。

参数:

df (pandas.DataFrame) – 输入 DataFrame

返回值:

新特征和标签。

返回类型:

numpy.ndarray, numpy.ndarray

recommenders.models.lightgbm.lightgbm_utils.unpackbits(x, num_bits)[源代码]#

将十进制值的 numpy.ndarray 转换为多二元值的 numpy.ndarray ([1,2]->[[0,1],[1,0]])

参数:
  • x (numpy.ndarray) – 十进制数组。

  • num_bits (int) – 转换后的二元值的最大长度。

NCF#

class recommenders.models.ncf.dataset.DataFile(filename, col_user, col_item, col_rating, col_test_batch=None, binary=True)[源代码]#

NCF 的 DataFile 类。一个用于从 csv 文件读取数据的迭代器。数据必须按用户排序。包含从文件加载用户数据、格式化并返回 Pandas DataFrame 的实用工具。

__init__(filename, col_user, col_item, col_rating, col_test_batch=None, binary=True)[源代码]#

构造函数

参数:
  • filename (str) – 要处理的文件路径。

  • col_user (str) – 用户列名。

  • col_item (str) – 物品列名。

  • col_rating (str) – 评分列名。

  • col_test_batch (str) – 测试批次列名。

  • binary (bool) – 如果为 true,将评分 > 0 设置为评分 = 1。

load_data(key, by_user=True)[源代码]#

加载指定用户或测试批次的数据

参数:
  • key (int) – 用户或测试批次索引

  • by_user (bool) – 如果为 True,按用户加载数据;否则按测试批次加载。

返回值:

pandas.DataFrame

class recommenders.models.ncf.dataset.Dataset(train_file, test_file=None, test_file_full=None, overwrite_test_file_full=False, n_neg=4, n_neg_test=100, col_user='userID', col_item='itemID', col_rating='rating', binary=True, seed=None, sample_with_replacement=False, print_warnings=False)[源代码]#

NCF 的 Dataset 类

__init__(train_file, test_file=None, test_file_full=None, overwrite_test_file_full=False, n_neg=4, n_neg_test=100, col_user='userID', col_item='itemID', col_rating='rating', binary=True, seed=None, sample_with_replacement=False, print_warnings=False)[源代码]#

构造函数

参数:
  • train_file (str) – 训练数据集文件的路径。

  • test_file (str) – 用于留一评估的测试数据集文件路径。

  • test_file_full (str) – 包含负样本的完整测试数据集文件路径。

  • overwrite_test_file_full (bool) – 如果为 true,则重新创建并覆盖 test_file_full。

  • n_neg (int) – 训练集中每个正样本对应的负样本数量。

  • n_neg_test (int) – 测试集中每个正样本对应的负样本数量。

  • col_user (str) – 用户列名。

  • col_item (str) – 物品列名。

  • col_rating (str) – 评分列名。

  • binary (bool) – 如果为 true,将评分 > 0 设置为评分 = 1。

  • seed (int) – 种子。

  • sample_with_replacement (bool) – 如果为 true,则有放回地采样负样本,否则无放回地采样。

  • print_warnings (bool) – 如果为 true,则在无放回采样时,如果项目数量不足以满足 n_neg 或 n_neg_test 时打印警告。

test_loader(yield_id=False)[源代码]#

用于为留一评估提供测试数据批次的生成器。数据从 test_file_full 加载。

参数:

yield_id (bool) – 如果为 true,返回分配的用户和项目 ID;否则返回原始值。

返回值:

list

train_loader(batch_size, shuffle_size=None, yield_id=False, write_to=None)[源代码]#

用于为训练数据提供批次的生成器。正样本从原始训练文件加载,并添加负样本。数据被加载到内存中的一个洗牌缓冲区中,最多为 shuffle_size 行,然后进行洗牌并释放。如果遇到内存不足错误,请尝试减小 shuffle_size。

参数:
  • batch_size (int) – 每个批次中的样本数量。

  • shuffle_size (int) – 洗牌缓冲区中的最大样本数量。

  • yield_id (bool) – 如果为 true,返回分配的用户和项目 ID;否则返回原始值。

  • write_to (str) – 写入完整数据集(包括负样本)的文件路径。

返回值:

list

exception recommenders.models.ncf.dataset.EmptyFileException[源代码]#

如果文件为空时引发的异常

exception recommenders.models.ncf.dataset.FileNotSortedException[源代码]#

如果文件未正确排序时引发的异常

exception recommenders.models.ncf.dataset.MissingFieldsException[源代码]#

如果文件缺少预期字段时引发的异常

exception recommenders.models.ncf.dataset.MissingUserException[源代码]#

如果用户不在文件中时引发的异常

class recommenders.models.ncf.dataset.NegativeSampler(user, n_samples, user_positive_item_pool, item_pool, sample_with_replacement, print_warnings=True, training=True)[源代码]#

NCF 的 NegativeSampler 类。从给定的项目总体中采样负项目的一个子集。

__init__(user, n_samples, user_positive_item_pool, item_pool, sample_with_replacement, print_warnings=True, training=True)[源代码]#

构造函数

参数:
  • user (str or int) – 要采样的用户。

  • n_samples (int) – 所需的样本数量。

  • user_positive_item_pool (set) – 用户之前已交互的项目集合。

  • item_pool (set) – 总体中所有项目的集合。

  • sample_with_replacement (bool) – 如果为 true,则有放回地采样负样本,否则无放回地采样。

  • print_warnings (bool) – 如果为 true,则在无放回采样时,如果项目数量不足以满足 n_neg 或 n_neg_test 时打印警告。

  • training (bool) – 如果为训练集采样则设为 true,如果为测试集则设为 false。

sample()[源代码]#

从负项目总体中均匀采样的方

返回: list

class recommenders.models.ncf.ncf_singlenode.NCF(n_users, n_items, model_type='NeuMF', n_factors=8, layer_sizes=[16, 8, 4], n_epochs=50, batch_size=64, learning_rate=0.005, verbose=1, seed=None)[源代码]#

神经协同过滤 (NCF) 实现

引用:

He, Xiangnan, Lizi Liao, Hanwang Zhang, Liqiang Nie, Xia Hu, and Tat-Seng Chua. “Neural collaborative filtering.” In Proceedings of the 26th International Conference on World Wide Web, pp. 173-182. International World Wide Web Conferences Steering Committee, 2017. Link: https://www.comp.nus.edu.sg/~xiangnan/papers/ncf.pdf

__init__(n_users, n_items, model_type='NeuMF', n_factors=8, layer_sizes=[16, 8, 4], n_epochs=50, batch_size=64, learning_rate=0.005, verbose=1, seed=None)[源代码]#

构造函数

参数:
  • n_users (int) – 数据集中的用户数量。

  • n_items (int) – 数据集中的项目数量。

  • model_type (str) – 模型类型。

  • n_factors (int) – 潜在空间的维度。

  • layer_sizes (list) – MLP 的层数。

  • n_epochs (int) – 训练的 epoch 数量。

  • batch_size (int) – 批次大小。

  • learning_rate (float) – 学习率。

  • verbose (int) – 是否显示训练输出。

  • seed (int) – 种子。

fit(data)[源代码]#

使用训练数据拟合模型

参数:

data (NCFDataset) – ./dataset.py 中初始化的 Dataset。

load(gmf_dir=None, mlp_dir=None, neumf_dir=None, alpha=0.5)[源代码]#

加载模型参数以供进一步使用。

GMF 模型 –> 从 gmf_dir 加载参数

MLP 模型 –> 从 mlp_dir 加载参数

NeuMF 模型 –> 从 neumf_dir 或从 gmf_dirmlp_dir 加载参数

参数:
  • gmf_dir (str) – GMF 模型的目录名。

  • mlp_dir (str) – MLP 模型的目录名。

  • neumf_dir (str) – neumf 模型的目录名。

  • alpha (float) – gmf 和 mlp 输出层的连接超参数。

返回值:

在此模型中加载参数。

返回类型:

object

predict(user_input, item_input, is_list=False)[源代码]#

此训练模型的预测函数

参数:
  • user_input (list or element of list) – 用户 ID 或用户 ID 列表

  • item_input (list or element of list) – 项目 ID 或项目 ID 列表

  • is_list (bool) – 如果为 true,输入为列表类型,注意列表式预测比元素式预测快。

返回值:

预测评分列表或预测评分值。

返回类型:

list 或 float

save(dir_name)[源代码]#

将模型参数保存在 dir_name

参数:

dir_name (str) – 目录名,应为文件夹名而不是文件名,如果不存在则会创建新目录。

NewsRec 工具函数#

基础模型#

class recommenders.models.newsrec.models.base_model.BaseModel(hparams, iterator_creator, seed=None)[源代码]#

模型的基础类

hparams#

一个 HParams 对象,包含整个超参数集。

类型:

HParams

train_iterator#

一个在训练步骤中加载数据的迭代器。

类型:

object

test_iterator#

一个在测试步骤中加载数据的迭代器。

类型:

object

graph#

一个可选的图。

类型:

object

seed#

随机种子。

类型:

int

__init__(hparams, iterator_creator, seed=None)[源代码]#

初始化模型。创建所有 deeprec 模型所需的通用逻辑,例如损失函数、参数集。

参数:
  • hparams (HParams) – 一个 HParams 对象,包含整个超参数集。

  • iterator_creator (object) – 用于加载数据的迭代器。

  • graph (object) – 可选的图。

  • seed (int) – 随机种子。

eval(eval_batch_data)[源代码]#

使用当前模型评估 feed_dict 中的数据。

参数:
  • sess (object) – 模型会话对象。

  • feed_dict (dict) – 用于评估的输入值。这是一个将图元素映射到值的字典。

返回值:

评估结果的列表,包括总损失值、数据损失值、预测分数和真实标签。

返回类型:

list

fit(train_news_file, train_behaviors_file, valid_news_file, valid_behaviors_file, test_news_file=None, test_behaviors_file=None, step_limit=None)[源代码]#

使用 train_file 拟合模型。每个 epoch 在 valid_file 上评估模型以观察训练状态。如果 test_news_file 不为 None,也进行评估。

参数:
  • train_file (str) – 训练数据集。

  • valid_file (str) – 验证集。

  • test_news_file (str) – 测试集。

返回值:

self 的一个实例。

返回类型:

object

group_labels(labels, preds, group_keys)[源代码]#

根据分组键中的值将标签和预测分为几组。

参数:
  • labels (list) – 真实标签列表。

  • preds (list) – 预测分数列表。

  • group_keys (list) – 分组键列表。

返回值:

  • 分组后的键。

  • 分组后的标签。

  • 分组后的预测。

返回类型:

list, list, list

run_eval(news_filename, behaviors_file)[源代码]#

评估给定文件并返回一些评估指标。

参数:

filename (str) – 将要评估的文件名。

返回值:

包含评估指标的字典。

返回类型:

dict

train(train_batch_data)[源代码]#

使用 feed_dict 中的训练数据执行一次优化步骤。

参数:
  • sess (object) – 模型会话对象。

  • feed_dict (dict) – 用于训练模型的输入值。这是一个将图元素映射到值的字典。

返回值:

一个值列表,包括更新操作、总损失、数据损失和合并的 summary。

返回类型:

list

迭代器#

class recommenders.models.newsrec.io.mind_iterator.MINDIterator(hparams, npratio=-1, col_spliter='\t', ID_spliter='%')[源代码]#

NAML 模型 的训练数据加载器。该模型需要一种特殊的数据格式,其中每个实例包含一个标签、曝光 ID、用户 ID、候选新闻文章和用户点击的新闻文章。文章由标题词、正文词、主要类别和子类别表示。

迭代器不会将全部数据加载到内存中。相反,它按 mini-batch 将数据加载到内存中,以便可以使用大文件作为输入数据。

col_spliter#

一行中的列分隔符。

类型:

str

ID_spliter#

一行中的 ID 分隔符。

类型:

str

batch_size#

一个批次中的样本数量。

类型:

int

title_size#

新闻标题中的最大词数。

类型:

int

his_size#

用户点击历史中最大点击新闻数量。

类型:

int

npratio#

负样本与正样本的比例,用于负采样。-1 表示不需要负采样。

类型:

int

__init__(hparams, npratio=-1, col_spliter='\t', ID_spliter='%')[源代码]#

初始化迭代器。为模型创建必要的占位符。

参数:
  • hparams (object) – 全局超参数。包含一些关键设置,例如 head_num 和 head_dim。

  • npratio (int) – 负样本与正样本的比例,用于负采样。-1 表示不需要负采样。

  • col_spliter (str) – 一行中的列分隔符。

  • ID_spliter (str) – 一行中的 ID 分隔符。

init_behaviors(behaviors_file)[源代码]#

根据 behaviors 文件初始化行为日志。

参数: behaviors_file: behaviors 文件路径

init_news(news_file)[源代码]#

根据 news 文件初始化新闻信息,例如 news_title_index 和 nid2index。:param news_file: news 文件路径

load_data_from_file(news_file, behavior_file)[源代码]#

从 news 文件和 behavior 文件读取并解析数据。

参数:
  • news_file (str) – 包含新闻信息的文件。

  • beahaviros_file (str) – 包含用户曝光信息的文件。

生成:

object – 一个迭代器,以 dict 格式生成解析结果。

load_dict(file_path)[源代码]#

加载 pickle 文件

参数:

path (file) – 文件路径

返回值:

pickle 加载的对象

返回类型:

object

load_impression_from_file(behaivors_file)[源代码]#

从 behaivors 文件读取并解析曝光数据。

参数:

behaivors_file (str) – 包含行为信息的文件。

生成:

object – 一个迭代器,以 dict 格式生成解析后的曝光数据。

load_news_from_file(news_file)[源代码]#

从 news 文件读取并解析用户数据。

参数:

news_file (str) – 包含新闻信息的文件。

生成:

object – 一个迭代器,以 dict 格式生成解析后的新闻特征。

load_user_from_file(news_file, behavior_file)[源代码]#

从 news 文件和 behavior 文件读取并解析用户数据。

参数:
  • news_file (str) – 包含新闻信息的文件。

  • beahaviros_file (str) – 包含用户曝光信息的文件。

生成:

object – 一个迭代器,以 dict 格式生成解析后的用户特征。

parser_one_line(line)[源代码]#

将一个行为样本解析为特征值。如果 npratio 大于 0,返回负采样结果。

参数:

line (int) – 样本索引。

生成:

list – 解析结果,包括标签、曝光 ID、用户 ID、candidate_title_index、clicked_title_index。

class recommenders.models.newsrec.io.mind_all_iterator.MINDAllIterator(hparams, npratio=-1, col_spliter='\t', ID_spliter='%')[源代码]#

NAML 模型 的训练数据加载器。该模型需要一种特殊的数据格式,其中每个实例包含一个标签、曝光 ID、用户 ID、候选新闻文章和用户点击的新闻文章。文章由标题词、正文词、主要类别和子类别表示。

迭代器不会将全部数据加载到内存中。相反,它按 mini-batch 将数据加载到内存中,以便可以使用大文件作为输入数据。

col_spliter#

一行中的列分隔符。

类型:

str

ID_spliter#

一行中的 ID 分隔符。

类型:

str

batch_size#

一个批次中的样本数量。

类型:

int

title_size#

新闻标题中的最大词数。

类型:

int

body_size#

新闻正文(在 MIND 中使用摘要)中的最大词数。

类型:

int

his_size#

用户点击历史中最大点击新闻数量。

类型:

int

npratio#

负样本与正样本的比例,用于负采样。-1 表示不需要负采样。

类型:

int

__init__(hparams, npratio=-1, col_spliter='\t', ID_spliter='%')[源代码]#

初始化迭代器。为模型创建必要的占位符。

参数:
  • hparams (object) – 全局超参数。包含一些关键设置,例如 head_num 和 head_dim。

  • graph (object) – 运行中的图。所有创建的占位符都将添加到此图中。

  • col_spliter (str) – 一行中的列分隔符。

  • ID_spliter (str) – 一行中的 ID 分隔符。

init_behaviors(behaviors_file)[源代码]#

根据 behaviors 文件初始化行为日志。

参数:

behaviors_file (str) – behaviors 文件路径

init_news(news_file)[源代码]#

根据 news 文件初始化新闻信息,例如 news_title_indexnews_abstract_index

参数:

news_file – news 文件路径

load_data_from_file(news_file, behavior_file)[源代码]#

从文件读取和解析数据。

参数:
  • news_file (str) – 包含新闻信息的文件。

  • beahaviros_file (str) – 包含用户曝光信息的文件。

生成:

object – 一个迭代器,以图 feed_dict 的格式生成解析结果。

load_dict(file_path)[源代码]#

加载 pickled 文件

参数:

path (file) – 文件路径

返回值:

pickle 加载对象

返回类型:

object

load_impression_from_file(behaivors_file)[源代码]#

从 behaivors 文件读取并解析曝光数据。

参数:

behaivors_file (str) – 包含行为信息的文件。

生成:

object – 一个迭代器,以 dict 格式生成解析后的曝光数据。

load_news_from_file(news_file)[源代码]#

从 news 文件读取并解析用户数据。

参数:

news_file (str) – 包含新闻信息的文件。

生成:

object – 一个迭代器,以 dict 格式生成解析后的新闻特征。

load_user_from_file(news_file, behavior_file)[源代码]#

从 news 文件和 behavior 文件读取并解析用户数据。

参数:
  • news_file (str) – 包含新闻信息的文件。

  • beahaviros_file (str) – 包含用户曝光信息的文件。

生成:

object – 一个迭代器,以 dict 格式生成解析后的用户特征。

parser_one_line(line)[源代码]#

将一个字符串行解析为特征值。

参数:

line (str) – 表示一个实例的字符串。

生成:

list – 解析结果,包括标签、曝光 ID、用户 ID、candidate_title_index、clicked_title_index、candidate_ab_index、clicked_ab_index、candidate_vert_index、clicked_vert_index、candidate_subvert_index、clicked_subvert_index、

实用工具#

class recommenders.models.newsrec.models.layers.AttLayer2(*args, **kwargs)[源代码]#

软对齐注意力实现。

dim#

注意力隐藏维度

类型:

int

__init__(dim=200, seed=0, **kwargs)[source]#

AttLayer2 的初始化步骤。

参数:

dim (int) – 注意力隐藏维度

build(input_shape)[source]#

AttLayer2 中变量的初始化。AttLayer2 中有三个变量:W、b 和 q。

参数:

input_shape (object) – 输入张量的形状。

call(inputs, mask=None, **kwargs)[source]#

软注意力机制的核心实现。

参数:

inputs (object) – 输入张量。

返回值:

输入张量的加权和。

返回类型:

object

compute_mask(input, input_mask=None)[source]#

计算输出掩码值。

参数:
  • input (object) – 输入张量。

  • input_mask – 输入掩码

返回值:

输出掩码。

返回类型:

object

compute_output_shape(input_shape)[source]#

计算输出张量的形状。

参数:

input_shape (tuple) – 输入张量的形状。

返回值:

输出张量的形状。

返回类型:

tuple

class recommenders.models.newsrec.models.layers.ComputeMasking(*args, **kwargs)[source]#

计算输入是否包含零值。

返回值:

对于不等于零的值为 True。

返回类型:

布尔张量

call(inputs, **kwargs)[source]#

ComputeMasking 的调用方法。

参数:

inputs (object) – 输入张量。

返回值:

对于不等于零的值为 True。

返回类型:

布尔张量

compute_output_shape(input_shape)[source]#

计算层的输出形状。

如果尚未发生,此方法将导致构建层的状态。这要求该层稍后与此处提供的输入形状相匹配的输入一起使用。

参数:

input_shape – 形状元组(整数元组)或 tf.TensorShape,或形状元组/tf.TensorShape 实例的结构(每层一个输出张量对应一个)。形状元组可以包含 None 表示自由维度,而不是整数。

返回值:

一个 tf.TensorShape 实例或 tf.TensorShape 实例的结构。

class recommenders.models.newsrec.models.layers.OverwriteMasking(*args, **kwargs)[source]#

将特定位置的值设置为零。

参数:

inputs (list) – 值张量和掩码张量。

返回值:

将值设为零后的张量。

返回类型:

object

build(input_shape)[source]#

创建层的变量(供子类实现者使用)。

这是 LayerModel 子类的实现者可以在层实例化和层调用之间需要状态创建步骤时重写的方法。它会在第一次执行 call() 之前自动调用。

这通常用于创建 Layer 子类的权重(由子类实现者决定)。

参数:

input_shapeTensorShape 的实例,或者如果层需要输入列表(每个输入一个实例),则为 TensorShape 实例的列表。

call(inputs, **kwargs)[source]#

OverwriteMasking 的调用方法。

参数:

inputs (list) – 值张量和掩码张量。

返回值:

将值设为零后的张量。

返回类型:

object

compute_output_shape(input_shape)[source]#

计算层的输出形状。

如果尚未发生,此方法将导致构建层的状态。这要求该层稍后与此处提供的输入形状相匹配的输入一起使用。

参数:

input_shape – 形状元组(整数元组)或 tf.TensorShape,或形状元组/tf.TensorShape 实例的结构(每层一个输出张量对应一个)。形状元组可以包含 None 表示自由维度,而不是整数。

返回值:

一个 tf.TensorShape 实例或 tf.TensorShape 实例的结构。

recommenders.models.newsrec.models.layers.PersonalizedAttentivePooling(dim1, dim2, dim3, seed=0)[source]#

软对齐注意力实现。

recommenders.models.newsrec.models.layers.dim1#

值形状的第一个维度。

类型:

int

recommenders.models.newsrec.models.layers.dim2#

值形状的第二个维度。

类型:

int

recommenders.models.newsrec.models.layers.dim3#

查询的形状

类型:

int

返回值:

输入值的加权汇总。

返回类型:

object

class recommenders.models.newsrec.models.layers.SelfAttention(*args, **kwargs)[source]#

多头自注意力实现。

参数:
  • multiheads (int) – 头部的数量。

  • head_dim (object) – 每个头部的维度。

  • mask_right (boolean) – 是否掩码右侧词。

返回值:

注意力后的加权和。

返回类型:

object

Mask(inputs, seq_len, mode='add')[source]#

多头自注意力中使用的掩码操作

参数:
  • seq_len (object) – 输入序列的长度。

  • mode (str) – 掩码模式。

返回值:

掩码后的张量。

返回类型:

object

__init__(multiheads, head_dim, seed=0, mask_right=False, **kwargs)[source]#

AttLayer2 的初始化步骤。

参数:
  • multiheads (int) – 头部的数量。

  • head_dim (object) – 每个头部的维度。

  • mask_right (boolean) – 是否掩码右侧词语。

build(input_shape)[source]#

SelfAttention 中变量的初始化。SelfAttention 中有三个变量:WQ、WK 和 WV。WQ 用于查询的线性变换。WK 用于键的线性变换。WV 用于值的线性变换。

参数:

input_shape (object) – 输入张量的形状。

call(QKVs)[source]#

多头自注意力的核心逻辑。

参数:

QKVs (list) – 多头自注意力的输入,即查询、键和值。

返回值:

输出张量。

返回类型:

object

compute_output_shape(input_shape)[source]#

计算输出张量的形状。

返回值:

输出形状元组。

返回类型:

tuple

get_config()[source]#

将 multiheads 和 mask_right 添加到层配置中。

返回值:

SelfAttention 层的配置。

返回类型:

dict

recommenders.models.newsrec.newsrec_utils.check_nn_config(f_config)[source]#

检查神经网络配置。

参数:

f_config (dict) – 神经网络配置。

抛出:

ValueError – 如果参数不正确。

recommenders.models.newsrec.newsrec_utils.check_type(config)[source]#

检查配置参数是否为正确的类型

参数:

config (dict) – 配置字典。

抛出:

TypeError – 如果参数类型不正确。

recommenders.models.newsrec.newsrec_utils.create_hparams(flags)[source]#

创建模型超参数。

参数:

flags (dict) – 包含模型要求的字典。

返回值:

超参数对象。

返回类型:

HParams

recommenders.models.newsrec.newsrec_utils.get_mind_data_set(type)[source]#

获取 MIND 数据集地址

参数:

type (str) – MIND 数据集类型,必须在 [‘large’, ‘small’, ‘demo’] 中

返回值:

数据 URL 和训练/验证数据集名称

返回类型:

list

recommenders.models.newsrec.newsrec_utils.newsample(news, ratio)[source]#

从新闻列表中抽取 ratio 个样本。如果新闻列表长度小于 ratio,则用零填充。

参数:
  • news (list) – 输入新闻列表

  • ratio (int) – 样本数量

返回值:

采样列表的输出。

返回类型:

list

recommenders.models.newsrec.newsrec_utils.prepare_hparams(yaml_file=None, **kwargs)[source]#

准备模型超参数并检查所有参数值是否正确。

参数:

yaml_file (str) – 作为配置的 YAML 文件。

返回值:

超参数对象。

返回类型:

HParams

recommenders.models.newsrec.newsrec_utils.word_tokenize(sent)[source]#

使用正则表达式将句子分割成单词列表。 :param sent: 输入句子 :type sent: str

返回值:

单词列表

返回类型:

list

LSTUR#

class recommenders.models.newsrec.models.lstur.LSTURModel(hparams, iterator_creator, seed=None)[source]#

LSTUR 模型(基于多头自注意力机制的神经新闻推荐)

Mingxiao An, Fangzhao Wu, Chuhan Wu, Kun Zhang, Zheng Liu and Xing Xie: Neural News Recommendation with Long- and Short-term User Representations, ACL 2019

word2vec_embedding#

预训练词嵌入矩阵。

类型:

numpy.ndarray

hparam#

全局超参数。

类型:

object

__init__(hparams, iterator_creator, seed=None)[source]#

LSTUR 的初始化步骤。与 BaseModel 相比,LSTUR 需要词嵌入。创建词嵌入矩阵后,将调用 BaseModel 的 __init__ 方法。

参数:
  • hparams (object) – 全局超参数。包含一些关键设置,例如 type 和 gru_unit。

  • iterator_creator_train (object) – 用于训练数据的 LSTUR 数据加载器类。

  • iterator_creator_test (object) – 用于测试和验证数据的 LSTUR 数据加载器类

NAML#

class recommenders.models.newsrec.models.naml.NAMLModel(hparams, iterator_creator, seed=None)[source]#

NAML 模型(基于注意力多视图学习的神经新闻推荐)

Chuhan Wu, Fangzhao Wu, Mingxiao An, Jianqiang Huang, Yongfeng Huang and Xing Xie, Neural News Recommendation with Attentive Multi-View Learning, IJCAI 2019

word2vec_embedding#

预训练词嵌入矩阵。

类型:

numpy.ndarray

hparam#

全局超参数。

类型:

object

__init__(hparams, iterator_creator, seed=None)[source]#

NAML 的初始化步骤。与 BaseModel 相比,NAML 需要词嵌入。创建词嵌入矩阵后,将调用 BaseModel 的 __init__ 方法。

参数:
  • hparams (object) – 全局超参数。包含一些关键设置,例如 filter_num。

  • iterator_creator_train (object) – 用于训练数据的 NAML 数据加载器类。

  • iterator_creator_test (object) – 用于测试和验证数据的 NAML 数据加载器类

NPA#

class recommenders.models.newsrec.models.npa.NPAModel(hparams, iterator_creator, seed=None)[source]#

NPA 模型(基于注意力多视图学习的神经新闻推荐)

Chuhan Wu, Fangzhao Wu, Mingxiao An, Jianqiang Huang, Yongfeng Huang and Xing Xie: NPA: Neural News Recommendation with Personalized Attention, KDD 2019, ADS track.

word2vec_embedding#

预训练词嵌入矩阵。

类型:

numpy.ndarray

hparam#

全局超参数。

类型:

object

__init__(hparams, iterator_creator, seed=None)[source]#

NPA 的初始化步骤。与 BaseModel 相比,NPA 需要词嵌入。创建词嵌入矩阵后,将调用 BaseModel 的 __init__ 方法。

参数:
  • hparams (object) – 全局超参数。包含一些关键设置,例如 filter_num。

  • iterator_creator_train (object) – 用于训练数据的 NPA 数据加载器类。

  • iterator_creator_test (object) – 用于测试和验证数据的 NPA 数据加载器类

NRMS#

class recommenders.models.newsrec.models.nrms.NRMSModel(hparams, iterator_creator, seed=None)[source]#

NRMS 模型(基于多头自注意力机制的神经新闻推荐)

Chuhan Wu, Fangzhao Wu, Suyu Ge, Tao Qi, Yongfeng Huang,and Xing Xie, “Neural News Recommendation with Multi-Head Self-Attention” in Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP)

word2vec_embedding#

预训练词嵌入矩阵。

类型:

numpy.ndarray

hparam#

全局超参数。

类型:

object

__init__(hparams, iterator_creator, seed=None)[source]#

NRMS 的初始化步骤。与 BaseModel 相比,NRMS 需要词嵌入。创建词嵌入矩阵后,将调用 BaseModel 的 __init__ 方法。

参数:
  • hparams (object) – 全局超参数。包含一些关键设置,例如 head_num 和 head_dim。

  • iterator_creator_train (object) – 用于训练数据的 NRMS 数据加载器类。

  • iterator_creator_test (object) – 用于测试和验证数据的 NRMS 数据加载器类

RBM#

class recommenders.models.rbm.rbm.RBM(possible_ratings, visible_units, hidden_units=500, keep_prob=0.7, init_stdv=0.1, learning_rate=0.004, minibatch_size=100, training_epoch=20, display_epoch=10, sampling_protocol=[50, 70, 80, 90, 100], debug=False, with_metrics=False, seed=42)[source]#

受限玻尔兹曼机

__init__(possible_ratings, visible_units, hidden_units=500, keep_prob=0.7, init_stdv=0.1, learning_rate=0.004, minibatch_size=100, training_epoch=20, display_epoch=10, sampling_protocol=[50, 70, 80, 90, 100], debug=False, with_metrics=False, seed=42)[source]#

使用 numpy/pandas/tensorflow 实现用于协同过滤的多项式受限玻尔兹曼机

基于 Ruslan Salakhutdinov, Andriy Mnih 和 Geoffrey Hinton 的文章 https://www.cs.toronto.edu/~rsalakhu/papers/rbmcf.pdf

在此实现中,我们使用多项式单元代替论文中使用的独热编码。这意味着权重是秩为 2 的(矩阵)而不是秩为 3 的张量。

基本机制

1) RBM 类实例化时会创建一个计算图。对于基于物品的推荐器,它包含:可见单元:可见单元的数量 n_visible 等于物品的数量,隐藏单元:训练期间固定的超参数

  1. 吉布斯采样

2.1) 对于每个训练 epoch,首先将可见单元固定在数据上

2.2) 根据可见单元的线性组合,评估隐藏单元的激活概率 P(h=1|phi_v)。然后使用该概率采样隐藏单元的值。

2.3) 评估概率 P(v=l|phi_h),其中 l=1,..,r 是评分(例如,对于 movielens 数据集,r=5)。通常,这是一种多项式分布,我们从中采样 v 的值。

2.4) 此步骤重复 k 次,其中 k 随着优化收敛而增加。在整个学习过程中,必须将原始未评分项设为零。

3) 优化:在开始时 (F_0) 和 k 步伯努利采样后 (F_k) 评估给定隐藏单元的可见单元的自由能。通过最小化差异 F_0 - F_k 来更新权重和偏差。

4) 推断:学习到联合概率分布 P(v,h) 后,即可用于为所有用户生成未评分物品的评分。

batch_training(num_minibatches)[source]#

对输入小批量进行训练。如果 self.with_metrics 为 False,则不评估在线指标。

参数:

num_minibatches (scalar, int32) – 训练小批量的数量。

返回值:

每个 epoch 的训练误差。如果 self.with_metrics 为 False,则为零。

返回类型:

float

binomial_sampling(pr)[source]#

使用拒绝抽样方法对隐藏单元激活进行二项式采样。

基本机制

1) 从均匀分布 (g) 中提取一个随机数,并将其与单元的概率 (pr) 进行比较

2) 如果 pr

参数:
  • pr (tf.Tensor, float32) – 输入条件概率。

  • g (numpy.ndarray, float32) – 用于比较的均匀概率。

返回值:

采样的单元的 Float32 张量。如果 pr>g,则值为 1,否则为 0。

返回类型:

tf.Tensor

data_pipeline()[source]#

定义数据管道

eval_out()[source]#

从训练好的模型实现多项式采样

fit(xtr)[source]#

Fit 方法

生成模型中的训练分为两个步骤

  1. 吉布斯采样

  2. 梯度评估和参数更新

该估计值稍后用于通过最小化模型与经验自由能之间的距离来更新权重。请注意,虽然采样了单元的配置空间,但权重是通过最大似然法(鞍点)确定的。

算法的主要组成部分;一旦实例化,它将生成计算图并执行模型训练

参数:
  • xtr (numpy.ndarray, integers) – 训练集的 用户/关联矩阵

  • xtst (numpy.ndarray, integers) – 测试集的 用户/关联矩阵

free_energy(x)[source]#

给定隐藏单元时可见单元的自由能。由于求和是针对隐藏单元的状态进行的,可见单元自由能的函数形式与二元模型的函数形式相同。

参数:

x (tf.Tensor) – 这可以是可见单元的采样值 (v_k) 或输入数据

返回值:

模型的自由能。

返回类型:

tf.Tensor

generate_graph()[source]#

调用不同的 RBM 模块以生成计算图

gibbs_protocol(i)[source]#

吉布斯协议。

基本机制

如果当前 epoch i 在训练协议指定的区间内,吉布斯采样的步数 (k) 将加一,并且相应更新 gibbs_sampling。

参数:

i (int) – 循环中的当前 epoch

gibbs_sampling()[source]#

吉布斯采样:通过采样确定模型配置的估计值。在二元 RBM 中,我们需要强制未见过的电影保持原样,即采样阶段不应修改 v=0 的元素。

参数:
  • k (scalar, integer) – 迭代器。采样步数。

  • v (tf.Tensor, float32) – 可见单元。

返回值:

  • h_k: 步骤 k 中隐藏单元的采样值,float32。

  • v_k: 步骤 k 中可见单元的采样值,float32。

返回类型:

tf.Tensor, tf.Tensor

init_gpu()[source]#

配置 GPU 内存

init_metrics()[source]#

初始化指标

init_parameters()[source]#

初始化模型的参数。

这是一个带有两个偏置项的单层模型。因此,我们需要初始化一个矩形矩阵 w_{ij} 和两个偏置向量。

参数:
  • n_visible (int) – 可见单元数量(输入层)

  • n_hidden (int) – 隐藏单元数量(模型的潜在变量)

返回值:

  • w of size (n_visible, n_hidden): 大小为 (n_visible, n_hidden) 的关联矩阵:通过从均值为零、方差为 init_stdv 的正态分布中采样初始化。

  • bv of size (1, n_visible): 可见单元偏置项,初始化为零。

  • bh of size (1, n_hidden): 隐藏单元偏置项,初始化为零。

返回类型:

tf.Tensor, tf.Tensor, tf.Tensor

init_training_session(xtr)[source]#

在训练数据上初始化 TF session

参数:

xtr (numpy.ndarray, int32) – 训练集的 用户/关联矩阵。

load(file_path='.%2Frbm_model.ckpt')[source]#

加载模型参数以供进一步使用。

此函数加载已保存的 tensorflow session。

参数:

file_path (str) – RBM 模型检查点的文件路径

losses(vv)[source]#

计算对比散度,它是固定在数据 (v) 上的自由能与模型自由能 (v_k) 之间的差异。

参数:

vv (tf.Tensor, float32) – 经验输入

返回值:

对比散度

返回类型:

obj

multinomial_distribution(phi)[source]#

给定 phi 时单元 v 取值 l 的概率:P(v=l|phi)

参数:
  • phi (tf.Tensor) – 前一层值的线性组合

  • r (float) – 评分量度,对应于类别数

返回值:

  • 一个形状为 (r, m, Nv) 的张量:最后一步需要将其重塑为 (m, Nv, r),以便在多项式函数中使用时加快采样速度。

返回类型:

tf.Tensor

multinomial_sampling(pr)[source]#

评分的多项式采样

基本机制:对于 r 个类别,我们使用拒绝抽样方法采样 r 个二项分布。这是可能的,因为每个类别在统计上都是相互独立的。请注意,这与 numpy 的 random.multinomial() 函数中使用的方法相同。

1) 从均匀分布 (g) 中提取大小为 r 的随机数数组。由于 pr 已归一化,我们也需要对 g 进行归一化。

2) 对于每个用户和物品,将 pr 与参考分布进行比较。请注意,根据假设,参考分布对于数据集中所有用户/物品对都必须相同,因为它们是从共同分布中采样的。

参数:
  • pr (tf.Tensor, float32) – 形状为 (m, n, r) 的分布,其中 m 是样本数,n 是特征数,r 是类别数。pr 需要归一化,即对于固定的 n,所有 m 都有 sum_k p(k) = 1。

  • f (tf.Tensor, float32) – 用于比较的归一化均匀概率。

返回值:

一个 (m,n) 的 float32 张量,包含从 1 到 r 的采样排名。

返回类型:

tf.Tensor

placeholder()[source]#

初始化可见单元的占位符

predict(x)[source]#

返回推断的评分。此方法类似于 recommend_k_items(),不同之处在于它返回所有推断的评分

基本机制

该方法从学习到的联合分布中采样新的评分及其概率。输入 x 必须与用于训练模型的矩阵具有相同的列数,即物品数量相同,但可以具有任意数量的行(用户)。

参数:
  • x (numpy.ndarray, int32) – 输入 用户/关联矩阵。注意,这可以是一个单向量,即

  • user. (the ratings of a single)

返回值:

  • 包含推断评分的矩阵。

  • 预测的耗时。

返回类型:

numpy.ndarray, float

recommend_k_items(x, top_k=10, remove_seen=True)[source]#

返回按相关性分数排序的 top-k 物品。

基本机制

该方法从学习到的联合分布中采样新的评分及其概率。输入 x 必须与用于训练模型的矩阵具有相同的列数(即物品数量相同),但可以具有任意数量的行(用户)。

通过计算评分与相关概率之间的元素乘积来评估推荐分数。例如,我们可能有以下情况

        rating     probability     score
item1     5           0.5          2.5
item2     4           0.8          3.2

然后将推荐 item2。

参数:
  • x (numpy.ndarray, int32) – 输入 用户/关联矩阵。注意,这可以是一个单向量,即评分

  • user. (of a single)

  • top_k (scalar, int32) – 推荐的物品数量。

返回值:

  • 一个包含按分数排序的 top_k 元素的稀疏矩阵。

  • 推荐 k 个物品所需的时间。

返回类型:

numpy.ndarray, float

sample_hidden_units(vv)[source]#

采样:在 RBM 中,我们使用对比散度对参数空间进行采样。为此,我们需要初始化两个条件概率

P(h|phi_v) –> returns the probability that the i-th hidden unit is active

P(v|phi_h) –> returns the probability that the i-th visible unit is active

给定可见单元采样隐藏单元。这可以看作是 FFN 中的前向传播步骤

参数:

vv (tf.Tensor, float32) – 可见单元

返回值:

  • phv: 隐藏单元的激活概率。

  • h_: 从成功概率为 phv 的伯努利分布中采样的隐藏单元值。

返回类型:

tf.Tensor, tf.Tensor

sample_visible_units(h)[source]#

给定隐藏单元采样可见单元。这可以看作是 FFN 中的反向传播(负相)步骤。每个可见单元可以取值 [1, rating],而零保留给缺失数据;因此,隐藏单元的值是从多项式分布中采样的。

基本机制

1) For every training example we first sample Nv Multinomial distributions. The result is of the form [0,1,0,0,0,…,0] where the index of the 1 element corresponds to the rth rating. The index is extracted using the argmax function and we need to add 1 at the end since array indeces starts from 0.

2) Selects only those units that have been sampled. During the training phase it is important to not use the reconstructed inputs, so we beed to enforce a zero value in the reconstructed ratings in the same position as the original input.

参数:

h (tf.Tensor, float32) – visible units.

返回值:

  • pvh: The activation probability of the visible unit given the hidden.

  • v_: The sampled value of the visible unit from a Multinomial distributions having success probability pvh.

返回类型:

tf.Tensor, tf.Tensor

save(file_path='./rbm_model.ckpt')[source]#

Save model parameters to file_path

This function saves the current tensorflow session to a specified path.

参数:

file_path (str) – output file path for the RBM model checkpoint we will create a new directory if not existing.

SAR#

class recommenders.models.sar.sar_singlenode.SARSingleNode(col_user='userID', col_item='itemID', col_rating='rating', col_timestamp='timestamp', col_prediction='prediction', similarity_type='jaccard', time_decay_coefficient=30, time_now=None, timedecay_formula=False, threshold=1, normalize=False)[source]#

Simple Algorithm for Recommendations (SAR) implementation

SAR is a fast scalable adaptive algorithm for personalized recommendations based on user transaction history and items description. The core idea behind SAR is to recommend items like those that a user already has demonstrated an affinity to. It does this by 1) estimating the affinity of users for items, 2) estimating similarity across items, and then 3) combining the estimates to generate a set of recommendations for a given user.

__init__(col_user='userID', col_item='itemID', col_rating='rating', col_timestamp='timestamp', col_prediction='prediction', similarity_type='jaccard', time_decay_coefficient=30, time_now=None, timedecay_formula=False, threshold=1, normalize=False)[source]#

Initialize model parameters

参数:
  • col_user (str) – user column name

  • col_item (str) – item column name

  • col_rating (str) – rating column name

  • col_timestamp (str) – timestamp column name

  • col_prediction (str) – prediction column name

  • similarity_type (str) – [‘cooccurrence’, ‘cosine’, ‘inclusion index’, ‘jaccard’, ‘lexicographers mutual information’, ‘lift’, ‘mutual information’] option for computing item-item similarity

  • time_decay_coefficient (float) – number of days till ratings are decayed by 1/2

  • time_now (int | None) – current time for time decay calculation

  • timedecay_formula (bool) – flag to apply time decay

  • threshold (int) – item-item co-occurrences below this threshold will be removed

  • normalize (bool) – option for normalizing predictions to scale of original ratings

compute_affinity_matrix(df, rating_col)[source]#

Affinity matrix.

The user-affinity matrix can be constructed by treating the users and items as indices in a sparse matrix, and the events as the data. Here, we’re treating the ratings as the event weights. We convert between different sparse-matrix formats to de-duplicate user-item pairs, otherwise they will get added up.

参数:
  • df (pandas.DataFrame) – Indexed df of users and items

  • rating_col (str) – Name of column to use for ratings

返回值:

Affinity matrix in Compressed Sparse Row (CSR) format.

返回类型:

sparse.csr

compute_cooccurrence_matrix(df)[source]#

Co-occurrence matrix.

The co-occurrence matrix is defined as \(C = U^T * U\)

where U is the user_affinity matrix with 1’s as values (instead of ratings).

参数:

df (pandas.DataFrame) – DataFrame of users and items

返回值:

Co-occurrence matrix

返回类型:

numpy.ndarray

compute_time_decay(df, decay_column)[source]#

Compute time decay on provided column.

参数:
  • df (pandas.DataFrame) – DataFrame of users and items

  • decay_column (str) – column to decay

返回值:

with column decayed

返回类型:

pandas.DataFrame

fit(df)[source]#

Main fit method for SAR.

注意

Please make sure that df has no duplicates.

参数:

df (pandas.DataFrame) – User item rating dataframe (without duplicates).

get_item_based_topk(items, top_k=10, sort_top_k=True)[source]#

Get top K similar items to provided seed items based on similarity metric defined. This method will take a set of items and use them to recommend the most similar items to that set based on the similarity matrix fit during training. This allows recommendations for cold-users (unseen during training), note - the model is not updated.

The following options are possible based on information provided in the items input: 1. Single user or seed of items: only item column (ratings are assumed to be 1) 2. Single user or seed of items w/ ratings: item column and rating column 3. Separate users or seeds of items: item and user column (user ids are only used to separate item sets) 4. Separate users or seeds of items with ratings: item, user and rating columns provided

参数:
  • items (pandas.DataFrame) – DataFrame with item, user (optional), and rating (optional) columns

  • top_k (int) – number of top items to recommend

  • sort_top_k (bool) – flag to sort top k results

返回值:

sorted top k recommendation items

返回类型:

pandas.DataFrame

get_popularity_based_topk(top_k=10, sort_top_k=True, items=True)[source]#

Get top K most frequently occurring items across all users.

参数:
  • top_k (int) – number of top items to recommend.

  • sort_top_k (bool) – flag to sort top k results.

  • items (bool) – if false, return most frequent users instead

返回值:

top k most popular items.

返回类型:

pandas.DataFrame

get_topk_most_similar_users(user, top_k, sort_top_k=True)[source]#

Based on user affinity towards items, calculate the most similar users to the given user.

参数:
  • user (int) – user to retrieve most similar users for

  • top_k (int) – number of top items to recommend

  • sort_top_k (bool) – flag to sort top k results

返回值:

top k most similar users and their scores

返回类型:

pandas.DataFrame

predict(test)[source]#

Output SAR scores for only the users-items pairs which are in the test set

参数:

test (pandas.DataFrame) – DataFrame that contains users and items to test

返回值:

DataFrame contains the prediction results

返回类型:

pandas.DataFrame

recommend_k_items(test, top_k=10, sort_top_k=True, remove_seen=False)[source]#

Recommend top K items for all users which are in the test set

参数:
  • test (pandas.DataFrame) – users to test

  • top_k (int) – number of top items to recommend

  • sort_top_k (bool) – flag to sort top k results

  • remove_seen (bool) – flag to remove items seen in training from recommendation

返回值:

top k recommendation items for each user

返回类型:

pandas.DataFrame

score(test, remove_seen=False)[source]#

为测试用户的所有物品评分。

参数:
  • test (pandas.DataFrame) – user to test

  • remove_seen (bool) – flag to remove items seen in training from recommendation

返回值:

用户对所有物品的兴趣值。

返回类型:

numpy.ndarray

set_index(df)[source]#

Generate continuous indices for users and items to reduce memory usage.

参数:

df (pandas.DataFrame) – dataframe with user and item ids

SASRec#

class recommenders.models.sasrec.model.Encoder(*args, **kwargs)[source]#

Invokes Transformer based encoder with user defined number of layers

__init__(num_layers, seq_max_len, embedding_dim, attention_dim, num_heads, conv_dims, dropout_rate)[source]#

Initialize parameters.

参数:
  • num_layers (int) – Number of layers.

  • seq_max_len (int) – Maximum sequence length.

  • embedding_dim (int) – Embedding dimension.

  • attention_dim (int) – Dimension of the attention embeddings.

  • num_heads (int) – Number of heads in the multi-head self-attention module.

  • conv_dims (list) – List of the dimensions of the Feedforward layer.

  • dropout_rate (float) – Dropout probability.

call(x, training, mask)[source]#

Model forward pass.

参数:
  • x (tf.Tensor) – Input tensor.

  • training (Boolean) – True if in training mode.

  • mask (tf.Tensor) – Mask tensor.

返回值:

Output tensor.

返回类型:

tf.Tensor

class recommenders.models.sasrec.model.EncoderLayer(*args, **kwargs)[source]#

Transformer based encoder layer

__init__(seq_max_len, embedding_dim, attention_dim, num_heads, conv_dims, dropout_rate)[source]#

Initialize parameters.

参数:
  • seq_max_len (int) – Maximum sequence length.

  • embedding_dim (int) – Embedding dimension.

  • attention_dim (int) – Dimension of the attention embeddings.

  • num_heads (int) – Number of heads in the multi-head self-attention module.

  • conv_dims (list) – List of the dimensions of the Feedforward layer.

  • dropout_rate (float) – Dropout probability.

call(x, training, mask)[source]#

Model forward pass.

参数:
  • x (tf.Tensor) – Input tensor.

  • training (Boolean) – True if in training mode.

  • mask (tf.Tensor) – Mask tensor.

返回值:

Output tensor.

返回类型:

tf.Tensor

call_(x, training, mask)[source]#

Model forward pass.

参数:
  • x (tf.Tensor) – Input tensor.

  • training (tf.Tensor) – Training tensor.

  • mask (tf.Tensor) – Mask tensor.

返回值:

Output tensor.

返回类型:

tf.Tensor

class recommenders.models.sasrec.model.LayerNormalization(*args, **kwargs)[source]#

Layer normalization using mean and variance gamma and beta are the learnable parameters

__init__(seq_max_len, embedding_dim, epsilon)[source]#

Initialize parameters.

参数:
  • seq_max_len (int) – Maximum sequence length.

  • embedding_dim (int) – Embedding dimension.

  • epsilon (float) – Epsilon value.

call(x)[source]#

Model forward pass.

参数:

x (tf.Tensor) – Input tensor.

返回值:

Output tensor.

返回类型:

tf.Tensor

class recommenders.models.sasrec.model.MultiHeadAttention(*args, **kwargs)[source]#
  • Q (query), K (key) and V (value) are split into multiple heads (num_heads)

  • each tuple (q, k, v) are fed to scaled_dot_product_attention

  • all attention outputs are concatenated

__init__(attention_dim, num_heads, dropout_rate)[source]#

Initialize parameters.

参数:
  • attention_dim (int) – Dimension of the attention embeddings.

  • num_heads (int) – Number of heads in the multi-head self-attention module.

  • dropout_rate (float) – Dropout probability.

call(queries, keys)[source]#

Model forward pass.

参数:
  • queries (tf.Tensor) – Tensor of queries.

  • keys (tf.Tensor) – Tensor of keys

返回值:

Output tensor.

返回类型:

tf.Tensor

class recommenders.models.sasrec.model.PointWiseFeedForward(*args, **kwargs)[source]#

Convolution layers with residual connection

__init__(conv_dims, dropout_rate)[source]#

Initialize parameters.

参数:
  • conv_dims (list) – List of the dimensions of the Feedforward layer.

  • dropout_rate (float) – Dropout probability.

call(x)[source]#

Model forward pass.

参数:

x (tf.Tensor) – Input tensor.

返回值:

Output tensor.

返回类型:

tf.Tensor

class recommenders.models.sasrec.model.SASREC(*args, **kwargs)[source]#

SAS Rec model Self-Attentive Sequential Recommendation Using Transformer

引用:

Wang-Cheng Kang, Julian McAuley (2018), Self-Attentive Sequential Recommendation. Proceedings of IEEE International Conference on Data Mining (ICDM’18)

Original source code from nnkkmto/SASRec-tf2, nnkkmto/SASRec-tf2

__init__(**kwargs)[source]#

Model initialization.

参数:
  • item_num (int) – Number of items in the dataset.

  • seq_max_len (int) – Maximum number of items in user history.

  • num_blocks (int) – Number of Transformer blocks to be used.

  • embedding_dim (int) – Item embedding dimension.

  • attention_dim (int) – Transformer attention dimension.

  • conv_dims (list) – List of the dimensions of the Feedforward layer.

  • dropout_rate (float) – Dropout rate.

  • l2_reg (float) – Coefficient of the L2 regularization.

  • num_neg_test (int) – Number of negative examples used in testing.

call(x, training)[source]#

Model forward pass.

参数:
  • x (tf.Tensor) – Input tensor.

  • training (tf.Tensor) – Training tensor.

返回值:

  • Logits of the positive examples.

  • Logits of the negative examples.

  • Mask for nonzero targets

返回类型:

tf.Tensor, tf.Tensor, tf.Tensor

create_combined_dataset(u, seq, pos, neg)[source]#

function to create model inputs from sampled batch data. This function is used only during training.

embedding(input_seq)[source]#

Compute the sequence and positional embeddings.

参数:

input_seq (tf.Tensor) – Input sequence

返回值:

  • Sequence embeddings.

  • Positional embeddings.

返回类型:

tf.Tensor, tf.Tensor

evaluate(dataset)[source]#

Evaluation on the test users (users with at least 3 items)

evaluate_valid(dataset)[source]#

Evaluation on the validation users

loss_function(pos_logits, neg_logits, istarget)[source]#

Losses are calculated separately for the positive and negative items based on the corresponding logits. A mask is included to take care of the zero items (added for padding).

参数:
  • pos_logits (tf.Tensor) – Logits of the positive examples.

  • neg_logits (tf.Tensor) – Logits of the negative examples.

  • istarget (tf.Tensor) – Mask for nonzero targets.

返回值:

Loss.

返回类型:

float

predict(inputs)[source]#

Returns the logits for the test items.

参数:

inputs (tf.Tensor) – Input tensor.

返回值:

Output tensor.

返回类型:

tf.Tensor

train(dataset, sampler, **kwargs)[source]#

High level function for model training as well as evaluation on the validation and test dataset

class recommenders.models.sasrec.sampler.WarpSampler(User, usernum, itemnum, batch_size=64, maxlen=10, n_workers=1)[source]#

Sampler object that creates an iterator for feeding batch data while training.

User#

dict, all the users (keys) with items as values

usernum#

integer, total number of users

itemnum#

integer, total number of items

batch_size#

batch size

类型:

int

maxlen#

maximum input sequence length

类型:

int

n_workers#

number of workers for parallel execution

类型:

int

__init__(User, usernum, itemnum, batch_size=64, maxlen=10, n_workers=1)[source]#
recommenders.models.sasrec.sampler.sample_function(user_train, usernum, itemnum, batch_size, maxlen, result_queue, seed)[source]#

Batch sampler that creates a sequence of negative items based on the original sequence of items (positive) that the user has interacted with.

参数:
  • user_train (dict) – dictionary of training exampled for each user

  • usernum (int) – number of users

  • itemnum (int) – number of items

  • batch_size (int) – batch size

  • maxlen (int) – maximum input sequence length

  • result_queue (multiprocessing.Queue) – queue for storing sample results

  • seed (int) – seed for random generator

class recommenders.models.sasrec.util.SASRecDataSet(**kwargs)[source]#

A class for creating SASRec specific dataset used during train, validation and testing.

usernum#

integer, total number of users

itemnum#

integer, total number of items

User#

dict, all the users (keys) with items as values

Items#

set of all the items

user_train#

dict, subset of User that are used for training

user_valid#

dict, subset of User that are used for validation

user_test#

dict, subset of User that are used for testing

col_sep#

column separator in the data file

filename#

data filename

SSE-PT#

class recommenders.models.sasrec.ssept.SSEPT(*args, **kwargs)[source]#

SSE-PT Model

引用:

Wu L., Li S., Hsieh C-J., Sharpnack J., SSE-PT: Sequential Recommendation Via Personalized Transformer, RecSys, 2020. TF 1.x codebase: SSE-PT/SSE-PT TF 2.x codebase (SASREc): nnkkmto/SASRec-tf2

__init__(**kwargs)[source]#

Model initialization.

参数:
  • item_num (int) – Number of items in the dataset.

  • seq_max_len (int) – Maximum number of items in user history.

  • num_blocks (int) – Number of Transformer blocks to be used.

  • embedding_dim (int) – Item embedding dimension.

  • attention_dim (int) – Transformer attention dimension.

  • conv_dims (list) – List of the dimensions of the Feedforward layer.

  • dropout_rate (float) – Dropout rate.

  • l2_reg (float) – Coefficient of the L2 regularization.

  • num_neg_test (int) – Number of negative examples used in testing.

  • user_num (int) – Number of users in the dataset.

  • user_embedding_dim (int) – User embedding dimension.

  • item_embedding_dim (int) – Item embedding dimension.

call(x, training)[source]#

Model forward pass.

参数:
  • x (tf.Tensor) – Input tensor.

  • training (tf.Tensor) – Training tensor.

返回值:

  • Logits of the positive examples.

  • Logits of the negative examples.

  • Mask for nonzero targets

返回类型:

tf.Tensor, tf.Tensor, tf.Tensor

loss_function(pos_logits, neg_logits, istarget)[source]#

Losses are calculated separately for the positive and negative items based on the corresponding logits. A mask is included to take care of the zero items (added for padding).

参数:
  • pos_logits (tf.Tensor) – Logits of the positive examples.

  • neg_logits (tf.Tensor) – Logits of the negative examples.

  • istarget (tf.Tensor) – Mask for nonzero targets.

返回值:

Loss.

返回类型:

float

predict(inputs)[source]#

Model prediction for candidate (negative) items

Surprise utilities#

recommenders.models.surprise.surprise_utils.compute_ranking_predictions(algo, data, usercol='userID', itemcol='itemID', predcol='prediction', remove_seen=False)[source]#

Computes predictions of an algorithm from Surprise on all users and items in data. It can be used for computing ranking metrics like NDCG.

参数:
  • algo (surprise.prediction_algorithms.algo_base.AlgoBase) – an algorithm from Surprise

  • data (pandas.DataFrame) – the data from which to get the users and items

  • usercol (str) – name of the user column

  • itemcol (str) – name of the item column

  • remove_seen (bool) – flag to remove (user, item) pairs seen in the training data

返回值:

包含 usercol、itemcol、predcol 列的数据框

返回类型:

pandas.DataFrame

recommenders.models.surprise.surprise_utils.predict(algo, data, usercol='userID', itemcol='itemID', predcol='prediction')[source]#

Computes predictions of an algorithm from Surprise on the data. Can be used for computing rating metrics like RMSE.

参数:
  • algo (surprise.prediction_algorithms.algo_base.AlgoBase) – an algorithm from Surprise

  • data (pandas.DataFrame) – the data on which to predict

  • usercol (str) – name of the user column

  • itemcol (str) – name of the item column

返回值:

包含 usercol、itemcol、predcol 列的数据框

返回类型:

pandas.DataFrame

recommenders.models.surprise.surprise_utils.surprise_trainset_to_df(trainset, col_user='uid', col_item='iid', col_rating='rating')[source]#

Converts a surprise.Trainset object to pandas.DataFrame

More info: https://docs.surpriselib.cn/en/stable/trainset.html

参数:
  • trainset (object) – A surprise.Trainset object.

  • col_user (str) – 用户列名。

  • col_item (str) – 物品列名。

  • col_rating (str) – 评分列名。

返回值:

A dataframe with user column (str), item column (str), and rating column (float).

返回类型:

pandas.DataFrame

TF-IDF utilities#

class recommenders.models.tfidf.tfidf_utils.TfidfRecommender(id_col, tokenization_method='scibert')[source]#

Term Frequency - Inverse Document Frequency (TF-IDF) Recommender

This class provides content-based recommendations using TF-IDF vectorization in combination with cosine similarity.

clean_dataframe(df, cols_to_clean, new_col_name='cleaned_text')[source]#

Clean the text within the columns of interest and return a dataframe with cleaned and combined text.

参数:
  • df (pandas.DataFrame) – Dataframe containing the text content to clean.

  • cols_to_clean (list of str) – List of columns to clean by name (e.g., [‘abstract’,’full_text’]).

  • new_col_name (str) – Name of the new column that will contain the cleaned text.

返回值:

Dataframe with cleaned text in the new column.

返回类型:

pandas.DataFrame

fit(tf, vectors_tokenized)[source]#

Fit TF-IDF vectorizer to the cleaned and tokenized text.

参数:
  • tf (TfidfVectorizer) – sklearn.feature_extraction.text.TfidfVectorizer object defined in .tokenize_text().

  • vectors_tokenized (pandas.Series) – Each row contains tokens for respective documents separated by spaces.

get_stop_words()[source]#

Return the stop words excluded in the TF-IDF vectorizer.

返回值:

Frozenset of stop words used by the TF-IDF vectorizer (can be converted to list).

返回类型:

list

get_tokens()[source]#

Return the tokens generated by the TF-IDF vectorizer.

返回值:

Dictionary of tokens generated by the TF-IDF vectorizer.

返回类型:

dict

get_top_k_recommendations(metadata, query_id, cols_to_keep=[], verbose=True)[source]#

Return the top k recommendations with useful metadata for each recommendation.

参数:
  • metadata (pandas.DataFrame) – Dataframe holding metadata for all public domain papers.

  • query_id (str) – ID of item of interest.

  • cols_to_keep (list of str) – List of columns from the metadata dataframe to include (e.g., [‘title’,’authors’,’journal’,’publish_time’,’url’]). By default, all columns are kept.

  • verbose (boolean) – Set to True if you want to print the table.

返回值:

Stylized dataframe holding recommendations and associated metadata just for the item of interest (can access as normal dataframe by using df.data).

返回类型:

pandas.Styler

recommend_top_k_items(df_clean, k=5)[source]#

Recommend k number of items similar to the item of interest.

参数:
  • df_clean (pandas.DataFrame) – Dataframe with cleaned text.

  • k (int) – Number of recommendations to return.

返回值:

Dataframe containing id of top k recommendations for all items.

返回类型:

pandas.DataFrame

tokenize_text(df_clean, text_col='cleaned_text', ngram_range=(1, 3), min_df=0.0)[source]#

Tokenize the input text. For more details on the TfidfVectorizer, see https://scikit-learn.cn/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html

参数:
  • df_clean (pandas.DataFrame) – Dataframe with cleaned text in the new column.

  • text_col (str) – Name of column containing the cleaned text.

  • ngram_range (tuple of int) – The lower and upper boundary of the range of n-values for different n-grams to be extracted.

  • min_df (float) – When building the vocabulary ignore terms that have a document frequency strictly lower than the given threshold.

返回值:

  • Scikit-learn TfidfVectorizer object defined in .tokenize_text().

  • Each row contains tokens for respective documents separated by spaces.

返回类型:

TfidfVectorizer, pandas.Series

Standard VAE#

class recommenders.models.vae.standard_vae.AnnealingCallback(beta, anneal_cap, total_anneal_steps)[source]#

This class is used for updating the value of β during the annealing process. When β reaches the value of anneal_cap, it stops increasing.

__init__(beta, anneal_cap, total_anneal_steps)[source]#

构造函数

参数:
  • beta (float) – current value of beta.

  • anneal_cap (float) – maximum value that beta can reach.

  • total_anneal_steps (int) – total number of annealing steps.

get_data()[source]#

Returns a list of the beta values per epoch.

on_batch_end(epoch, logs={})[source]#

At the end of each batch the beta should is updated until it reaches the values of anneal cap.

on_epoch_end(epoch, logs={})[source]#

At the end of each epoch save the value of beta in _beta list.

on_train_begin(logs={})[source]#

Initialise a list in which the beta value will be saved at the end of each epoch.

class recommenders.models.vae.standard_vae.LossHistory[source]#

This class is used for saving the validation loss and the training loss per epoch.

on_epoch_end(epoch, logs={})[source]#

Save the loss of training and validation set at the end of each epoch.

on_train_begin(logs={})[source]#

Initialise the lists where the loss of training and validation will be saved.

class recommenders.models.vae.standard_vae.Metrics(model, val_tr, val_te, mapper, k, save_path=None)[source]#

Callback function used to calculate the NDCG@k metric of validation set at the end of each epoch. Weights of the model with the highest NDCG@k value is saved.

__init__(model, val_tr, val_te, mapper, k, save_path=None)[source]#

初始化类参数。

参数:
  • model – 用于验证的已训练模型。

  • val_tr (numpy.ndarray, float) – 验证集训练部分的点击矩阵。

  • val_te (numpy.ndarray, float) – 验证集测试部分的点击矩阵。

  • mapper (AffinityMatrix) – 用于将点击矩阵转换为 DataFrame 的映射器。

  • k (int) – 每个用户的顶部 k 个项目数(可选)。

  • save_path (str) – 保存权重的默认路径。

get_data()[source]#

返回在每个 Epoch 结束时计算的验证集指标的 NDCG@k 列表。

on_epoch_end(batch, logs={})[source]#

在每个 Epoch 结束时计算验证集的 NDCG@k。如果模型性能得到改善,则保存模型权重。通过添加获取的值来更新验证 NDCG@k 列表。

on_train_begin(logs={})[source]#

初始化验证 NDCG@k 的列表。

recommend_k_items(x, k, remove_seen=True)[source]#

返回按相关性得分排序的顶部 k 个项目。获得的概率用作推荐得分。

参数:
  • x (numpy.ndarray, int32) – 输入点击矩阵。

  • k (scalar, int32) – 要推荐的项目数量。

返回值:

一个包含按分数排序的 top_k 元素的稀疏矩阵。

返回类型:

numpy.ndarray

class recommenders.models.vae.standard_vae.StandardVAE(n_users, original_dim, intermediate_dim=200, latent_dim=70, n_epochs=400, batch_size=100, k=100, verbose=1, drop_encoder=0.5, drop_decoder=0.5, beta=1.0, annealing=False, anneal_cap=1.0, seed=None, save_path=None)[source]#

用于协同过滤的标准变分自动编码器 (VAE) 实现。

__init__(n_users, original_dim, intermediate_dim=200, latent_dim=70, n_epochs=400, batch_size=100, k=100, verbose=1, drop_encoder=0.5, drop_decoder=0.5, beta=1.0, annealing=False, anneal_cap=1.0, seed=None, save_path=None)[source]#

初始化类参数。

参数:
  • n_users (int) – 训练集中的唯一用户数量。

  • original_dim (int) – 训练集中的唯一项目数量。

  • intermediate_dim (int) – 中间空间的维度。

  • latent_dim (int) – 潜在空间的维度。

  • n_epochs (int) – 训练的 epoch 数量。

  • batch_size (int) – 批次大小。

  • k (int) – 每个用户的顶部 k 个项目数量。

  • verbose (int) – 是否显示训练输出。

  • drop_encoder (float) – 编码器的 Dropout 百分比。

  • drop_decoder (float) – 解码器的 Dropout 百分比。

  • beta (float) – 当不使用退火(annealing=False)时,ELBO 函数中的常数参数 β

  • annealing (bool) – 训练模型时使用退火方法(True)或不使用退火并保持常数 beta(False)的选项

  • anneal_cap (float) – 退火过程中 beta 可以取到的最大值。

  • seed (int) – 种子。

  • save_path (str) – 保存权重的默认路径。

display_metrics()[source]#

绘制:1) 验证集和训练集的每 Epoch 损失 2) 验证集的每 Epoch NDCG@k

fit(x_train, x_valid, x_val_tr, x_val_te, mapper)[source]#

使用训练集拟合模型并在验证集上进行验证。

参数:
  • x_train (numpy.ndarray) – 训练集的点击矩阵。

  • x_valid (numpy.ndarray) – 验证集的点击矩阵。

  • x_val_tr (numpy.ndarray) – 验证集训练部分的点击矩阵。

  • x_val_te (numpy.ndarray) – 验证集测试部分的点击矩阵。

  • mapper (object) – 用于将点击矩阵转换为 DataFrame 的映射器。可以是 AffinityMatrix。

get_optimal_beta()[source]#

返回最优 beta 的值。

ndcg_per_epoch()[source]#

返回每个 Epoch 的 NDCG@k 列表。

nn_batch_generator(x_train)[source]#

用于将数据集分割成批次。

参数:

x_train (numpy.ndarray) – 包含浮点值的训练集点击矩阵。

recommend_k_items(x, k, remove_seen=True)[source]#

返回按相关性分数排序的 top-k 物品。

获得的概率用作推荐得分。

参数:
  • x (numpy.ndarray) – 输入点击矩阵,值为 int32

  • k (scalar) – 要推荐的项目数量。

返回值:

一个包含按分数排序的 top_k 元素的稀疏矩阵。

返回类型:

numpy.ndarray

Multinomial VAE#

class recommenders.models.vae.multinomial_vae.AnnealingCallback(beta, anneal_cap, total_anneal_steps)[source]#

This class is used for updating the value of β during the annealing process. When β reaches the value of anneal_cap, it stops increasing.

__init__(beta, anneal_cap, total_anneal_steps)[source]#

构造函数

参数:
  • beta (float) – current value of beta.

  • anneal_cap (float) – maximum value that beta can reach.

  • total_anneal_steps (int) – total number of annealing steps.

get_data()[source]#

Returns a list of the beta values per epoch.

on_batch_end(epoch, logs={})[source]#

At the end of each batch the beta should is updated until it reaches the values of anneal cap.

on_epoch_end(epoch, logs={})[source]#

At the end of each epoch save the value of beta in _beta list.

on_train_begin(logs={})[source]#

Initialise a list in which the beta value will be saved at the end of each epoch.

class recommenders.models.vae.multinomial_vae.LossHistory[source]#

This class is used for saving the validation loss and the training loss per epoch.

on_epoch_end(epoch, logs={})[source]#

Save the loss of training and validation set at the end of each epoch.

on_train_begin(logs={})[source]#

Initialise the lists where the loss of training and validation will be saved.

class recommenders.models.vae.multinomial_vae.Metrics(model, val_tr, val_te, mapper, k, save_path=None)[source]#

Callback function used to calculate the NDCG@k metric of validation set at the end of each epoch. Weights of the model with the highest NDCG@k value is saved.

__init__(model, val_tr, val_te, mapper, k, save_path=None)[source]#

初始化类参数。

参数:
  • model – 用于验证的已训练模型。

  • val_tr (numpy.ndarray, float) – 验证集训练部分的点击矩阵。

  • val_te (numpy.ndarray, float) – 验证集测试部分的点击矩阵。

  • mapper (AffinityMatrix) – 用于将点击矩阵转换为 DataFrame 的映射器。

  • k (int) – 每个用户的顶部 k 个项目数(可选)。

  • save_path (str) – 保存权重的默认路径。

get_data()[source]#

返回在每个 Epoch 结束时计算的验证集指标的 NDCG@k 列表。

on_epoch_end(batch, logs={})[source]#

在每个 Epoch 结束时计算验证集的 NDCG@k。

如果模型性能得到改善,则保存模型权重。通过添加获得的值来更新验证 NDCG@k 列表

on_train_begin(logs={})[source]#

初始化验证 NDCG@k 的列表。

recommend_k_items(x, k, remove_seen=True)[source]#

返回按相关性得分排序的顶部 k 个项目。获得的概率用作推荐得分。

参数:
  • x (numpy.ndarray, int32) – 输入点击矩阵。

  • k (scalar, int32) – 要推荐的项目数量。

返回值:

一个包含按分数排序的 top_k 元素的稀疏矩阵。

返回类型:

numpy.ndarray

class recommenders.models.vae.multinomial_vae.Mult_VAE(n_users, original_dim, intermediate_dim=200, latent_dim=70, n_epochs=400, batch_size=100, k=100, verbose=1, drop_encoder=0.5, drop_decoder=0.5, beta=1.0, annealing=False, anneal_cap=1.0, seed=None, save_path=None)[source]#

用于协同过滤的 Multinomial Variational Autoencoders (Multi-VAE) 实现

引用:

Liang, Dawen, et al. “用于协同过滤的变分自动编码器。” Proceedings of the 2018 World Wide Web Conference. 2018. https://arxiv.org/pdf/1802.05814.pdf

__init__(n_users, original_dim, intermediate_dim=200, latent_dim=70, n_epochs=400, batch_size=100, k=100, verbose=1, drop_encoder=0.5, drop_decoder=0.5, beta=1.0, annealing=False, anneal_cap=1.0, seed=None, save_path=None)[source]#

构造函数

参数:
  • n_users (int) – 训练集中的唯一用户数量。

  • original_dim (int) – 训练集中的唯一项目数量。

  • intermediate_dim (int) – 中间空间的维度。

  • latent_dim (int) – 潜在空间的维度。

  • n_epochs (int) – 训练的 epoch 数量。

  • batch_size (int) – 批次大小。

  • k (int) – 每个用户的顶部 k 个项目数量。

  • verbose (int) – 是否显示训练输出。

  • drop_encoder (float) – 编码器的 Dropout 百分比。

  • drop_decoder (float) – 解码器的 Dropout 百分比。

  • beta (float) – 当不使用退火(annealing=False)时,ELBO 函数中的常数参数 β

  • annealing (bool) – 训练模型时使用退火方法(True)或不使用退火并保持常数 beta(False)的选项

  • anneal_cap (float) – 退火过程中 beta 可以取到的最大值。

  • seed (int) – 种子。

  • save_path (str) – 保存权重的默认路径。

display_metrics()[source]#

绘制:1) 验证集和训练集的每 Epoch 损失 2) 验证集的每 Epoch NDCG@k

fit(x_train, x_valid, x_val_tr, x_val_te, mapper)[source]#

使用训练集拟合模型并在验证集上进行验证。

参数:
  • x_train (numpy.ndarray) – 训练集的点击矩阵。

  • x_valid (numpy.ndarray) – 验证集的点击矩阵。

  • x_val_tr (numpy.ndarray) – 验证集训练部分的点击矩阵。

  • x_val_te (numpy.ndarray) – 验证集测试部分的点击矩阵。

  • mapper (object) – 用于将点击矩阵转换为 DataFrame 的映射器。可以是 AffinityMatrix。

get_optimal_beta()[source]#

返回最优 beta 的值。

ndcg_per_epoch()[source]#

返回每个 Epoch 的 NDCG@k 列表。

nn_batch_generator(x_train)[source]#

用于将数据集分割成批次。

参数:

x_train (numpy.ndarray) – 包含浮点值的训练集点击矩阵。

recommend_k_items(x, k, remove_seen=True)[source]#

返回按相关性得分排序的顶部 k 个项目。获得的概率用作推荐得分。

参数:
  • x (numpy.ndarray, int32) – 输入点击矩阵。

  • k (scalar, int32) – 要推荐的项目数量。

返回值:

一个包含按分数排序的 top_k 元素的稀疏矩阵。

返回类型:

numpy.ndarray, float

Vowpal Wabbit 工具集#

本文件提供了通过 python 从命令行运行 Vowpal Wabbit 的封装。不建议在生产环境中使用此方法,可以从仓库或 pip 安装 python 绑定,或者直接使用命令行。这仅仅是为了在示例笔记本中演示 vw 的用法。

class recommenders.models.vowpal_wabbit.vw.VW(col_user='userID', col_item='itemID', col_rating='rating', col_timestamp='timestamp', col_prediction='prediction', **kwargs)[source]#

Vowpal Wabbit 类

fit(df)[source]#

训练模型

参数:

df (pandas.DataFrame) – 输入训练数据

parse_test_params(params)[source]#

解析输入超参数以构建 vw 测试命令

参数:

params (dict) – 键 = 参数, 值 = 值 (如果参数仅为标志,使用 True)

返回值:

vw 命令行参数列表(字符串)

返回类型:

list[str]

parse_train_params(params)[source]#

解析输入超参数以构建 vw 训练命令

参数:

params (dict) – 键 = 参数, 值 = 值 (如果参数仅为标志,使用 True)

返回值:

vw 命令行参数列表(字符串)

返回类型:

list[str]

predict(df)[source]#

预测结果

参数:

df (pandas.DataFrame) – 输入测试数据

static to_vw_cmd(params)[source]#

将参数字典转换为 vw 命令行。

参数:

params (dict) – 键 = 参数, 值 = 值 (如果参数仅为标志,使用 True)

返回值:

vw 命令行参数列表(字符串)

返回类型:

list[str]

to_vw_file(df, train=True)[source]#

将 Pandas DataFrame 转换为 vw 输入格式文件

参数:
  • df (pandas.DataFrame) – 输入 DataFrame

  • train (bool) – 训练模式标志(或测试模式,如果为 False)

Wide & Deep#

recommenders.models.wide_deep.wide_deep_utils.build_feature_columns(users, items, user_col='userID', item_col='itemID', item_feat_col=None, crossed_feat_dim=1000, user_dim=8, item_dim=8, item_feat_shape=None, model_type='wide_deep')[source]#

为 TensorFlow 高级 API Estimator 构建 wide 和/或 deep 特征列。

参数:
  • users (iterable) – 不同的用户 ID。

  • items (iterable) – 不同的项目 ID。

  • user_col (str) – 用户列名。

  • item_col (str) – 项目列名。

  • item_feat_col (str) – 用于 ‘deep’ 或 ‘wide_deep’ 模型项目特征列名称。

  • crossed_feat_dim (int) – 用于 ‘wide’ 或 ‘wide_deep’ 模型交叉特征维度。

  • user_dim (int) – 用于 ‘deep’ 或 ‘wide_deep’ 模型用户嵌入维度。

  • item_dim (int) – 用于 ‘deep’ 或 ‘wide_deep’ 模型项目嵌入维度。

  • item_feat_shape (int or an iterable of integers) – 用于 ‘deep’ 或 ‘wide_deep’ 模型项目特征数组形状。

  • model_type (str) – 模型类型,可以是线性模型的 ‘wide’,深度神经网络的 ‘deep’,或线性模型和神经网络组合的 ‘wide_deep’。

返回值:

  • wide 特征列

  • deep 特征列。如果只选择了 wide 模型,则 deep 列列表为空,反之亦然。

返回类型:

list, list

recommenders.models.wide_deep.wide_deep_utils.build_model(model_dir='model_checkpoints', wide_columns=(), deep_columns=(), linear_optimizer='Ftrl', dnn_optimizer='Adagrad', dnn_hidden_units=(128, 128), dnn_dropout=0.0, dnn_batch_norm=True, log_every_n_iter=1000, save_checkpoints_steps=10000, seed=None)[source]#

构建 wide-deep 模型。

要生成 wide 模型,仅传递 wide_columns。要生成 deep 模型,仅传递 deep_columns。要生成 wide_deep 模型,同时传递 wide_columns 和 deep_columns。

参数:
  • model_dir (str) – 模型检查点目录。

  • wide_columns (list of tf.feature_column) – wide 模型特征列。

  • deep_columns (list of tf.feature_column) – deep 模型特征列。

  • linear_optimizer (str or tf.train.Optimizer) – wide 模型优化器名称或对象。

  • dnn_optimizer (str or tf.train.Optimizer) – deep 模型优化器名称或对象。

  • dnn_hidden_units (list of int) – deep 模型隐藏单元。例如,[10, 10, 10] 表示三层,每层 10 个节点。

  • dnn_dropout (float) – deep 模型的 dropout 率。

  • dnn_batch_norm (bool) – deep 模型的批标准化标志。

  • log_every_n_iter (int) – 每隔 n 步记录一次训练损失。

  • save_checkpoints_steps (int) – 模型检查点频率。

  • seed (int) – 随机种子。

返回值:

模型

返回类型:

tf.estimator.Estimator