
基于隨機(jī)梯度下降的矩陣分解推薦算法
SVD是矩陣分解常用的方法,其原理為:矩陣M可以寫成矩陣A、B與C相乘得到,而B可以與A或者C合并,就變成了兩個(gè)元素M1與M2的矩陣相乘可以得到M。
矩陣分解推薦的思想就是基于此,將每個(gè)user和item的內(nèi)在feature構(gòu)成的矩陣分別表示為M1與M2,則內(nèi)在feature的乘積得到M;因此我們可以利用已有數(shù)據(jù)(user對(duì)item的打分)通過隨機(jī)梯度下降的方法計(jì)算出現(xiàn)有user和item最可能的feature對(duì)應(yīng)到的M1與M2(相當(dāng)于得到每個(gè)user和每個(gè)item的內(nèi)在屬性),這樣就可以得到通過feature之間的內(nèi)積得到user沒有打過分的item的分?jǐn)?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): #求兩個(gè)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): #讀取文件,同時(shí)得到訓(xùn)練集和測(cè)試集
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()獲取指定目錄的相對(duì)路徑
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 #隨機(jī)梯度下降中加入,防止更新過度
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è)每個(gè)user和每個(gè)movie有3個(gè)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中對(duì)應(yīng)uId的feature
u_m = train[train['userId'] == uId] #找到在train中userId點(diǎn)評(píng)過的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ù)分析咨詢請(qǐng)掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報(bào)考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計(jì)的實(shí)用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強(qiáng)大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實(shí)施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價(jià)值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡(jiǎn)稱 BI)深度融合的時(shí)代,BI ...
2025-07-10SQL 在預(yù)測(cè)分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢(shì)預(yù)判? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代,預(yù)測(cè)分析作為挖掘數(shù)據(jù)潛在價(jià)值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價(jià)值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點(diǎn),而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報(bào)考到取證的全攻略? 在數(shù)字經(jīng)濟(jì)蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭(zhēng)搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢(shì)性檢驗(yàn):捕捉數(shù)據(jù)背后的時(shí)間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢(shì)性檢驗(yàn)如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時(shí)間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時(shí)間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實(shí)戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗(yàn):數(shù)據(jù)趨勢(shì)與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢(shì)變化以及識(shí)別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對(duì)策略? 長短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨(dú)特的門控機(jī)制,在 ...
2025-07-07統(tǒng)計(jì)學(xué)方法在市場(chǎng)調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場(chǎng)調(diào)研是企業(yè)洞察市場(chǎng)動(dòng)態(tài)、了解消費(fèi)者需求的重要途徑,而統(tǒng)計(jì)學(xué)方法則是市場(chǎng)調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動(dòng)力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動(dòng)力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價(jià)值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03