日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

推荐算法 之协同过滤

發布時間:2025/4/5 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 推荐算法 之协同过滤 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

代碼下載

# coding:UTF-8 ''' Date:20160928 @author: zhaozhiyong '''import numpy as np import pandasdef load_data(file_path):'''導入用戶商品數據input: file_path(string):用戶商品數據存放的文件output: data(mat):用戶商品矩陣'''f = open(file_path) data = []for line in f.readlines():lines = line.strip().split("\t")tmp = []for x in lines:if x != "-":tmp.append(float(x)) # 直接存儲用戶對商品的打分else:tmp.append(0)data.append(tmp)f.close()return np.mat(data)def cos_sim(x, y):'''余弦相似性input: x(mat):以行向量的形式存儲,可以是用戶或者商品y(mat):以行向量的形式存儲,可以是用戶或者商品output: x和y之間的余弦相似度'''numerator = x * y.T # x和y之間的額內積denominator = np.sqrt(x * x.T) * np.sqrt(y * y.T) return (numerator / denominator)[0, 0]def similarity(data):'''計算矩陣中任意兩行之間的相似度input: data(mat):任意矩陣output: w(mat):任意兩行之間的相似度'''m = np.shape(data)[0] # 用戶的數量# 初始化相似度矩陣w = np.mat(np.zeros((m, m)))for i in range(m):for j in range(i, m):if j != i:# 計算任意兩行之間的相似度w[i, j] = cos_sim(data[i, ], data[j, ])w[j, i] = w[i, j]else:w[i, j] = 0return wdef user_based_recommend(data, w, user):'''基于用戶相似性為用戶user推薦商品input: data(mat):用戶商品矩陣w(mat):用戶之間的相似度user(int):用戶的編號output: predict(list):推薦列表'''m, n = np.shape(data)interaction = data[user, ] # 用戶user與商品信息# 1、找到用戶user沒有互動過的商品not_inter = []for i in range(n):if interaction[0, i] == 0: # 沒有互動的商品not_inter.append(i)# 2、對沒有互動過的商品進行預測print('not_inter=',not_inter)predict={}dd=np.array(data)ww=np.array(w) if len(not_inter)>0:for i in not_inter:predict[i]=ww[:,user]@dd[:,i].Tprint(predict)return predictdef top_k(predict, k):'''為用戶推薦前k個商品input: predict(list):排好序的商品列表k(int):推薦的商品個數output: top_recom(list):top_k個商品'''pp=pandas.Series(predict)pp1=pp.sort_values(ascending=False)#top_recom = []len_result = len(predict)if k>=len_result:return pp1.iloc[:k]else:return pp1if __name__ == "__main__":# 1、導入用戶商品數據print ("------------ 1. load data ------------")data = load_data("data.txt")# 2、計算用戶之間的相似性print ("------------ 2. calculate similarity between users -------------" ) w = similarity(data)# 3、利用用戶之間的相似性進行推薦print ("------------ 3. predict ------------" ) predict = user_based_recommend(data, w, 0)# 4、進行Top-K推薦print ("------------ 4. top_k recommendation ------------")top_recom = top_k(predict, 1)print ('top_recom=',top_recom) ------------ 1. load data ------------ ------------ 2. calculate similarity between users ------------- ------------ 3. predict ------------ not_inter= [2, 4] {2: 5.1030390226883604} {2: 5.1030390226883604, 4: 2.2249110640673515} ------------ 4. top_k recommendation ------------ top_recom= 2 5.103039 4 2.224911 dtype: float64

總結

以上是生活随笔為你收集整理的推荐算法 之协同过滤的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。