天天看點

搭建推薦系統,掌握機器學習

說明

大多數推薦系統學習,要麼講解算法,要麼講解理論。

這裡,我們結合python和pgsql資料庫,從0開始搭建一個電影推薦系統。

資料庫操作(pgsql)

建立一個資料庫使用者,用于管理推薦系統相關資料庫對象

create user hrjlk_recomm with password '123456';
           

建立表空間,用于存儲推薦系統相關的資料

create tablespace ts_recomm_data owner hrjlk_recomm location '/Users/../data_ts/ts_recomm_data';
           

建立電影推薦的資料庫

create database db_movies owner hrjlk_recomm tablespace ts_recomm_data encoding utf8;
           

退出目前使用者

\q
           

切換推薦系統的資料庫使用者重新登入

psql -h localhost -U hrjlk_recomm -d db_movies
           

建立表,儲存使用者對電影的評分資料

create table user_move_ratings (  
ratingId          serial           not null primary key
,userId           int              not null
,moveId           int              not null
,ratingVal        decimal(2,1)     not null
,created_at       varchar(16)      not null
);
comment on table user_move_ratings is '使用者電影評分記錄';
comment on column user_move_ratings.ratingId is '評分記錄ID';
comment on column user_move_ratings.userId is '使用者ID';
comment on column user_move_ratings.moveId is '電影ID';
comment on column user_move_ratings.ratingVal is '使用者對電影的評分';
comment on column user_move_ratings.created_at is '資料建立時間';
           

導入資料,我用的是Posticon工具,總計20000263行。

資料檔案擷取,關注公衆号“自然語言酷”,背景發送表名,客服每天統一回複網盤位址

python項目

環境(python3.6以上)

需要各位自行安裝

py-postgresql

pip install py-postgresql

配置

建立目錄hrjlk-recomm,并建立下一級目錄

src

src

下建立目錄

conf

conf

目錄下,建立

conf.ini

檔案

用于儲存相關配置

[HRJLK-DB-MOVIE]
USER = hrjlk_recomm
PASSWORD = 123456
HOST = 127.0.0.1
PORT = 5432
DATABASE = db_movies
           

conf

目錄下,建立

sql.ini

檔案

sql語句的配置檔案

[RATING]
GET_USER_MOVIE_RATING = select ratingVal from user_movie_ratings where userId={user_id} and moveId={move_id};
           

Utils

src下,建立目錄

utils

建立python檔案,dbHandle.py,資料庫操作的工具類

# -*- coding:utf-8 -*-

import os
import postgresql.driver as pg_driver
import configparser


class DBHandle:
    # 配置檔案的路徑
    __configPath = '../../conf/conf.ini'
    # 聲明一個配置檔案Reader
    confReader = None

    def __init__(self,dbName):
        if os.path.exists(self.__configPath):
            confReader = configparser.ConfigParser()
            confReader.read(self.__configPath)
        else:
            raise IOError("config file path is:'" + self.__configPath + "'not found")
        # 初始化資料庫連接配接
        self.dbConn = pg_driver.connect(user=confReader.get(dbName, 'USER')
                                   , password=confReader.get(dbName, 'PASSWORD')
                                   , host=confReader.get(dbName, 'HOST')
                                   , port=confReader.get(dbName, 'PORT')
                                   , database=confReader.get(dbName, 'DATABASE')
                                   )

    # 執行查詢,隻取第一行,實作查詢一行的功能
    def executeQueryFirst(self, sqlText):
        firstQuery = self.dbConn.prepare(sqlText)
        return firstQuery.first()
    
    # 執行查詢
    def executeQuery(self,sqlText):
        queryPrepare = self.dbConn.prepare(sqlText)
        return queryPrepare

    # 執行插入資料,清單形式批量插入
    def executeInsertLoad(self, sqlText, listLines):
        insertQuery = self.dbConn.prepare(sqlText)
        insertReturn = insertQuery.load_rows(listLines)

    # 将查詢結果插入目标表
    def executeInsertSql(self,sqlText):
        insertResult = self.dbConn.execute(sqlText)

    # Truncate table
    def executeTruncate(self,tableName):
        _sqlTruncae = 'truncate table %s' % (tableName)
        self.dbConn.execute(_sqlTruncae)

    # 删除當日資料
    def executeDelDateData(self,tableName,dataDate):
        _sqlDel = "delete from %s where data_date = '%s'" % (tableName,dataDate)
        self.dbConn.execute(_sqlDel)

    # 關閉資料庫連接配接
    def closeDBConnection(self):
        if self.dbConn:
            self.dbConn.close()
           

建立python檔案,DataUtil.py,配置類

class DataConfig:
    sqlFilePath = '../../conf/sqls.ini'
    dbNameRecomm = 'HRJLK-DB-MOVIE'
           

建立python檔案,fileUtil.py,檔案操作的工具類

# -*- coding:utf-8 -*-
import configparser
import os


class confReader:
    """
    讀取配置檔案,适用于單次讀取
    """

    def __init__():
        pass

    '''
    讀取ini配置檔案中值的工具方法
    '''
    @staticmethod
    def readConfvalue(confFilePath,sectionName,keyName):
        if os.path.exists(confFilePath):
            confReader = configparser.ConfigParser()
            confReader.read(confFilePath)
            confVal = confReader.get(sectionName, keyName)
            return confVal
        else:
            raise IOError("config file path is:'" + confFilePath + "'not found")
           

執行檔案

src

下建立目錄

executer

,并建立python檔案

test.py

這裡完成第一步,也是最基本的功能,根據使用者ID和電影ID,查出使用者對該電影的評分

# -*- coding:utf-8 -*-
import sys
sys.path.append('../utils')

from dbHandle import DBHandle
from dataUtil import DataConfig
from fileUtil import ConfReader

# 從配置檔案中讀取sql内容
__sqlModelName = 'RATING'
sqlContent = ConfReader.readConfvalue(DataConfig.sqlFilePath,__sqlModelName,'GET_USER_MOVIE_RATING')
# 建立資料庫連接配接
dbConn = DBHandle(DataConfig.dbNameRecomm)

dbResultUserMoveRating = dbConn.executeQuery(sqlContent.format(user_id = sys.argv[1],move_id = sys.argv[2]))
print(dbResultUserMoveRating.first())

# 關閉連接配接
dbConn.closeDBConnection()
           

在指令行執行

python test.py 1 2
           

關注公衆号“自然語言酷”,每周更新,大資料架構師進步之路。