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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > windows >内容正文

windows

【转】Python推荐系统库——Surprise

發布時間:2023/12/8 windows 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【转】Python推荐系统库——Surprise 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

原文 :https://blog.csdn.net/mycafe_/article/details/79146764

?

@ 2018-01-24

Surprise
簡單易用同時支持多種推薦算法
其中基于近鄰的方法協同過濾可以設定不同的度量準則
支持不同的評估準則
使用示例
基本使用方法如下
載入自己的數據集方法
算法調參讓推薦系統有更好的效果
在自己的數據集上訓練模型
首先載入數據
使用不同的推薦系統算法進行建模比較
建模和存儲模型
用協同過濾構建模型并進行預測
1 movielens的例子
2 音樂預測的例子
用SVD矩陣分解進行預測
Surprise
在推薦系統的建模過程中,我們將用到python庫 Surprise(Simple Python RecommendatIon System Engine),是scikit系列中的一個(很多同學用過scikit-learn和scikit-image等庫)。Surprise的User Guide有詳細的解釋和說明

簡單易用,同時支持多種推薦算法:
基礎算法/baseline algorithms
基于近鄰方法(協同過濾)/neighborhood methods
矩陣分解方法/matrix factorization-based (SVD, PMF, SVD++, NMF)
算法類名?? ?說明
random_pred.NormalPredictor?? ?Algorithm predicting a random rating based on the distribution of the training set, which is assumed to be normal.
baseline_only.BaselineOnly?? ?Algorithm predicting the baseline estimate for given user and item.
knns.KNNBasic?? ?A basic collaborative filtering algorithm.
knns.KNNWithMeans?? ?A basic collaborative filtering algorithm, taking into account the mean ratings of each user.
knns.KNNBaseline?? ?A basic collaborative filtering algorithm taking into account a baseline rating.
matrix_factorization.SVD?? ?The famous SVD algorithm, as popularized by Simon Funk during the Netflix Prize.
matrix_factorization.SVDpp?? ?The SVD++ algorithm, an extension of SVD taking into account implicit ratings.
matrix_factorization.NMF?? ?A collaborative filtering algorithm based on Non-negative Matrix Factorization.
slope_one.SlopeOne?? ?A simple yet accurate collaborative filtering algorithm.
co_clustering.CoClustering?? ?A collaborative filtering algorithm based on co-clustering.
其中基于近鄰的方法(協同過濾)可以設定不同的度量準則。
相似度度量標準?? ?度量標準說明
cosine?? ?Compute the cosine similarity between all pairs of users (or items).
msd?? ?Compute the Mean Squared Difference similarity between all pairs of users (or items).
pearson?? ?Compute the Pearson correlation coefficient between all pairs of users (or items).
pearson_baseline?? ?Compute the (shrunk) Pearson correlation coefficient between all pairs of users (or items) using baselines for centering instead of means.
支持不同的評估準則
評估準則?? ?準則說明
rmse?? ?Compute RMSE (Root Mean Squared Error).
mae?? ?Compute MAE (Mean Absolute Error).
fcp?? ?Compute FCP (Fraction of Concordant Pairs).
使用示例
基本使用方法如下
# 可以使用上面提到的各種推薦系統算法
from surprise import SVD
from surprise import Dataset
from surprise import evaluate, print_perf

# 默認載入movielens數據集,會提示是否下載這個數據集,這是非常經典的公開推薦系統數據集——MovieLens數據集之一
data = Dataset.load_builtin('ml-100k')
# k折交叉驗證(k=3)
data.split(n_folds=3)
# 試一把SVD矩陣分解
algo = SVD()
# 在數據集上測試一下效果
perf = evaluate(algo, data, measures=['RMSE', 'MAE'])
#輸出結果
print_perf(perf)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
載入自己的數據集方法
# 指定文件所在路徑
file_path = os.path.expanduser('~/.surprise_data/ml-100k/ml-100k/u.data')
# 告訴文本閱讀器,文本的格式是怎么樣的
reader = Reader(line_format='user item rating timestamp', sep='\t')
# 加載數據
data = Dataset.load_from_file(file_path, reader=reader)
# 手動切分成5折(方便交叉驗證)
data.split(n_folds=5)
1
2
3
4
5
6
7
8
算法調參(讓推薦系統有更好的效果)
這里實現的算法用到的算法無外乎也是SGD等,因此也有一些超參數會影響最后的結果,我們同樣可以用sklearn中常用到的網格搜索交叉驗證(GridSearchCV)來選擇最優的參數。簡單的例子如下所示:

# 定義好需要優選的參數網格
param_grid = {'n_epochs': [5, 10], 'lr_all': [0.002, 0.005],
? ? ? ? ? ? ? 'reg_all': [0.4, 0.6]}
# 使用網格搜索交叉驗證
grid_search = GridSearch(SVD, param_grid, measures=['RMSE', 'FCP'])
# 在數據集上找到最好的參數
data = Dataset.load_builtin('ml-100k')
data.split(n_folds=3)
grid_search.evaluate(data)
# 輸出調優的參數組?
# 輸出最好的RMSE結果
print(grid_search.best_score['RMSE'])
# >>> 0.96117566386

# 輸出對應最好的RMSE結果的參數
print(grid_search.best_params['RMSE'])
# >>> {'reg_all': 0.4, 'lr_all': 0.005, 'n_epochs': 10}

# 最好的FCP得分
print(grid_search.best_score['FCP'])
# >>> 0.702279736531

# 對應最高FCP得分的參數
print(grid_search.best_params['FCP'])
# >>> {'reg_all': 0.6, 'lr_all': 0.005, 'n_epochs': 10}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
在自己的數據集上訓練模型
首先載入數據
import os
from surprise import Reader, Dataset
# 指定文件路徑
file_path = os.path.expanduser('./popular_music_suprise_format.txt')
# 指定文件格式
reader = Reader(line_format='user item rating timestamp', sep=',')
# 從文件讀取數據
music_data = Dataset.load_from_file(file_path, reader=reader)
# 分成5折
music_data.split(n_folds=5)
1
2
3
4
5
6
7
8
9
10
使用不同的推薦系統算法進行建模比較
### 使用NormalPredictor
from surprise import NormalPredictor, evaluate
algo = NormalPredictor()
perf = evaluate(algo, music_data, measures=['RMSE', 'MAE'])

### 使用BaselineOnly
from surprise import BaselineOnly, evaluate
algo = BaselineOnly()
perf = evaluate(algo, music_data, measures=['RMSE', 'MAE'])

### 使用基礎版協同過濾
from surprise import KNNBasic, evaluate
algo = KNNBasic()
perf = evaluate(algo, music_data, measures=['RMSE', 'MAE'])

### 使用均值協同過濾
from surprise import KNNWithMeans, evaluate
algo = KNNWithMeans()
perf = evaluate(algo, music_data, measures=['RMSE', 'MAE'])

### 使用協同過濾baseline
from surprise import KNNBaseline, evaluate
algo = KNNBaseline()
perf = evaluate(algo, music_data, measures=['RMSE', 'MAE'])

### 使用SVD
from surprise import SVD, evaluate
algo = SVD()
perf = evaluate(algo, music_data, measures=['RMSE', 'MAE'])

### 使用SVD++
from surprise import SVDpp, evaluate
algo = SVDpp()
perf = evaluate(algo, music_data, measures=['RMSE', 'MAE'])

### 使用NMF
from surprise import NMF
algo = NMF()
perf = evaluate(algo, music_data, measures=['RMSE', 'MAE'])
print_perf(perf)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
建模和存儲模型
1.用協同過濾構建模型并進行預測
1.1 movielens的例子
# 可以使用上面提到的各種推薦系統算法
from surprise import SVD
from surprise import Dataset
from surprise import evaluate, print_perf

# 默認載入movielens數據集
data = Dataset.load_builtin('ml-100k')
# k折交叉驗證(k=3)
data.split(n_folds=3)
# 試一把SVD矩陣分解
algo = SVD()
# 在數據集上測試一下效果
perf = evaluate(algo, data, measures=['RMSE', 'MAE'])
#輸出結果
print_perf(perf)

"""
以下的程序段告訴大家如何在協同過濾算法建模以后,根據一個item取回相似度最高的item,主要是用到algo.get_neighbors()這個函數
"""

from __future__ import (absolute_import, division, print_function,
? ? ? ? ? ? ? ? ? ? ? ? unicode_literals)
import os
import io

from surprise import KNNBaseline
from surprise import Dataset


def read_item_names():
? ? """
? ? 獲取電影名到電影id 和 電影id到電影名的映射
? ? """

? ? file_name = (os.path.expanduser('~') +
? ? ? ? ? ? ? ? ?'/.surprise_data/ml-100k/ml-100k/u.item')
? ? rid_to_name = {}
? ? name_to_rid = {}
? ? with io.open(file_name, 'r', encoding='ISO-8859-1') as f:
? ? ? ? for line in f:
? ? ? ? ? ? line = line.split('|')
? ? ? ? ? ? rid_to_name[line[0]] = line[1]
? ? ? ? ? ? name_to_rid[line[1]] = line[0]

? ? return rid_to_name, name_to_rid


# 首先,用算法計算相互間的相似度
data = Dataset.load_builtin('ml-100k')
trainset = data.build_full_trainset()
sim_options = {'name': 'pearson_baseline', 'user_based': False}
algo = KNNBaseline(sim_options=sim_options)
algo.train(trainset)

# 獲取電影名到電影id 和 電影id到電影名的映射
rid_to_name, name_to_rid = read_item_names()

# Retieve inner id of the movie Toy Story
toy_story_raw_id = name_to_rid['Toy Story (1995)']
toy_story_inner_id = algo.trainset.to_inner_iid(toy_story_raw_id)

# Retrieve inner ids of the nearest neighbors of Toy Story.
toy_story_neighbors = algo.get_neighbors(toy_story_inner_id, k=10)

# Convert inner ids of the neighbors into names.
toy_story_neighbors = (algo.trainset.to_raw_iid(inner_id)
? ? ? ? ? ? ? ? ? ? ? ?for inner_id in toy_story_neighbors)
toy_story_neighbors = (rid_to_name[rid]
? ? ? ? ? ? ? ? ? ? ? ?for rid in toy_story_neighbors)

print()
print('The 10 nearest neighbors of Toy Story are:')
for movie in toy_story_neighbors:
? ? print(movie)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
1.2 音樂預測的例子
from __future__ import (absolute_import, division, print_function, unicode_literals)
import os
import io

from surprise import KNNBaseline
from surprise import Dataset

import cPickle as pickle
# 重建歌單id到歌單名的映射字典
id_name_dic = pickle.load(open("popular_playlist.pkl","rb"))
print("加載歌單id到歌單名的映射字典完成...")
# 重建歌單名到歌單id的映射字典
name_id_dic = {}
for playlist_id in id_name_dic:
? ? name_id_dic[id_name_dic[playlist_id]] = playlist_id
print("加載歌單名到歌單id的映射字典完成...")


file_path = os.path.expanduser('./popular_music_suprise_format.txt')
# 指定文件格式
reader = Reader(line_format='user item rating timestamp', sep=',')
# 從文件讀取數據
music_data = Dataset.load_from_file(file_path, reader=reader)
# 計算歌曲和歌曲之間的相似度
print("構建數據集...")
trainset = music_data.build_full_trainset()
#sim_options = {'name': 'pearson_baseline', 'user_based': False}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
current_playlist => 歌單名
playlist_id => 歌單id(網易給的歌單id)
playlist_inner_id => 內部id(對所有歌單id重新從1開始編碼)
print("開始訓練模型...")
#sim_options = {'user_based': False}
#algo = KNNBaseline(sim_options=sim_options)
algo = KNNBaseline()
algo.train(trainset)

current_playlist = name_id_dic.keys()[39]
print(current_playlist)

# 取出近鄰
playlist_id = name_id_dic[current_playlist]
print(playlist_id)
playlist_inner_id = algo.trainset.to_inner_uid(playlist_id)
print(playlist_inner_id)

playlist_neighbors = algo.get_neighbors(playlist_inner_id, k=10)

# 把歌曲id轉成歌曲名字
playlist_neighbors = (algo.trainset.to_raw_uid(inner_id)
? ? ? ? ? ? ? ? ? ? ? ?for inner_id in playlist_neighbors)
playlist_neighbors = (id_name_dic[playlist_id]
? ? ? ? ? ? ? ? ? ? ? ?for playlist_id in playlist_neighbors)

print()
print("和歌單 《", current_playlist, "》 最接近的10個歌單為:\n")
for playlist in playlist_neighbors:
? ? print(playlist)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2.用SVD矩陣分解進行預測
### 使用SVD++
from surprise import SVDpp, evaluate
from surprise import Dataset

file_path = os.path.expanduser('./popular_music_suprise_format.txt')
# 指定文件格式
reader = Reader(line_format='user item rating timestamp', sep=',')
# 從文件讀取數據
music_data = Dataset.load_from_file(file_path, reader=reader)
# 構建數據集和建模
algo = SVDpp()
trainset = music_data.build_full_trainset()
algo.train(trainset)
---------------------?
作者:Mars_myCafe?
來源:CSDN?
原文:https://blog.csdn.net/mycafe_/article/details/79146764?
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

?

?

總結

以上是生活随笔為你收集整理的【转】Python推荐系统库——Surprise的全部內容,希望文章能夠幫你解決所遇到的問題。

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

主站蜘蛛池模板: 麻豆传媒在线视频 | 夜色视频在线观看 | 日韩在线免费 | 封神榜二在线高清免费观看 | 免费黄色一级视频 | 中文字幕av不卡 | 国产裸体永久免费视频网站 | 欧美女优一区二区 | www.综合色| 精品国产乱码一区二区三区99 | 色妞欧美 | 成人青青草 | 国产丝袜一区二区三区 | 寻找身体恐怖电影免费播放 | www.久久国产| 日韩一本在线 | 亚洲男女啪啪 | 成人午夜在线播放 | 91精品国产免费 | 新x8x8拨牐拨牐永久免费影库 | 中文字幕精品一区二区精品 | 国产1区2区3区中文字幕 | 欧美高清一级 | 伊人网中文字幕 | 久久国产乱子伦免费精品 | 黄频在线播放 | 99这里有精品视频 | 久久久九九九九 | 日本不卡1| 国产深夜福利 | 亚洲一区,二区 | 东北少妇不戴套对白第一次 | 亚洲天堂伊人网 | 日本一区二区观看 | 暧暧视频在线观看 | 久久入口 | 人成在线观看 | 国产chinese | 白白色在线播放 | 天堂久久精品忘忧草 | 91狠狠干| 成人在线观看一区二区 | 日日碰狠狠添天天爽 | 封神榜二在线高清免费观看 | 老鸭窝av在线 | 天堂8在线视频 | 亚洲av熟女国产一区二区性色 | 日本成人在线免费观看 | 制服丝袜一区在线 | 国产成人愉拍精品久久 | 一区二区三区av | 激情av小说| 91在线免费视频观看 | 日本精品二区 | 绿帽人妻精品一区二区 | 天堂精品在线 | 久久久久精彩视频 | 精品人妻一区二区三区三区四区 | 欧美日韩毛片 | 香蕉爱爱视频 | 国产午夜亚洲精品午夜鲁丝片 | 91射| 国产无码精品合集 | 亚洲国产成人自拍 | 男生尿隔着内裤呲出来视频 | 91视频在线免费 | 久久与婷婷 | 国产男女猛烈无遮挡免费视频动漫 | 国产伊人一区 | 亚洲欧洲日本一区二区三区 | 国产丝袜美腿一区二区三区 | 国产99在线观看 | 99爱视频 | 神马影院午夜伦理 | 国产刺激高潮av | 先锋影音一区二区 | 一本久道视频一本久道 | www.色国产| 国产东北露脸精品视频 | 国产精品日韩欧美一区二区三区 | 国产视频一区在线 | www.-级毛片线天内射视视 | 超碰在线最新地址 | 久久综合伊人77777麻豆最新章节 | 性感美女高潮 | 人妻熟女一区二区aⅴ水野 91在线观看视频 | 国产精品77777 | 涩涩视频免费观看 | 色老二导航 | 怡春院在线视频 | 四虎永久在线精品免费一区二区 | 中文字幕国产剧情 | 91免费毛片 | 被扒开腿一边憋尿一边惩罚 | 俺去日| 欧美成a| 国产香蕉视频 | 天天操天天插 | 日本不卡一二 |