機器學習演算法 11 推薦系統實戰

2021-08-27 16:01:42 字數 2801 閱讀 1652

from numpy import *

from numpy import linalg as la

# 載入資料 (使用者-菜餚矩陣)

# 行為 使用者, 列為希餚, 表示使用者對某個菜餚的評分

def loadexdata2():

return[[0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 5],

[0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 3],

[0, 0, 0, 0, 4, 0, 0, 1, 0, 4, 0],

[3, 3, 4, 0, 0, 0, 0, 2, 2, 0, 0],

[5, 4, 5, 0, 0, 0, 0, 5, 5, 0, 0],

[0, 0, 0, 0, 5, 0, 1, 0, 0, 5, 0],

[4, 3, 4, 0, 0, 0, 0, 5, 5, 0, 1],

[0, 0, 0, 4, 0, 4, 0, 0, 0, 0, 4],

[0, 0, 0, 2, 0, 2, 5, 0, 0, 1, 2],

[0, 0, 0, 0, 5, 0, 0, 0, 0, 4, 0],

[1, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0]]

# 計算兩個評分的歐氏距離

def esclidsim(ina,inb):

if len(ina)<3:

return 1.0

return 1.0/(1.0+la.norm(ina-inb))

# 計算兩個評分的 皮爾遜相關係數 (pearson correlation)

def pearssim(ina,inb):

if len(ina)<3:

return 1.0

return 0.5+0.5*corrcoef(ina.inb)[0][1]

# 計算兩個評分的余弦相似度 (cosine similarity)

def cossim(ina,inb):

num = float(ina.t*inb)

denom = la.norm(ina)*la.norm(inb)

return 0.5+0.5*(num/denom)

# 基於物品的相似度推薦

def standest(datamat,user,sinmeas,item):

n = shape(datamat)[1]

simtotal = 0.0;ratsimtotal = 0.0

for j in range(n):

userrating = datamat[user,j]

if userrating ==0:

continue

overlap = nonzero(logical_and(datamat[:,item].a>0,datamat[:,j].a>0))[0]

if len(overlap)==0:

simility =0

else:

simility = sinmeas(datamat[overlap,item],datamat[overlap,j])

print("the %d and %d similit is :%f"%(item,j,simility))

simtotal +=simility

ratsimtotal+=simility*userrating

if simtotal == 0:

return 0

else:

return ratsimtotal/simtotal

def recommand(datamat,user,n=3,simmeans=cossim,estmethod =standest):

unrateditems = nonzero(datamat[user,:].a==0)[1]

if len(unrateditems)==0:

return "you rated everything"

itemscores =

for item in unrateditems:

estimatscore = estmethod(datamat,user,simmeans,item)

return sorted(itemscores,key = lambda jj:jj[1],reverse=true)[:n]

mymat = mat(loadexdata2())

print(recommand(mymat, 1))

執行結果:

the 0 and 10 similit is :1.000000

the 1 and 10 similit is :1.000000

the 2 and 10 similit is :1.000000

the 6 and 3 similit is :1.000000

the 6 and 5 similit is :1.000000

the 6 and 10 similit is :1.000000

the 7 and 10 similit is :1.000000

the 8 and 10 similit is :1.000000

the 9 and 3 similit is :1.000000

the 9 and 5 similit is :1.000000

the 9 and 10 similit is :1.000000

[(6, 3.3333333333333335), (9, 3.3333333333333335), (0, 3.0)]

process finished with exit code 0

機器學習 推薦系統

在各類 軟體或各大購物 裡,通常會存在推薦系統。它可以根據每個使用者的個人喜好為使用者推薦相應的歌曲 商品 從而增加使用者體驗,並提高了產品的銷量。因此,推薦系統是乙個很值得學習的應用領域。如下圖所示,這是4個使用者對5部電影的評價,我們要求評價只能是0 5之間的數。可以看出,有一些已經打分了,有一...

機器學習 推薦演算法

推薦系統的核心問題是為使用者推薦與其興趣相似度比較高的商品。此時需要乙個函式f x 來計算候選商品與使用者之間的相似度,並向使用者推薦相似度比較高的商品。為了能夠 出函式f x 可以利用的歷史資料主要有 使用者的歷史行為資料 與該使用者相關的其他使用者資訊 商品之間的相似性 文字的描述等等。其中,r...

推薦系統7 推薦演算法實戰 mahout推薦演算法框架

1.1概述 1.2發展歷史 mahout一直伴隨hadoop發展的,從一開始能夠幫助我們在hadoop上實現很多機器學習,到後來發現它的效率越來越慢,於是放棄使用了一段時間,在一年之後,大概14年開始宣布 0.9版本 截止14年底,mahout不再接受任何mapreduce開發的演算法,轉向spar...