
基于隨機梯度下降的矩陣分解推薦算法
SVD是矩陣分解常用的方法,其原理為:矩陣M可以寫成矩陣A、B與C相乘得到,而B可以與A或者C合并,就變成了兩個元素M1與M2的矩陣相乘可以得到M。
矩陣分解推薦的思想就是基于此,將每個user和item的內(nèi)在feature構(gòu)成的矩陣分別表示為M1與M2,則內(nèi)在feature的乘積得到M;因此我們可以利用已有數(shù)據(jù)(user對item的打分)通過隨機梯度下降的方法計算出現(xiàn)有user和item最可能的feature對應(yīng)到的M1與M2(相當(dāng)于得到每個user和每個item的內(nèi)在屬性),這樣就可以得到通過feature之間的內(nèi)積得到user沒有打過分的item的分數(shù)。
本文所采用的數(shù)據(jù)是movielens中的數(shù)據(jù),且自行切割成了train和test,但是由于數(shù)據(jù)量較大,沒有用到全部數(shù)據(jù)。
代碼如下:
[python] view plain copy
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 9 19:33:00 2017
@author: wjw
"""
import pandas as pd
import numpy as np
import os
def difference(left,right,on): #求兩個dataframe的差集
df = pd.merge(left,right,how='left',on=on) #參數(shù)on指的是用于連接的列索引名稱
left_columns = left.columns
col_y = df.columns[-1] # 得到最后一列
df = df[df[col_y].isnull()]#得到boolean的list
df = df.iloc[:,0:left_columns.size]#得到的數(shù)據(jù)里面還有其他同列名的column
df.columns = left_columns # 重新定義columns
return df
def readfile(filepath): #讀取文件,同時得到訓(xùn)練集和測試集
pwd = os.getcwd()#返回當(dāng)前工程的工作目錄
os.chdir(os.path.dirname(filepath))
#os.path.dirname()獲得filepath文件的目錄;chdir()切換到filepath目錄下
initialData = pd.read_csv(os.path.basename(filepath))
#basename()獲取指定目錄的相對路徑
os.chdir(pwd)#回到先前工作目錄下
predData = initialData.iloc[:,0:3] #將最后一列數(shù)據(jù)去掉
newIndexData = predData.drop_duplicates()
trainData = newIndexData.sample(axis=0,frac = 0.1) #90%的數(shù)據(jù)作為訓(xùn)練集
testData = difference(newIndexData,trainData,['userId','movieId']).sample(axis=0,frac=0.1)
return trainData,testData
def getmodel(train):
slowRate = 0.99
preRmse = 10000000.0
max_iter = 100
features = 3
lamda = 0.2
gama = 0.01 #隨機梯度下降中加入,防止更新過度
user = pd.DataFrame(train.userId.drop_duplicates(),columns=['userId']).reset_index(drop=True) #把在原來dataFrame中的索引重新設(shè)置,drop=True并拋棄
movie = pd.DataFrame(train.movieId.drop_duplicates(),columns=['movieId']).reset_index(drop=True)
userNum = user.count().loc['userId'] #671
movieNum = movie.count().loc['movieId']
userFeatures = np.random.rand(userNum,features) #構(gòu)造user和movie的特征向量集合
movieFeatures = np.random.rand(movieNum,features)
#假設(shè)每個user和每個movie有3個feature
userFeaturesFrame =user.join(pd.DataFrame(userFeatures,columns = ['f1','f2','f3']))
movieFeaturesFrame =movie.join(pd.DataFrame(movieFeatures,columns= ['f1','f2','f3']))
userFeaturesFrame = userFeaturesFrame.set_index('userId')
movieFeaturesFrame = movieFeaturesFrame.set_index('movieId') #重新設(shè)置index
for i in range(max_iter):
rmse = 0
n = 0
for index,row in user.iterrows():
uId = row.userId
userFeature = userFeaturesFrame.loc[uId] #得到userFeatureFrame中對應(yīng)uId的feature
u_m = train[train['userId'] == uId] #找到在train中userId點評過的movieId的data
for index,row in u_m.iterrows():
u_mId = int(row.movieId)
realRating = row.rating
movieFeature = movieFeaturesFrame.loc[u_mId]
eui = realRating-np.dot(userFeature,movieFeature)
rmse += pow(eui,2)
n += 1
userFeaturesFrame.loc[uId] += gama * (eui*movieFeature-lamda*userFeature)
movieFeaturesFrame.loc[u_mId] += gama*(eui*userFeature-lamda*movieFeature)
nowRmse = np.sqrt(rmse*1.0/n)
print('step:%f,rmse:%f'%((i+1),nowRmse))
if nowRmse<preRmse:
preRmse = nowRmse
elif nowRmse<0.5:
break
elif nowRmse-preRmse<=0.001:
break
gama*=slowRate
return userFeaturesFrame,movieFeaturesFrame
def evaluate(userFeaturesFrame,movieFeaturesFrame,test):
test['predictRating']='NAN' # 新增一列
for index,row in test.iterrows():
print(index)
userId = row.userId
movieId = row.movieId
if userId not in userFeaturesFrame.index or movieId not in movieFeaturesFrame.index:
continue
userFeature = userFeaturesFrame.loc[userId]
movieFeature = movieFeaturesFrame.loc[movieId]
test.loc[index,'predictRating'] = np.dot(userFeature,movieFeature) #不定位到不能修改值
return test
if __name__ == "__main__":
filepath = r"E:\學(xué)習(xí)\研究生\推薦系統(tǒng)\ml-latest-small\ratings.csv"
train,test = readfile(filepath)
userFeaturesFrame,movieFeaturesFrame = getmodel(train)
result = evaluate(userFeaturesFrame,movieFeaturesFrame,test)
在test中得到的結(jié)果為:
NAN則是訓(xùn)練集中沒有的數(shù)據(jù)
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
SQL Server 中 CONVERT 函數(shù)的日期轉(zhuǎn)換:從基礎(chǔ)用法到實戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉(zhuǎn)換是高頻需求 —— 無論 ...
2025-09-18MySQL 大表拆分與關(guān)聯(lián)查詢效率:打破 “拆分必慢” 的認知誤區(qū) 在 MySQL 數(shù)據(jù)庫管理中,“大表” 始終是性能優(yōu)化繞不開的話題。 ...
2025-09-18CDA 數(shù)據(jù)分析師:表結(jié)構(gòu)數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結(jié)構(gòu)數(shù)據(jù)(如數(shù)據(jù)庫表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-18DSGE 模型中的 Et:理性預(yù)期算子的內(nèi)涵、作用與應(yīng)用解析 動態(tài)隨機一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結(jié)構(gòu)數(shù)據(jù)特征價值的專業(yè)核心 表結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲的結(jié)構(gòu)化數(shù)據(jù),如數(shù)據(jù)庫表、Excel 表、 ...
2025-09-17Excel 導(dǎo)入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實戰(zhàn)應(yīng)用 在用 Python(如 pandas 庫)處理 Excel 數(shù)據(jù)時,“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗與 t 檢驗:差異、適用場景與實踐應(yīng)用 在數(shù)據(jù)分析與統(tǒng)計學(xué)領(lǐng)域,假設(shè)檢驗是驗證研究假設(shè)、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結(jié)構(gòu)數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 存儲的結(jié)構(gòu)化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計劃中 rows 數(shù)量的準(zhǔn)確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對象的 text 與 content:區(qū)別、場景與實踐指南 在 Python 進行 HTTP 網(wǎng)絡(luò)請求開發(fā)時(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結(jié)構(gòu)數(shù)據(jù)價值的核心操盤手 表格結(jié)構(gòu)數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫表)是企業(yè)最基礎(chǔ)、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請求工具對比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長浮點數(shù)據(jù)的科學(xué)計數(shù)法問題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長浮點數(shù)據(jù)時的科學(xué)計數(shù)法問題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務(wù)數(shù)據(jù)分析步驟的落地者與價值優(yōu)化者 業(yè)務(wù)數(shù)據(jù)分析是企業(yè)解決日常運營問題、提升執(zhí)行效率的核心手段,其價值 ...
2025-09-12用 SQL 驗證業(yè)務(wù)邏輯:從規(guī)則拆解到數(shù)據(jù)把關(guān)的實戰(zhàn)指南 在業(yè)務(wù)系統(tǒng)落地過程中,“業(yè)務(wù)邏輯” 是連接 “需求設(shè)計” 與 “用戶體驗 ...
2025-09-11塔吉特百貨孕婦營銷案例:數(shù)據(jù)驅(qū)動下的精準(zhǔn)零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當(dāng)下,精準(zhǔn)營銷成為企業(yè)突圍的核心方 ...
2025-09-11CDA 數(shù)據(jù)分析師與戰(zhàn)略 / 業(yè)務(wù)數(shù)據(jù)分析:概念辨析與協(xié)同價值 在數(shù)據(jù)驅(qū)動決策的體系中,“戰(zhàn)略數(shù)據(jù)分析”“業(yè)務(wù)數(shù)據(jù)分析” 是企業(yè) ...
2025-09-11Excel 數(shù)據(jù)聚類分析:從操作實踐到業(yè)務(wù)價值挖掘 在數(shù)據(jù)分析場景中,聚類分析作為 “無監(jiān)督分組” 的核心工具,能從雜亂數(shù)據(jù)中挖 ...
2025-09-10統(tǒng)計模型的核心目的:從數(shù)據(jù)解讀到?jīng)Q策支撐的價值導(dǎo)向 統(tǒng)計模型作為數(shù)據(jù)分析的核心工具,并非簡單的 “公式堆砌”,而是圍繞特定 ...
2025-09-10