人工智能在推荐系统中的应用与优化

AI2周前发布 beixibaobao
16 0 0

第七篇:人工智能在推荐系统中的应用与优化

在这里插入图片描述

学习目标

💡 理解推荐系统的基本概念和重要性
💡 掌握推荐系统常用的算法(协同过滤、内容推荐、混合推荐)
💡 学会使用推荐系统库(Surprise、TensorFlow Recommenders)构建简单的推荐系统
💡 理解推荐系统的评估指标和优化方法
💡 通过实战项目,开发一个完整的推荐系统

重点内容

  • 推荐系统的基本概念
  • 推荐系统常用算法(协同过滤、内容推荐、混合推荐)
  • 推荐系统库介绍(Surprise、TensorFlow Recommenders)
  • 推荐系统的评估指标和优化方法
  • 实战项目:推荐系统开发

一、推荐系统基础

1.1 推荐系统的基本概念

推荐系统是一种信息过滤系统,它根据用户的历史行为、兴趣爱好和需求,向用户推荐相关的内容。推荐系统在电商、社交网络、音乐、视频等领域都有广泛的应用。

1.1.1 推荐系统的重要性

推荐系统具有以下重要性:

  1. 提高用户体验:推荐系统可以根据用户的兴趣爱好和需求,向用户推荐相关的内容,提高用户体验
  2. 增加用户粘性:推荐系统可以让用户更容易找到感兴趣的内容,增加用户粘性
  3. 提高转化率:推荐系统可以向用户推荐相关的商品,提高转化率
  4. 优化资源分配:推荐系统可以根据用户的需求,优化资源分配
  5. 数据驱动决策:推荐系统可以收集和分析用户数据,为企业提供数据驱动的决策支持
1.1.2 推荐系统的应用场景

推荐系统在各个领域都有广泛的应用,主要包括:

  • 电商:推荐商品
  • 社交网络:推荐好友、帖子
  • 音乐:推荐歌曲、歌手
  • 视频:推荐电影、电视剧
  • 新闻:推荐新闻内容
  • 广告:推荐广告内容

1.2 推荐系统的基本类型

推荐系统的基本类型包括:

1.2.1 协同过滤推荐

协同过滤推荐是基于用户或物品的相似性来推荐相关的内容。它分为用户协同过滤和物品协同过滤两种类型。

1.2.2 内容推荐

内容推荐是基于物品的内容特征来推荐相关的内容。它根据用户的历史行为和兴趣爱好,向用户推荐具有相似内容特征的物品。

1.2.3 混合推荐

混合推荐是将协同过滤推荐和内容推荐相结合的推荐方法。它可以克服协同过滤推荐和内容推荐的缺点,提高推荐的准确性。


二、推荐系统常用算法

2.1 协同过滤推荐算法

2.1.1 用户协同过滤

用户协同过滤是基于用户的相似性来推荐相关的内容。它首先找到与目标用户相似的用户,然后根据相似用户的历史行为向目标用户推荐相关的内容。

2.1.2 物品协同过滤

物品协同过滤是基于物品的相似性来推荐相关的内容。它首先找到与目标物品相似的物品,然后根据目标用户的历史行为向目标用户推荐相关的内容。

2.1.3 协同过滤的代码实现

以下是一个简单的协同过滤代码实现:

import numpy as np
from surprise import Dataset, Reader, KNNBasic
from surprise.model_selection import cross_validate
# 准备数据
data = Dataset.load_builtin("ml-100k")
# 选择算法
sim_options = {"name": "cosine", "user_based": True}
algo = KNNBasic(sim_options=sim_options)
# 训练模型
cross_validate(algo, data, measures=["RMSE", "MAE"], cv=5, verbose=True)

2.2 内容推荐算法

2.2.1 内容推荐的基本原理

内容推荐的基本原理是基于物品的内容特征来推荐相关的内容。它根据用户的历史行为和兴趣爱好,向用户推荐具有相似内容特征的物品。

2.2.2 内容推荐的代码实现

以下是一个简单的内容推荐代码实现:

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# 准备数据
documents = [
    "这是一篇关于机器学习的文章",
    "这是一篇关于深度学习的文章",
    "这是一篇关于自然语言处理的文章",
    "这是一篇关于计算机视觉的文章"
]
# 计算TF-IDF向量
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(documents)
# 计算余弦相似度
cosine_sim = cosine_similarity(tfidf_matrix, tfidf_matrix)
# 打印相似度矩阵
print(cosine_sim)

2.3 混合推荐算法

2.3.1 混合推荐的基本原理

混合推荐是将协同过滤推荐和内容推荐相结合的推荐方法。它可以克服协同过滤推荐和内容推荐的缺点,提高推荐的准确性。

2.3.2 混合推荐的代码实现

以下是一个简单的混合推荐代码实现:

import numpy as np
from surprise import Dataset, Reader, KNNBasic, SVD
from surprise.model_selection import cross_validate
# 准备数据
data = Dataset.load_builtin("ml-100k")
# 选择算法
sim_options = {"name": "cosine", "user_based": True}
algo1 = KNNBasic(sim_options=sim_options)
algo2 = SVD()
# 训练模型
results1 = cross_validate(algo1, data, measures=["RMSE", "MAE"], cv=5, verbose=True)
results2 = cross_validate(algo2, data, measures=["RMSE", "MAE"], cv=5, verbose=True)
# 打印结果
print("KNNBasic Results:")
print("RMSE: {:.4f}".format(np.mean(results1["test_rmse"])))
print("MAE: {:.4f}".format(np.mean(results1["test_mae"])))
print("SVD Results:")
print("RMSE: {:.4f}".format(np.mean(results2["test_rmse"])))
print("MAE: {:.4f}".format(np.mean(results2["test_mae"])))

三、推荐系统库介绍

3.1 Surprise 介绍

Surprise 是一个专门用于推荐系统的 Python 库。它提供了多种协同过滤算法的实现,包括 KNNBasic、KNNWithMeans、SVD 等。

3.1.1 Surprise 的安装

Surprise 可以通过 pip 安装:

pip install scikit-surprise
3.1.2 Surprise 的基本使用

以下是一个简单的 Surprise 使用示例:

import numpy as np
from surprise import Dataset, Reader, KNNBasic
from surprise.model_selection import cross_validate
# 准备数据
data = Dataset.load_builtin("ml-100k")
# 选择算法
sim_options = {"name": "cosine", "user_based": True}
algo = KNNBasic(sim_options=sim_options)
# 训练模型
cross_validate(algo, data, measures=["RMSE", "MAE"], cv=5, verbose=True)

3.2 TensorFlow Recommenders 介绍

TensorFlow Recommenders 是 Google 开发的推荐系统库。它提供了多种推荐系统算法的实现,包括协同过滤、内容推荐、混合推荐等。

3.2.1 TensorFlow Recommenders 的安装

TensorFlow Recommenders 可以通过 pip 安装:

pip install tensorflow-recommenders
3.2.2 TensorFlow Recommenders 的基本使用

以下是一个简单的 TensorFlow Recommenders 使用示例:

import tensorflow as tf
import tensorflow_recommenders as tfrs
import numpy as np
# 准备数据
ratings = tf.data.Dataset.from_tensor_slices({
    "user_id": [1, 1, 2, 2, 3, 3],
    "item_id": [1, 2, 1, 3, 2, 3],
    "rating": [5, 4, 3, 5, 4, 5]
})
# 构建模型
class RecommendationModel(tfrs.Model):
    def __init__(self):
        super().__init__()
        self.user_model = tf.keras.Sequential([
            tf.keras.layers.experimental.preprocessing.StringLookup(
                vocabulary=ratings.map(lambda x: x["user_id"]).unique().numpy(), mask_token=None),
            tf.keras.layers.Embedding(len(ratings.map(lambda x: x["user_id"]).unique().numpy()) + 1, 64)
        ])
        self.item_model = tf.keras.Sequential([
            tf.keras.layers.experimental.preprocessing.StringLookup(
                vocabulary=ratings.map(lambda x: x["item_id"]).unique().numpy(), mask_token=None),
            tf.keras.layers.Embedding(len(ratings.map(lambda x: x["item_id"]).unique().numpy()) + 1, 64)
        ])
        self.task = tfrs.tasks.Retrieval(
            metrics=tfrs.metrics.FactorizedTopK(
                candidates=ratings.map(lambda x: x["item_id"]).batch(128).map(self.item_model)
            )
        )
    def compute_loss(self, features, training=False):
        user_embeddings = self.user_model(features["user_id"])
        item_embeddings = self.item_model(features["item_id"])
        return self.task(user_embeddings, item_embeddings)
model = RecommendationModel()
model.compile(optimizer=tf.keras.optimizers.Adagrad(learning_rate=0.1))
# 训练模型
model.fit(ratings.batch(2).shuffle(100), epochs=3)
# 测试模型
scores, titles = model.user_model(np.array([1])), model.item_model(np.array([1, 2, 3]))
print("Scores:", scores)
print("Titles:", titles)

四、推荐系统的评估指标和优化方法

4.1 推荐系统的评估指标

推荐系统的评估指标主要包括:

4.1.1 准确率(Accuracy)

准确率是指推荐系统推荐的内容与用户真实需求相符的比例。

4.1.2 召回率(Recall)

召回率是指推荐系统推荐的内容中,用户真实需求的比例。

4.1.3 精确率(Precision)

精确率是指推荐系统推荐的内容中,与用户真实需求相符的比例。

4.1.4 F1 值

F1 值是准确率和召回率的调和平均。

4.1.5 ROC 曲线和 AUC 值

ROC 曲线是指真阳性率和假阳性率之间的关系曲线,AUC 值是 ROC 曲线下的面积。

4.2 推荐系统的优化方法

推荐系统的优化方法主要包括:

4.2.1 特征工程

特征工程是推荐系统的基础,它可以提高推荐系统的准确性。

4.2.2 算法优化

算法优化是推荐系统的核心,它可以提高推荐系统的性能。

4.2.3 模型融合

模型融合是将多个推荐系统模型相结合的方法,它可以提高推荐系统的准确性。

4.2.4 实时推荐

实时推荐是根据用户的实时行为向用户推荐相关的内容,它可以提高推荐系统的响应速度。


五、实战项目:推荐系统开发

5.1 项目需求分析

5.1.1 应用目标

构建一个推荐系统,能够根据用户的历史行为向用户推荐相关的内容。

5.1.2 用户需求
  • 支持用户登录和注册
  • 支持用户浏览和搜索内容
  • 支持用户对内容进行评分和评论
  • 支持向用户推荐相关的内容
  • 提供友好的用户界面,使用简单方便
5.1.3 功能范围
  • 用户登录和注册
  • 内容浏览和搜索
  • 内容评分和评论
  • 内容推荐
  • 结果可视化

5.2 系统架构设计

5.2.1 应用架构

该推荐系统的架构采用分层设计,分为以下几个层次:

  1. 用户界面层:提供用户与系统的交互接口,包括用户登录和注册、内容浏览和搜索、内容评分和评论、内容推荐等功能
  2. 应用逻辑层:处理用户请求、业务逻辑和应用控制
  3. 数据处理层:对数据进行处理和分析
  4. 数据存储层:存储用户数据、内容数据和评分数据
5.2.2 数据存储方案

该系统的数据存储方案包括以下几个部分:

  1. 用户数据存储:使用数据库存储用户的基本信息
  2. 内容数据存储:使用数据库存储内容的基本信息
  3. 评分数据存储:使用数据库存储用户对内容的评分信息

5.3 系统实现

5.3.1 开发环境搭建

首先,需要搭建开发环境。该系统使用 Python 作为开发语言,使用 Flask 作为 Web 框架,使用 SQLite 作为数据库,使用 Surprise 库进行推荐系统开发。

# 安装 Flask 库
pip install flask
# 安装 Surprise 库
pip install scikit-surprise
# 安装 SQLite 库
pip install sqlite3
5.3.2 数据库设计

数据库设计是系统的基础功能。以下是数据库设计的实现代码:

import sqlite3
# 连接数据库
conn = sqlite3.connect("recommendation.db")
cursor = conn.cursor()
# 创建用户表
cursor.execute("""
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT NOT NULL,
        password TEXT NOT NULL,
        email TEXT NOT NULL
    )
""")
# 创建内容表
cursor.execute("""
    CREATE TABLE IF NOT EXISTS contents (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        description TEXT NOT NULL,
        category TEXT NOT NULL
    )
""")
# 创建评分表
cursor.execute("""
    CREATE TABLE IF NOT EXISTS ratings (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id INTEGER NOT NULL,
        content_id INTEGER NOT NULL,
        rating INTEGER NOT NULL,
        FOREIGN KEY (user_id) REFERENCES users (id),
        FOREIGN KEY (content_id) REFERENCES contents (id)
    )
""")
# 提交更改
conn.commit()
# 关闭连接
conn.close()
5.3.3 用户管理

用户管理是系统的基础功能。以下是用户管理的实现代码:

import sqlite3
from werkzeug.security import generate_password_hash, check_password_hash
def add_user(username, password, email):
    try:
        conn = sqlite3.connect("recommendation.db")
        cursor = conn.cursor()
        hashed_password = generate_password_hash(password)
        cursor.execute("INSERT INTO users (username, password, email) VALUES (?, ?, ?)", (username, hashed_password, email))
        conn.commit()
        conn.close()
        return True
    except Exception as e:
        print(f"添加用户失败:{e}")
        return False
def get_user(username):
    try:
        conn = sqlite3.connect("recommendation.db")
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
        user = cursor.fetchone()
        conn.close()
        return user
    except Exception as e:
        print(f"获取用户失败:{e}")
        return None
def verify_password(username, password):
    try:
        user = get_user(username)
        if user:
            return check_password_hash(user[2], password)
        else:
            return False
    except Exception as e:
        print(f"验证密码失败:{e}")
        return False
5.3.4 内容管理

内容管理是系统的基础功能。以下是内容管理的实现代码:

import sqlite3
def add_content(title, description, category):
    try:
        conn = sqlite3.connect("recommendation.db")
        cursor = conn.cursor()
        cursor.execute("INSERT INTO contents (title, description, category) VALUES (?, ?, ?)", (title, description, category))
        conn.commit()
        conn.close()
        return True
    except Exception as e:
        print(f"添加内容失败:{e}")
        return False
def get_content(content_id):
    try:
        conn = sqlite3.connect("recommendation.db")
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM contents WHERE id = ?", (content_id,))
        content = cursor.fetchone()
        conn.close()
        return content
    except Exception as e:
        print(f"获取内容失败:{e}")
        return None
def get_all_contents():
    try:
        conn = sqlite3.connect("recommendation.db")
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM contents")
        contents = cursor.fetchall()
        conn.close()
        return contents
    except Exception as e:
        print(f"获取所有内容失败:{e}")
        return None
5.3.5 评分管理

评分管理是系统的基础功能。以下是评分管理的实现代码:

import sqlite3
def add_rating(user_id, content_id, rating):
    try:
        conn = sqlite3.connect("recommendation.db")
        cursor = conn.cursor()
        cursor.execute("INSERT INTO ratings (user_id, content_id, rating) VALUES (?, ?, ?)", (user_id, content_id, rating))
        conn.commit()
        conn.close()
        return True
    except Exception as e:
        print(f"添加评分失败:{e}")
        return False
def get_rating(user_id, content_id):
    try:
        conn = sqlite3.connect("recommendation.db")
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM ratings WHERE user_id = ? AND content_id = ?", (user_id, content_id))
        rating = cursor.fetchone()
        conn.close()
        return rating
    except Exception as e:
        print(f"获取评分失败:{e}")
        return None
def get_all_ratings():
    try:
        conn = sqlite3.connect("recommendation.db")
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM ratings")
        ratings = cursor.fetchall()
        conn.close()
        return ratings
    except Exception as e:
        print(f"获取所有评分失败:{e}")
        return None
5.3.6 推荐系统

推荐系统是系统的核心功能。以下是推荐系统的实现代码:

import numpy as np
from surprise import Dataset, Reader, KNNBasic
from surprise.model_selection import cross_validate
import sqlite3
def get_recommendations(user_id, n=10):
    try:
        # 准备数据
        conn = sqlite3.connect("recommendation.db")
        cursor = conn.cursor()
        cursor.execute("SELECT user_id, content_id, rating FROM ratings")
        ratings = cursor.fetchall()
        conn.close()
        reader = Reader(rating_scale=(1, 5))
        data = Dataset.load_from_df(np.array(ratings), reader)
        # 选择算法
        sim_options = {"name": "cosine", "user_based": True}
        algo = KNNBasic(sim_options=sim_options)
        # 训练模型
        trainset = data.build_full_trainset()
        algo.fit(trainset)
        # 获取所有内容
        contents = get_all_contents()
        # 计算推荐结果
        recommendations = []
        for content in contents:
            content_id = content[0]
            rating = algo.predict(user_id, content_id).est
            recommendations.append((content_id, rating))
        # 排序推荐结果
        recommendations = sorted(recommendations, key=lambda x: x[1], reverse=True)
        # 选择前 n 个推荐结果
        recommendations = recommendations[:n]
        # 获取推荐内容的详细信息
        recommended_contents = []
        for recommendation in recommendations:
            content_id = recommendation[0]
            content = get_content(content_id)
            recommended_contents.append(content)
        return recommended_contents
    except Exception as e:
        print(f"获取推荐结果失败:{e}")
        return None
5.3.7 用户界面

用户界面是系统的交互部分。以下是用户界面的实现代码:

from flask import Flask, render_template, request, redirect, url_for, session
import os
import uuid
from user_manager import add_user, get_user, verify_password
from content_manager import add_content, get_content, get_all_contents
from rating_manager import add_rating, get_rating, get_all_ratings
from recommendation_system import get_recommendations
app = Flask(__name__)
app.secret_key = "secret_key"
@app.route("/")
def index():
    if "username" in session:
        return render_template("index.html", username=session["username"])
    else:
        return redirect(url_for("login"))
@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        if verify_password(username, password):
            session["username"] = username
            return redirect(url_for("index"))
        else:
            return render_template("login.html", error="用户名或密码错误")
    return render_template("login.html")
@app.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        email = request.form["email"]
        if add_user(username, password, email):
            session["username"] = username
            return redirect(url_for("index"))
        else:
            return render_template("register.html", error="注册失败")
    return render_template("register.html")
@app.route("/logout")
def logout():
    session.pop("username", None)
    return redirect(url_for("login"))
@app.route("/contents")
def contents():
    if "username" not in session:
        return redirect(url_for("login"))
    contents = get_all_contents()
    return render_template("contents.html", contents=contents)
@app.route("/content/<int:content_id>")
def content(content_id):
    if "username" not in session:
        return redirect(url_for("login"))
    content = get_content(content_id)
    user = get_user(session["username"])
    rating = get_rating(user[0], content_id)
    return render_template("content.html", content=content, rating=rating)
@app.route("/rate/<int:content_id>", methods=["POST"])
def rate(content_id):
    if "username" not in session:
        return redirect(url_for("login"))
    user = get_user(session["username"])
    rating = int(request.form["rating"])
    if add_rating(user[0], content_id, rating):
        return redirect(url_for("content", content_id=content_id))
    else:
        return render_template("content.html", content=get_content(content_id), rating=get_rating(user[0], content_id), error="评分失败")
@app.route("/recommendations")
def recommendations():
    if "username" not in session:
        return redirect(url_for("login"))
    user = get_user(session["username"])
    recommended_contents = get_recommendations(user[0])
    return render_template("recommendations.html", recommended_contents=recommended_contents)
if __name__ == "__main__":
    app.run(debug=True)
5.3.8 前端界面

前端界面是系统的用户交互部分。以下是前端界面的实现代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>推荐系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin-top: 50px;
        }
        h1 {
            text-align: center;
            margin-bottom: 20px;
            color: #333;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 10px;
            font-weight: bold;
        }
        .form-group input, .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .form-group input[type="submit"] {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .form-group input[type="submit"]:hover {
            background-color: #45a049;
        }
        .error {
            color: red;
            text-align: center;
            margin-top: 20px;
            font-size: 18px;
            font-weight: bold;
        }
        .content-list {
            list-style: none;
            padding: 0;
        }
        .content-list li {
            margin-bottom: 20px;
            padding: 20px;
            background-color: #f9f9f9;
            border-radius: 5px;
        }
        .content-list li a {
            text-decoration: none;
            color: #333;
            font-weight: bold;
        }
        .content-list li a:hover {
            color: #4CAF50;
        }
        .rating {
            margin-top: 20px;
        }
        .rating input[type="radio"] {
            display: none;
        }
        .rating label {
            display: inline-block;
            width: 20px;
            height: 20px;
            background-color: #ddd;
            border-radius: 50%;
            cursor: pointer;
        }
        .rating input[type="radio"]:checked ~ label {
            background-color: #4CAF50;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>推荐系统</h1>
        <nav>
            <a href="{{ url_for('index') }}">首页</a> |
            <a href="{{ url_for('contents') }}">内容列表</a> |
            <a href="{{ url_for('recommendations') }}">推荐内容</a> |
            <a href="{{ url_for('logout') }}">退出登录</a>
        </nav>
        {% block content %}{% endblock %}
    </div>
</body>
</html>
<!-- login.html -->
{% extends "base.html" %}
{% block content %}
<h2>登录</h2>
<form method="POST" action="{{ url_for('login') }}">
    <div class="form-group">
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username" required>
    </div>
    <div class="form-group">
        <label for="password">密码:</label>
        <input type="password" id="password" name="password" required>
    </div>
    <div class="form-group">
        <input type="submit" value="登录">
    </div>
</form>
{% if error %}
<div class="error">{{ error }}</div>
{% endif %}
<p>还没有账号?<a href="{{ url_for('register') }}">立即注册</a></p>
{% endblock %}
<!-- register.html -->
{% extends "base.html" %}
{% block content %}
<h2>注册</h2>
<form method="POST" action="{{ url_for('register') }}">
    <div class="form-group">
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username" required>
    </div>
    <div class="form-group">
        <label for="password">密码:</label>
        <input type="password" id="password" name="password" required>
    </div>
    <div class="form-group">
        <label for="email">邮箱:</label>
        <input type="email" id="email" name="email" required>
    </div>
    <div class="form-group">
        <input type="submit" value="注册">
    </div>
</form>
{% if error %}
<div class="error">{{ error }}</div>
{% endif %}
<p>已有账号?<a href="{{ url_for('login') }}">立即登录</a></p>
{% endblock %}
<!-- index.html -->
{% extends "base.html" %}
{% block content %}
<h2>欢迎,{{ username }}!</h2>
<p>这是推荐系统的首页。您可以浏览内容列表或查看推荐内容。</p>
{% endblock %}
<!-- contents.html -->
{% extends "base.html" %}
{% block content %}
<h2>内容列表</h2>
<ul class="content-list">
    {% for content in contents %}
    <li>
        <a href="{{ url_for('content', content_id=content[0]) }}">{{ content[1] }}</a>
        <p>{{ content[2] }}</p>
        <p>分类:{{ content[3] }}</p>
    </li>
    {% endfor %}
</ul>
{% endblock %}
<!-- content.html -->
{% extends "base.html" %}
{% block content %}
<h2>{{ content[1] }}</h2>
<p>{{ content[2] }}</p>
<p>分类:{{ content[3] }}</p>
{% if rating %}
<p>您的评分:{{ rating[3] }}</p>
{% else %}
<form method="POST" action="{{ url_for('rate', content_id=content[0]) }}">
    <div class="form-group">
        <label for="rating">评分:</label>
        <div class="rating">
            <input type="radio" id="rating1" name="rating" value="1">
            <label for="rating1"></label>
            <input type="radio" id="rating2" name="rating" value="2">
            <label for="rating2"></label>
            <input type="radio" id="rating3" name="rating" value="3">
            <label for="rating3"></label>
            <input type="radio" id="rating4" name="rating" value="4">
            <label for="rating4"></label>
            <input type="radio" id="rating5" name="rating" value="5">
            <label for="rating5"></label>
        </div>
    </div>
    <div class="form-group">
        <input type="submit" value="评分">
    </div>
</form>
{% endif %}
{% if error %}
<div class="error">{{ error }}</div>
{% endif %}
{% endblock %}
<!-- recommendations.html -->
{% extends "base.html" %}
{% block content %}
<h2>推荐内容</h2>
<ul class="content-list">
    {% for content in recommended_contents %}
    <li>
        <a href="{{ url_for('content', content_id=content[0]) }}">{{ content[1] }}</a>
        <p>{{ content[2] }}</p>
        <p>分类:{{ content[3] }}</p>
    </li>
    {% endfor %}
</ul>
{% endblock %}

5.4 系统运行与测试

5.4.1 系统运行

运行系统时,需要执行以下步骤:

  1. 安装 Flask、Surprise 和 SQLite 库
  2. 运行 main.py 文件
  3. 访问 http://localhost:5000/
  4. 注册新用户或登录已有的用户
  5. 浏览内容列表,对内容进行评分
  6. 查看推荐内容
5.4.2 系统测试

系统测试时,需要使用一些测试数据。以下是一个简单的测试数据示例:

  1. 用户数据

    • 用户名:user1,密码:password1,邮箱:user1@example.com
    • 用户名:user2,密码:password2,邮箱:user2@example.com
  2. 内容数据

    • 标题:机器学习入门,描述:这是一篇关于机器学习的入门文章,分类:机器学习
    • 标题:深度学习入门,描述:这是一篇关于深度学习的入门文章,分类:深度学习
    • 标题:自然语言处理入门,描述:这是一篇关于自然语言处理的入门文章,分类:自然语言处理
    • 标题:计算机视觉入门,描述:这是一篇关于计算机视觉的入门文章,分类:计算机视觉
  3. 评分数据

    • 用户1 对 内容1 评分:5
    • 用户1 对 内容2 评分:4
    • 用户2 对 内容1 评分:3
    • 用户2 对 内容3 评分:5

添加测试数据后,运行系统,查看推荐内容。


六、总结

本章介绍了推荐系统的基本概念、重要性和应用场景,以及推荐系统常用算法(协同过滤、内容推荐、混合推荐)的实现方法。同时,本章还介绍了推荐系统库(Surprise、TensorFlow Recommenders)的基本使用方法,以及推荐系统的评估指标和优化方法。最后,通过实战项目,展示了如何开发一个完整的推荐系统。

推荐系统是一种信息过滤系统,它根据用户的历史行为、兴趣爱好和需求,向用户推荐相关的内容。推荐系统在电商、社交网络、音乐、视频等领域都有广泛的应用。通过学习本章的内容,读者可以掌握推荐系统的基本方法和技巧,具备开发推荐系统的能力。同时,通过实战项目,读者可以将所学知识应用到实际项目中,进一步提升自己的技能水平。

© 版权声明

相关文章