python surprise

本文详细介绍Surprise库,一个Python推荐系统库,支持多种预测算法,如SVD、KNN等。文章介绍了库的安装方法、预测算法配置及使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

surprise 库


目录

参考文档

Surprise’ documentation
GitHub — Surprise

安装

With pip (you’ll need numpy, and a C compiler. Windows users might prefer using conda):

$ pip install numpy
$ pip install scikit-surprise

With conda:

$ conda install -c conda-forge scikit-surprise

For the latest version, you can also clone the repo and build the source (you’ll first need Cython and numpy):

$ pip install numpy cython
$ git clone https://github.com/NicolasHug/surprise.git
$ cd surprise
$ python setup.py install

预测算法

  1. 所有算法都由AlgoBase基类生成,基类里实现了一些关键的方法,(e.g. predict, fit and test).
  2. Every algorithm is part of the global Surprise namespace, so you only need to import their names from the Surprise package
    任何算法都是在surprise库的全局命名空间中,可以直接调用。

prediction_algorithms

算法类名说明解释
random_pred.NormalPredictorAlgorithm predicting a random rating based on the distribution of the training set, which is assumed to be normal.根据训练集的分布特征随机给出一个预测值
baseline_only.BaselineOnlyAlgorithm predicting the baseline estimate for given user and item.给定用户和Item,给出基于baseline的估计值
knns.KNNBasicA basic collaborative filtering algorithm.最基础的协作过滤
knns.KNNWithMeansA basic collaborative filtering algorithm, taking into account the mean ratings of each user.将每个用户评分的均值考虑在内的协作过滤实现
knns.KNNBaselineA basic collaborative filtering algorithm taking into account a baseline rating.考虑基线评级的协作过滤
matrix_factorization.SVDThe famous SVD algorithm, as popularized by Simon Funk during the Netflix Prize.SVD实现
matrix_factorization.SVDppThe SVD++ algorithm, an extension of SVD taking into account implicit ratings.SVD++,即LFM+SVD
matrix_factorization.NMFA collaborative filtering algorithm based on Non-negative Matrix Factorization.基于矩阵分解的协作过滤
slope_one.SlopeOneA simple yet accurate collaborative filtering algorithm.一个简单但精确的协作过滤算法
co_clustering.CoClusteringA collaborative filtering algorithm based on co-clustering.基于协同聚类的协同过滤算法

The algorithm base class 算法基类

The surprise.prediction_algorithms.algo_base module defines the base class AlgoBase from which every single prediction algorithm has to inherit.

  1. fit(trainset)

    Train an algorithm on a given training set.
    This method is called by every derived class as the first basic step for training an algorithm. It basically just initializes some internal structures and set the self.trainset attribute.
    Parameters: trainset (Trainset) – A training set, as returned by the folds method.
    Returns: self

    在一个给定的数据集上训练一个算法

Baselines estimates configuration 基线法估计配置

中用到最小化平方误差函数的算法(包括Baseline 方法 和相似度计算)都需要配置参数,不同的参数会导致算法有不同的性能,且不同的 baseline 用于不同的算法,参数配置不一样。
使用默认的baseline参数已经可以取得一定的性能的。
需要注意的是,一些相似度度量用到Baseline,无论实际的预测算法是否用到baseline,都需要配置相关参数
具体的参数配置,可以参考这篇论文
Factor in the Neighbors: Scalable and Accurate Collaborative Filtering

使用GridSearchCV调整算法参数

cross_validate()函数针对给定的一组参数报告交叉验证过程的准确性度量。 如果你想知道哪个参数组合可以产生最好的结果,那么GridSearchCV类就可以解决问题。 给定一个参数的字典,这个类彻底地尝试所有参数组合,并报告任何准确性度量(在不同分割上的平均值)的最佳参数。 它受到scikit-learn的GridSearchCV的启发。

Similarity measure configuration 相似度度量配置

Many algorithms use a similarity measure to estimate a rating. The way they can be configured is done in a similar fashion as for baseline ratings: you just need to pass a sim_options argument at the creation of an algorithm. This argument is a dictionary with the following (all optional) keys:

通过指定sim_options这个字典变量来配置相似度指标
1. name: 指定相似度指标的名字,similarities module 中给出了MSD
2. user_based: 指定是使用计算用户之间的相似度还是Item之间的相似度,这个地方的选择对预测算法的性能有巨大影响,默认值:True
3. min_support:当相似度不为0时,最小公共用户数或公共项目数
4. shrinkage: 收缩参数,仅用于 pearson_baseline 相似度

Trainset class

It is used by the fit() method of every prediction algorithm. You should not try to built such an object on your own but rather use the Dataset.folds() method or the DatasetAutoFolds.build_full_trainset() method.

训练集不应该由个人创建,可以通过Dataset.folds()或者DatasetAutoFolds.build_full_trainset()方法创建。

源码解读

reader 类

def __init__(self, name=None, line_format='user item rating',
            sep=None,rating_scale=(1, 5), skip_lines=0):

建立阅读器的格式,自动将评分定在rating_scale区间
self.offset : self.offset = -lower_bound + 1 if lower_bound <= 0 else 0

def parse_line(self, line)
    '''Parse a line.

        Ratings are translated so that they are all strictly positive.

        Args:
            line(str): The line to parse

        Returns:
            tuple: User id, item id, rating and timestamp. The timestamp is set  to ``None`` if it does no exist.
    '''

解析一行,返回需要的格式数据

dataset 类

def build_full_trainset(self):
    """Do not split the dataset into folds and just return a trainset as
    is, built from the whole dataset.

    User can then query for predictions, as shown in the :ref:`User Guide
    <train_on_whole_trainset>`.

    Returns:
        The :class:`Trainset <surprise.Trainset>`.
    """

将所有数据用于生成训练集

 def construct_trainset(self, raw_trainset):

建立 `raw_id` 到 `inner_id`的映射
得到 ur 字典 --- `用户-评分`字典
     ir 字典 --- `Item-评分`字典
     n_users --- 用户数
     n_items --- Item数
     n_ratings --- 评分记录数

建立训练集

trainset 类

KNNBaseline 类

  1. KNNBaseline
    KNNBaseline.png
    考虑基础评分的协同过滤
    最好用 pearson_baseline 相似度
    关于Baseline方法的作用,可以参考这篇文章
    推荐系统的协同过滤算法实现和浅析 pdf

KNNBasic 类

KNNBasic.png

def fit(self, trainset):
    """
    计算相似度
    计算公式的由来可以参考相关书籍
    """
def estimate(self, u, i):
    """
    估计用户u对物品i的打分
    找出在给物品i打过分的k个近邻用户
    根据相应的预测评分计算公式计算预测评分
    返回值: est, details({'actual_k': actual_k})
    """

example

库中,是预测所有用户没有评论过的物品的评分
不适合做Top-N推荐

split 数据分割

数据分割部分的分割操作都是针对所有数据集的操作,适合评分预测的应用,不适合Top-N推荐的应用(有待验证)

ShuffleSplit 类

shuffleSplit
将所有的训练数据随机地分成k份。

train_test_split
将数据分割为训练集和测试集割为训练集和测试集

<think>我们正在回答用户关于如何下载和安装PythonSurprise库的问题。根据系统指令,我们需要使用中文回答,并遵循LaTeX格式要求,同时生成相关问题。由于用户的问题是关于安装Surprise库,我们可以参考一般的Python包安装方法,但注意Surprise可能需要一些依赖。步骤:1.确保已安装Python和pip(Python包管理工具)。2.使用pip安装Surprise库。但是,需要注意的是,Surprise库在安装时可能会因为依赖问题(如编译环境)而失败,特别是在Windows系统上。因此,我们可能需要提供一些额外的指导。另外,根据引用[1]和[2]的内容,我们可以知道:-用户可能使用Anaconda(这可以避免一些环境问题)[^1]。-另外,引用[2]提到Python可以调用高性能的代码,而Surprise库是一个用于推荐系统的库,其中可能包含一些C扩展,因此需要编译环境。因此,我们给出两种安装方法:使用pip安装和使用conda安装(如果使用Anaconda)。同时,我们还需要注意,Surprise库的官方文档中提到的安装方法。根据Surprise的官方文档(http://surpriselib.com/),安装方法如下:-使用pip:`pipinstallscikit-surprise`-使用conda:`condainstall-cconda-forgescikit-surprise`但是,由于网络问题,可能需要使用国内镜像源。因此,我们给出以下安装步骤:方法一:使用pip安装1.打开命令行(终端)。2.输入命令:`pipinstallscikit-surprise`如果遇到权限问题,可以尝试:`pipinstall--userscikit-surprise`如果速度慢,可以使用国内镜像,例如:`pipinstallscikit-surprise-ihttps://pypi.tuna.tsinghua.edu.cn/simple`方法二:使用conda安装(推荐,尤其对于Windows用户)1.打开AnacondaPrompt(如果安装了Anaconda)。2.输入命令:`condainstall-cconda-forgescikit-surprise`注意:在Windows上使用pip安装可能需要C++编译环境(如MicrosoftVisualC++BuildTools),因为Surprise依赖的scipy和numpy可能需要编译。如果遇到编译错误,建议使用conda安装。验证安装:在Python环境中运行:fromsurpriseimportDatasetdata=Dataset.load_builtin('ml-100k')如果能够成功导入,则说明安装成功。同时,我们还需要生成相关问题。根据用户的问题,我们生成以下相关问题:1.如何验证Surprise库是否安装成功?2.安装Surprise库时遇到编译错误怎么办?3.Surprise库支持哪些推荐算法?注意:回答中引用的内容末尾需要添加引用标识。但在这个问题中,我们并没有直接引用提供的引用内容,而是参考了引用[1]和[2]提到的Anaconda和编译问题。因此,在提到Anaconda和编译问题时,可以添加引用标识。但是,我们提供的安装步骤是通用的,所以不一定需要添加引用。如果我们在回答中提到了引用中的内容(如使用Anaconda可以避免环境问题),则可以添加引用标识。我们这样写:如果使用Anaconda,可以避免一些环境问题(如编译环境)[^1]。这是因为Anaconda自带了预编译的包。同时,我们也可以提到:由于Surprise库可能包含需要编译的代码,因此对于Windows用户,如果没有安装编译环境,可能会遇到问题[^2]。而使用conda安装则可以直接使用预编译的二进制包。因此,在回答中,我们可以这样引用:回答结构:1.介绍两种安装方法。2.分别详细说明步骤。3.提供验证安装的方法。4.生成相关问题。注意:系统指令要求行内数学表达式用$...$,独立公式用$$...$$,但这个问题不涉及数学公式,所以可以忽略。开始回答:</think>### 如何安装 Python SurpriseSurprise 是一个用于构建和分析推荐系统的 Python 库,以下是详细的安装步骤: #### 🛠️ 安装方法 1. **通过 pip 安装(推荐)** 在命令行中执行: ```bash pip install scikit-surprise ``` 若遇到网络问题,可使用国内镜像源加速: ```bash pip install scikit-surprise -i https://pypi.tuna.tsinghua.edu.cn/simple ``` 2. **通过 conda 安装(Anaconda 用户)** 使用 conda-forge 渠道: ```bash conda install -c conda-forge scikit-surprise ``` #### ⚠️ 注意事项 - **依赖环境**: Surprise 依赖 NumPy 和 SciPy。如果安装失败,先确保这些基础库已安装: ```bash pip install numpy scipy ``` - **编译工具**: Windows 用户可能需要安装 [Microsoft C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/),因为部分组件需要编译[^2]。 #### ✅ 验证安装 在 Python 中运行以下代码测试: ```python from surprise import Dataset data = Dataset.load_builtin('ml-100k') # 加载内置数据集 print("Surprise 安装成功!可加载数据集:", data) ``` #### 💻 开发环境建议 推荐使用 Jupyter Notebook 进行推荐系统实验。可通过 Anaconda 启动 Jupyter: ```bash conda activate your_env jupyter notebook ``` 这能提供交互式环境方便调试[^1]。 --- ### 📚 相关问题 1. 如何用 Surprise 实现基本的协同过滤推荐算法? 2. 在 Surprise 中如何处理自定义数据集? 3. 如何评估 Surprise 推荐模型的性能指标(如 RMSE、MAE)? 4. Surprise 支持哪些高级推荐算法(如 SVD++、NMF)? > 提示:安装后可通过 `surprise.__version__` 检查版本,最新稳定版为 1.1.3。遇到依赖问题可尝试 `pip install --upgrade numpy scikit-learn` 更新相关库[^2]。 [^1]: 可通过 Anaconda 启动 Jupyter 进行交互式开发 [^2]: Windows 用户可能需要安装 C++ 编译工具处理二进制依赖
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值