1. 程式人生 > >在MovieLens資料集上用SVD進行評分預測【修正後】

在MovieLens資料集上用SVD進行評分預測【修正後】

參考了Yehuda Koren 08年的論文Factorization Meets the Neighborhood: a Multifaceted Collaborative Filtering Model

程式碼如下:

# -*- coding: UTF-8 -*-
import random
import math
import cPickle as pickle

class SVD():
    def __init__(self,allfile,trainfile,testfile,factorNum=10):
        #all data file
self.allfile=allfile
        #training set file
self.trainfile=trainfile #testing set file self.testfile=testfile #get factor number self.factorNum=factorNum #get user number self.userNum=self.getUserNum() #get item number self.itemNum=self.getItemNum() #learning rate self.learningRate=0.01 #the regularization lamba
self.regularization=0.05 #initialize the model and parameters self.initModel() #get user number function def getUserNum(self): file=self.allfile cnt=0 userSet=set() for line in open(file): user=line.split('\t')[0].strip() if
user not in userSet: userSet.add(user) cnt+=1 return cnt #get item number function def getItemNum(self): file=self.allfile cnt=0 itemSet=set() for line in open(file): item=line.split('\t')[1].strip() if item not in itemSet: itemSet.add(item) cnt+=1 return cnt #initialize all parameters def initModel(self): self.av=self.average(self.trainfile) self.bu=[0.0 for i in range(self.userNum)] self.bi=[0.0 for i in range(self.itemNum)] temp=math.sqrt(self.factorNum) self.pu=[[(0.1*random.random()/temp) for i in range(self.factorNum)] for j in range(self.userNum)] self.qi=[[0.1*random.random()/temp for i in range(self.factorNum)] for j in range(self.itemNum)] print "Initialize end.The user number is:%d,item number is:%d,the average score is:%f" %(self.userNum,self.itemNum,self.av) #train model def train(self,iterTimes=100): print "Beginning to train the model......" trainfile=self.trainfile preRmse=10000.0 for iter in range(iterTimes): fi=open(trainfile,'r') #read the training file for line in fi: content=line.split('\t') user=int(content[0].strip())-1 item=int(content[1].strip())-1 rating=float(content[2].strip()) #calculate the predict score pscore=self.predictScore(self.av,self.bu[user],self.bi[item],self.pu[user],self.qi[item]) #the delta between the real score and the predict score eui=rating-pscore #update parameter bu and bi(user rating bias and item rating bias) self.bu[user]+=self.learningRate*(eui-self.regularization*self.bu[user]) self.bi[item]+=self.learningRate*(eui-self.regularization*self.bi[item]) for k in range(self.factorNum): temp=self.pu[user][k] #update pu,qi self.pu[user][k]+=self.learningRate*(eui*self.qi[item][k]-self.regularization*self.pu[user][k]) self.qi[item][k]+=self.learningRate*(eui*temp-self.regularization*self.qi[item][k]) #print pscore,eui #close the file fi.close() #calculate the current rmse curRmse=self.test(self.av,self.bu,self.bi,self.pu,self.qi)[0] curMae=self.test(self.av,self.bu,self.bi,self.pu,self.qi)[1] print "Iteration %d times,RMSE is : %f,MAE is : %f" %(iter+1,curRmse,curMae) if curRmse>preRmse: break else: preRmse=curRmse print "Iteration finished!" #test on the test set and calculate the RMSE def test(self,av,bu,bi,pu,qi): testfile=self.testfile rmse=0.0 mae=0.0 cnt=0 fi=open(testfile) for line in fi: cnt+=1 content=line.split('\t') user=int(content[0].strip())-1 item=int(content[1].strip())-1 score=float(content[2].strip()) pscore=self.predictScore(av,bu[user],bi[item],pu[user],qi[item]) rmse+=math.pow(score-pscore,2) mae+=abs(score-pscore) fi.close() return math.sqrt(rmse/cnt),mae/cnt #calculate the average rating in the training set def average(self,filename): result=0.0 cnt=0 for line in open(filename): cnt+=1 score=float(line.split('\t')[2].strip()) result+=score return result/cnt #calculate the inner product of two vectors def innerProduct(self,v1,v2): result=0.0 for i in range(len(v1)): result+=v1[i]*v2[i] return result def predictScore(self,av,bu,bi,pu,qi): pscore=av+bu+bi+self.innerProduct(pu,qi) if pscore<1: pscore=1 if pscore>5: pscore=5 return pscore if __name__=='__main__': s=SVD("data\\u.data","data\\ua.base","data\\ua.test") #print s.userNum,s.itemNum #print s.average("data\\ua.base") s.train()

實驗結果如下:

Initialize end.The user number is:943,item number is:1682,the average score is:3.523827
Beginning to train the model......
Iteration 1 times,RMSE is : 1.002799,MAE is : 0.807791
Iteration 2 times,RMSE is : 0.982096,MAE is : 0.783726
Iteration 3 times,RMSE is : 0.972882,MAE is : 0.774163
Iteration 4 times,RMSE is : 0.967721,MAE is : 0.769057
Iteration 5 times,RMSE is : 0.964556,MAE is : 0.765856
Iteration 6 times,RMSE is : 0.962501,MAE is : 0.763699
Iteration 7 times,RMSE is : 0.961121,MAE is : 0.762131
Iteration 8 times,RMSE is : 0.960174,MAE is : 0.760974
Iteration 9 times,RMSE is : 0.959496,MAE is : 0.760075
Iteration 10 times,RMSE is : 0.958957,MAE is : 0.759327
Iteration 11 times,RMSE is : 0.958456,MAE is : 0.758648
Iteration 12 times,RMSE is : 0.957879,MAE is : 0.757935
Iteration 13 times,RMSE is : 0.957088,MAE is : 0.757073
Iteration 14 times,RMSE is : 0.955944,MAE is : 0.755947
Iteration 15 times,RMSE is : 0.954353,MAE is : 0.754484
Iteration 16 times,RMSE is : 0.952345,MAE is : 0.752735
Iteration 17 times,RMSE is : 0.950108,MAE is : 0.750828
Iteration 18 times,RMSE is : 0.947883,MAE is : 0.748934
Iteration 19 times,RMSE is : 0.945824,MAE is : 0.747158
Iteration 20 times,RMSE is : 0.943971,MAE is : 0.745539
Iteration 21 times,RMSE is : 0.942294,MAE is : 0.744083
Iteration 22 times,RMSE is : 0.940736,MAE is : 0.742716
Iteration 23 times,RMSE is : 0.939252,MAE is : 0.741392
Iteration 24 times,RMSE is : 0.937806,MAE is : 0.740099
Iteration 25 times,RMSE is : 0.936384,MAE is : 0.738842
Iteration 26 times,RMSE is : 0.934983,MAE is : 0.737613
Iteration 27 times,RMSE is : 0.933612,MAE is : 0.736412
Iteration 28 times,RMSE is : 0.932294,MAE is : 0.735245
Iteration 29 times,RMSE is : 0.931057,MAE is : 0.734105
Iteration 30 times,RMSE is : 0.929926,MAE is : 0.733049
Iteration 31 times,RMSE is : 0.928929,MAE is : 0.732111
Iteration 32 times,RMSE is : 0.928082,MAE is : 0.731301
Iteration 33 times,RMSE is : 0.927391,MAE is : 0.730614
Iteration 34 times,RMSE is : 0.926858,MAE is : 0.730037
Iteration 35 times,RMSE is : 0.926480,MAE is : 0.729576
Iteration 36 times,RMSE is : 0.926256,MAE is : 0.729231
Iteration 37 times,RMSE is : 0.926174,MAE is : 0.728978
Iteration 38 times,RMSE is : 0.926232,MAE is : 0.728840
Iteration finished!

最後的RMSE是0.926左右,MAE是0.728左右,可見效果一般,後面會嘗試改進。

相關推薦

MovieLens資料SVD進行評分預測修正

參考了Yehuda Koren 08年的論文Factorization Meets the Neighborhood: a Multifaceted Collaborative Filtering Model程式碼如下:# -*- coding: UTF-8 -*- impo

MovieLens資料SVD進行評分預測

參考了Yehuda Koren 08年的論文Factorization Meets the Neighborhood: a Multifaceted Collaborative Filtering Model 程式碼如下: ''' Version:1.0 Created

PTB資料迴圈神經網路實現語言建模

一:PTB文字資料集是語言模型學習中目前最廣泛的資料集,tensorflow對ptb資料集是支援的,首先要下載資料集http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz,資料集中我們只需要利用data中的pt

《Spark機器學習》筆記——基於MovieLens資料使用Spark進行電影資料分析

1、資料集下載https://grouplens.org/datasets/movielens2、資料集下檔案格式u.user使用者屬性檔案包含user.id使用者ID    gender性別   occupation職業    ZIP code郵編等屬性,每個屬性之間用|分

ML之迴歸預測之Lasso:利用Lasso演算法解決迴歸(實數值評分預測)問題—在完整資料訓練Lasso模型

ML之迴歸預測之Lasso:利用Lasso演算法解決迴歸(實數值評分預測)問題—在完整資料集上訓練Lasso模型   輸出結果 設計思路   核心程式碼 t=3 if t==1: X = numpy.array(xList

MovieLens資料做推薦(Python推薦系統二)

              思路:下載MovieLens的資料集,對資料集進行函式定義,定義各資料列的名稱,根據上一篇Python寫出簡單的推薦系統(一) 文中的recommendations.py 的使用者相似度進行推薦。               下載MovieLe

DPM(Deformable Part Model,voc-release3.1)演算法在INRIA資料訓練自己的人體檢測模型

我的環境 DPM原始碼版本:voc-release3.1 VOC開發包版本:VOC2007_devkit_08-Jun Matlab版本:MatlabR2012b c++編譯器:VS2010 系統:Win7 32位 learn.exe迭代次數:5萬次 資料集

pandas探索Movielens資料

本文為譯文,原文連結: Let’s begin 1.資料集情況, # u.user檔案中為user_id,age,occupation,zip_code,格式如下: # u.data檔案

tensorflow 學習專欄(四):使用tensorflow在mnist資料使用邏輯迴歸logistic Regression進行分類

在面對分類問題時,我們常用的一個演算法便是邏輯迴歸(logistic Regression)在本次實驗中,我們的實驗物件是mnist手寫資料集,在該資料集中每張影象包含28*28個畫素點如下圖所示:我們使用邏輯迴歸演算法來對mnist資料集的資料進行分類,判斷影象所表示的數字

BWA0.7+Samtools1.5+GATK4.0在小資料的試驗

試驗資料 chr14_1.fastq chr14_2.fastq (1.47G each one .gz) chr14.fasta (28M .gz) chr14.fastq檔案可以在GAGE下載 chr14.fasta檔案可以在UCSC下載 軟體的版本: bwa-0.7.

BWA0.7+Samtools1.5+GATK4.0在大資料的試驗

試驗資料 fasta:hg38.fa檔案可以在UCSC下載 (hg38.fa.gz 938M) fastq非公開檔案 KY18011403DNA_DHG18153-V_AHHVVHCCXY_L7_1.fq 35G KY18011403DNA_DHG18153-V_AHHVVHCCX

ArcGIS|空間分析|網路分析10 在網路資料配置實時流量

文章目錄 要求 步驟 1 建立儲存實時流量檔案(DTF 檔案)的資料夾 2 建立網路資料集 *3 配置時區屬性 4 構建網路資料集 *5 實時流量源 獲取資料提供商帳戶 開啟模型工具

Pytorch 神經網路—自定義資料實現

第一步、匯入需要的包 import os import scipy.io as sio import numpy as np import torch import torch.nn as nn import torch.backends.cudnn as cudnn im

機器學習筆記 perceptron(感知機) 在ex4Data資料的實現

慣例的ML課堂作業,第四個也是最後一個線性分類模型,感知機。 感知機是一個非常簡單的線性分類模型,簡單來說就是一個神經元,其啟用函式是門限函式,有n個輸入和一個輸出,和神經元結構十分相似。 感知機的損失函式是看作是分類錯的所有樣本的輸出值的和 hw的輸出就是

機器學習(6) MovieLens資料

MovieLens資料集是一個關於電影評分的資料集,裡面包含了從IMDB, The Movie DataBase上面得到的使用者對電影的評分資訊,詳細請看下面的介紹。 介紹: links.csv: 檔案裡面的內容是幫助你如何通過網站id在對應網站上找到對應的電影連結的。資料格式如下:  m

Ubuntu 16.04下利用tf-faster-rcnn在VOC或其他資料訓練自己的模型

暑期的時候有朋友問我如何配置tf-faster-rcnn,那會簡單寫了個steps.pdf。正好最近閒了下來,就把它彙總一下。 Introduction 這是一篇介紹如何使用tf-faster-rcnn在VOC和其他資料集訓練自己模型的筆記. 筆記中所有檔案的地

基於keras的YOLOv3在VOC資料訓練測試

一、編譯環境 windows7 Anaconda+python3.6+keras+tensroflow+pyCharm 二、步驟 測試 從上文第二個github上下載工程,並用

LSTM在MNIST手寫資料做分類(程式碼中尺寸變換細節)

RNN和LSTM學了有一段時間了,主要都是看部落格瞭解原理,最近在研究SLSTM,在對SLSTM進行實現的時候遇到了困難,想說先比較一下二者的理論實現,這才發現自己對於LSTM內部的輸入輸出格式、輸出細節等等都不是非常清楚,藉此機會梳理一下,供後續研究使用。 下面程式碼來自

SciKit-Learn學習筆記2:kNN分類/迴歸,在糖尿病資料的表現

學習《scikit-learn機器學習》時的一些實踐。 kNN分類 在三個點周圍生成聚類樣本,然後做的kNN分類。 這種把標準差取得好(不要太小),得到的就不一定是線性可分的資料了。比如圖上右側有個玫紅點和藍點交錯。 from sklearn.datasets.sa

tensorflow MNIST資料簡單的MLP網路

一、code import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data'