具有惊奇预测的Sklearn标签编码器逆变换

时间:2018-07-26 19:54:52

标签: python machine-learning categorization

我有一个数据集,正在使用Label Encoder对数据进行分类(从字符串到数字)。

然后我正在使用Surprise库来训练推荐系统模型。

我使用以下代码获得预测:

# A reader is still needed but only the rating_scale param is requiered.
reader = Reader(rating_scale=(1, 100))

# The columns must correspond to user id, item id and ratings (in that order).
data = Dataset.load_from_df(df_categorized, reader)

# First train an SVD algorithm on the dataset.
trainset = data.build_full_trainset()
algo = SVD()
algo.fit(trainset)

# Than predict ratings for all pairs (u, i) that are NOT in the training set.
testset = trainset.build_anti_testset()
predictions = algo.test(testset)

top_n = get_top_n(predictions, n=5)

我使用了top_n方法,该方法获取top_n建议如下:

def get_top_n(predictions, n=5):
    '''Return the top-N recommendation for each user from a set of predictions.

    Args:
        predictions(list of Prediction objects): The list of predictions, as
            returned by the test method of an algorithm.
        n(int): The number of recommendation to output for each user. Default
            is 10.

    Returns:
    A dict where keys are user (raw) ids and values are lists of tuples:
        [(raw item id, rating estimation), ...] of size n.
    '''

    # First map the predictions to each user.
    top_n = defaultdict(list)
    for uid, iid, true_r, est, _ in predictions:
        top_n[uid].append((iid, est))

    # Then sort the predictions for each user and retrieve the k highest ones.
    for uid, user_ratings in top_n.items():
        user_ratings.sort(key=lambda x: x[1], reverse=True)
        top_n[uid] = user_ratings[:n]

    return top_n

由于首先使用Label Encoder对数据进行了分类,所以top_n会将userId称为编码值,并将推荐的内容也称为编码值。

如何将数据反转换回未编码的值?

我试图获取从top_n返回的键(已编码userId),并使用标签编码器逆变换方法,但是,由于它是字典,因此它没有该方法工作所需的索引。对于存储为字典中值的推荐内容也是如此。

0 个答案:

没有答案