【番剧推荐系统设计】基于 Flask 与 MySQL 实现番剧推荐系统(Python代码)(2)

    xiaoxiao2022-07-14  162

    推荐系统的实现

    一、实验简介

    1.1 实验介绍

    本节实验我们将在上一节实验的基础上实现推荐系统的核心部分。

    1.2 知识点

    本节实验中我们将学习并实践下列知识点:

    Jinja2模板引擎的使用http请求的处理复杂sql查询的使用简单的推荐算法

    二、基础知识

    路由: Flask 支持用 route() 装饰器把一个函数绑定到对应的 URL 上,从而实现路由功能。

    如下图代码所示,实现了 URL /hello 和 / 两个地址的访问请求处理:

    from flask import Flask app=Flask(__name__) @app.route('/') def index(): return "hello" if __name__=="__main__":

    二、简单推荐算法实现

    本节实验中我们实现的推荐算法比较简单,基本思路:

    找到用户所喜爱的番剧;分析这些番剧的类别(一个番剧可能有多个标签),进行统计排序;找到前三个标签,从数据库中找到同时具有这三个标签的番剧(喜欢的不能再推荐);将番剧相关信息(name,brief)进行展示。 SQL 数据库操作的实现上述的思路1 和 思路2: #下面代码实现得到用户所喜欢top3类型 sql='''select style_id from (select user_id,style_id from (select user_id,anime_id as id from user_anime where user_id=%s) as s natural join anime natural join (select anime_id as id,style_id from anime_style) as n )as temp group by style_id order by count(user_id) desc limit 3;'''%user

    其中下图所划去的一行内容对应思路1,即从 user_anime 表中查询用户和喜欢的番剧数据对:

    (select user_id,anime_id as id from user_anime where user_id=%s) as s

    剩下的两个 select 操作由以下代码共同完成:

    #建立三个类别番剧的set(集合),并取交集,即得到同时有三个类型标签的番剧 s=set(anime[str(lis[0])])&set(anime[str(lis[1])])&set(anime[str(lis[2])]) #建立用户喜欢番剧的集合 loveSet=set(love) #如果系统得到的所有番剧用户均已看过了即loveSet>s,就从Top1类型即最喜欢的类型中挑选一个 #这里我们默认数据库量够大,即用户没有把一个类别的所有番剧看完 if loveSet>s: s=set(anime[str(lis[0])]) #把集合转化为列表以待随机函数的使用 set_lis=[] for i in s: set_lis.append(i) #从结果中随机挑选 recommend=choice(set_lis) #直至挑选到用户没看过的 while recommend in love: recommend=choice(set_lis)

    上图中的红线部分较重要,其中第二个红线部分用了 Python 的 Set 数据结构以取交集。love 是喜欢番剧的列表,choice() 函数是随机取一个。while 循环中保证不取与喜欢的重复的,这里还考虑一个问题,就是你得到的交集是喜欢集合的子集,如果不加判断将会导致死循环,所以这种情况拿出来判断,如果出现这种情况就从用户最喜欢类别中拿出一个番剧。

    完整代码实现在 recommend.py 文件中,代码如下:

    # -*- coding: utf-8 -*- """ Created on Thu Aug 25 18:47:40 2016 @author: Albert """ from random import choice import MySQLdb def recommend(user): #连接数据库 DB=MySQLdb.connect("localhost","root","1234","recommend") #获得数据库游标 c=DB.cursor() #下面代码为实现从数据库中得到用户user所喜欢的番剧编号,以便判断重复 love=[] #sql语句 sql="select anime_id from user_anime where user_id=%s"%user c.execute(sql) #得到结果集 results=c.fetchall()#得到的数据数组赋给results for line in results: love.append(line[0])#得到字典赋给新的数组存放 #下面代码实现得到用户所喜欢top3类型 sql=''' select style_id from (select user_id,style_id from (select user_id,anime_id as id from user_anime where user_id=%s) as s natural join anime natural join (select anime_id as id,style_id from anime_style) as n )as temp group by style_id order by count(user_id) desc limit 3;'''%user c.execute(sql) results=c.fetchall() lis=[] anime={} for (line,) in results: lis.append(line) for i in lis: #从番剧信息的数据库中得到Top3各个类别的所有番剧并存入anime字典中 sql="select anime_id from anime_style where style_id="+str(i)+";" c.execute(sql) results=c.fetchall() anime_lis=[] for result in results: anime_lis.append(result[0]) #类型为key,值为存放番剧数据的列表 anime[str(i)]=anime_lis #建立三个类别番剧的set(集合),并取交集,即得到同时有三个类型标签的番剧 s=set(anime[str(lis[0])])&set(anime[str(lis[1])])&set(anime[str(lis[2])]) #建立用户喜欢番剧的集合 loveSet=set(love) #如果系统得到的所有番剧用户均已看过了即loveSet>s,就从Top1类型即最喜欢的类型中挑选一个 #这里我们默认数据库量够大,即用户没有把一个类别的所有番剧看完 if loveSet>s: s=set(anime[str(lis[0])]) #把集合转化为列表以待随机函数的使用 set_lis=[] for i in s: set_lis.append(i) #从结果中随机挑选 recommend=choice(set_lis) #直至挑选到用户没看过的 while recommend in love: recommend=choice(set_lis) dic={} #得到推荐番剧的相关信息,返回以待使用,显示 sql="select name,brief from anime where id="+str(recommend)+";" c.execute(sql) results=c.fetchall() dic['name']=results[0][0] dic['brief']=results[0][1] DB.close() return dic

    四、推荐系统的实现及部署

    4.1 app.py 的实现

    系统运行的启动我们使用 Flask 实现在 app.py 文件中,详细代码:

    # -*- coding: utf-8 -*- from flask import Flask,render_template,request import recommend#同文件下导入 app=Flask(__name__) @app.route('/')#表示传递一个网站,“/”是网站的主目录,也就是http://127.0.0.1:5000/ def index(): return render_template('index.html') @app.route('/search/') def search(): #request为全局变量可得到用户输入信息 n=request.args.get('user') #调用推荐函数 dic=recommend.recommend(n)#recommend下使用推荐算法 #用返回结果进行模板渲染 return render_template('search.html',Data=dic) if __name__=="__main__": app.run(debug=True)

    其中,render_template 为模板渲染函数,第一个参数为模板,第二个为要传的数据。

    4.2 模板文件实现

    其中模板文件 index.html 和 search.html 都在 templates 文件夹中(这是 Flask 默认设置的)。templates文件夹在项目工程中。如图: index.html 页面提供进入系统的首页,及查询输入的数据框,实现代码:

    <!doctype html> </html> <head><title>Recommend</title> <style type="text/css"> #body{ text-align:center; } #content{ margin-left:25%; } </style> </head> <body> <div id="body"> <br/><br/><br/><br/><br/><!--<br/>表示空格--> <br/><br/><br/><br/><br/> <form name="input" action="/search/" method="get"> <br/><br/> User Number: <input type="text" name="user" /> <input type="submit" value="Search" /> </form> </body> </div> </html>

    search.html 页面提供输出结果,实现代码:

    <!doctype html> </html> <head><title>Recommend</title> <style type="text/css"> .videoshow{ border-bottom:5px solid #EFEFEF; padding:20px 10% 20px 20px; margin:30px 25% 30px 5%; } #body{ text-align:center; } #content{ margin-left:25%; } </style> </head> <body> <div id="body"> <form name="input" action="/search/" method="get"> <br/><br/> User Number: <input type="text" name="user" /> <input type="submit" value="Search" /> </form> <br/><br/> <div id="content"> <div class="videoshow"> <p class="title">{{Data['name']}}</p> <p class="Introduction">{{Data['brief']}}</p> </div> </div> </div> </body> </html>

    现在就完成了整个系统的构建和编码。

    4.3 测试启动

    在spyder软件,运行 app.py 后,,打开浏览器访问 localhost:5000,你会进入 index.html 界面。 输入用户编号1 点击 search 按钮后,你将会进入 search 界面: 解释一下界面内容,a为推荐番剧的名称,A为推荐番剧的简介。至此,我们的简单推荐系统完成。

    五、总结

    本次实验我们用 Flask 框架和 Mysql 数据库完成了简单的番剧推荐系统。最后成功为我们输入的用户推荐了一个没有看过的番剧,并通过网页显示出来。相信大家通过此,不仅了解到 Flask 使用和数据库的使用,还懂得推荐系统的基本原理。大家可以对推荐算法进行进一步的优化,以有更好的效果。

    最新回复(0)