pytorch 个性化推荐系统(电影) - 56+"
本篇文章介绍项目:个性化电影推荐系统(提供完整代码)(一)
其余部分欢迎点击作者主页查看
遇到任何问题欢迎私信我
基于深度学习利用pytorch搭建神经网络,利用ml-1m 数据集进行训练,最后实现多种基于协同过滤的电影推荐方式。
项目资源,百度网盘下载地址(如果失效,可以私信我获取):
百度网盘 请输入提取码
提取码:6vcf
一.模型流程介绍
首先,先来介绍一下模型整体流程。
我们的模型就是要大致完成上述过程,将直观的user和movie 信息,通过模型,转换成一个特征向量,举个例子就是下面这样:
这个是说明userId 1,usergender F,userage "Under 18"(1表示小于18岁,这个是数据集的规定,后面会说明)useroccupation “K-12 student”(10表示的是K12 学生,这个是数据集的规定,后面会说明),zipcode 48067
我们希望通过模型将这些信息变成特征向量的形式
长度是256,很长,就不全部展示了
电影信息处理过程同上,下文会具体展示。
评分信息就是我们的模型训练目标了。
二.数据集介绍
ML-1M数据集是电影推荐系统研究中常用的公开数据集之一,由明尼苏达大学的GroupLens研究团队发布。该数据集包含约100万条电影评分记录,涉及6040名用户和3900多部电影。
数据集内容
用户数量:6040名用户。 电影数量:3900多部电影。 评分数量:1,000,209条评分。
数据集文件格式
users.dat:包含用户的基本信息,每条记录形式为UserID::Gender::Age::Occupation::Zip-code。 movies.dat:包含电影的基本信息,每条记录形式为MovieID::Title::Genres。 ratings.dat:包含用户的评分记录,每条记录形式为UserID::MovieID::Rating::Timestamp
具体来看看:
users.dat
这边要注意一点,
性别标注如下
Gender is denoted by a "M" for male and "F" for female
年龄标注如下,数据集中的数字是表示一个范围,不是具体年龄
Age is chosen from the following ranges:
* 1: "Under 18"
* 18: "18-24"
* 25: "25-34"
* 35: "35-44"
* 45: "45-49"
* 50: "50-55"
* 56: "56+"
职业标注如下,共21种职业,一个用户只能属于一种职业
Occupation is chosen from the following choices:
* 0: "other" or not specified
* 1: "academic/educator"
* 2: "artist"
* 3: "clerical/admin"
* 4: "college/grad student"
* 5: "customer service"
* 6: "doctor/health care"
* 7: "executive/managerial"
* 8: "farmer"
* 9: "homemaker"
* 10: "K-12 student"
* 11: "lawyer"
* 12: "programmer"
* 13: "retired"
* 14: "sales/marketing"
* 15: "scientist"
* 16: "self-employed"
* 17: "technician/engineer"
* 18: "tradesman/craftsman"
* 19: "unemployed"
* 20: "writer"
movies.dat
电影信息注意一点,每部电影名字后面都标上了上映时间,一部电影可能是多种体裁的
一共有如下18种体裁:
Genres are pipe-separated and are selected from the following genres:
* Action
* Adventure
* Animation
* Children's
* Comedy
* Crime
* Documentary
* Drama
* Fantasy
* Film-Noir
* Horror
* Musical
* Mystery
* Romance
* Sci-Fi
* Thriller
* War
* Western
ratings.dat
数据集下载链接
http://files.grouplens.org/datasets/movielens/ml-1m.zip
三.运行环境介绍
强烈推荐anconda来配置环境,几个主要的库的版本如下,别的不太重要
四.数据预处理
下面让我们来对上述的三个dat文件进行数据预处理,来适应模型的输入吧
我们直接继承torch的Dataset类,来写一个自己的MovielensDataset类
直接给出代码:
代码
import torch
from torch.utils.data import Dataset
import pandas as pd
import numpy as np
import re
class MovieLensDataset(Dataset):
def __init__(self, ratings_file, movies_file, users_file, glove_file, transform=None):
"""
:param ratings_file: str, ratings.dat 文件路径
:param movies_file: str, movies.dat 文件路径
:param users_file: str, users.dat 文件路径
:param glove_file: str, glove.6B 文件路径
:param transform: 可选的转换函数
"""
# 读取数据
self.ratings_df = pd.read_csv(ratings_file, sep='::', engine='python',
names=['userId', 'movieId', 'rating', 'timestamp'])
self.movies_df = pd.read_csv(movies_file, sep='::', engine='python', names=['movieId', 'title', 'genres'],
encoding='ISO-8859-1')
self.users_df = pd.read_csv(users_file, sep='::', engine='python',
names=['userId', 'gender', 'age', 'occupation', 'zip'])
# 加载 GloVe 词向量
self.glove_vectors = self.load_glove_vectors(glove_file)
# 处理数据
self.movies_df['title'] = self.movies_df['title'].apply(self.process_movie_title)
self.movies_df['title_matrix'] = self.movies_df['title'].apply(self.get_title_matrix)
self.movies_df['genres_vector'] = self.movies_df['genres'].apply(self.get_genres_vector)
self.users_df['gender'] = self.users_df['gender'].map({'M': 1, 'F': 0})
self.users_df['age'] = self.users_df['age'].map({1: 0, 18: 1, 25: 2, 35: 3, 45: 4, 50: 5, 56: 6})
self.transform = transform
def __len__(self):
return len(self.ratings_df)
def __getitem__(self, idx):
# 获取评分数据
rating_data = self.ratings_df.iloc[idx]
user_id = rating_data['userId']
movie_id = rating_data['movieId']
rating = rating_data['rating']
# 获取电影信息
movie_info = self.movies_df[self.movies_df['movieId'] == movie_id].iloc[0]
movie_title_matrix = movie_info['title_matrix']
movie_genres_vector = movie_info['genres_vector']
# 获取用户信息
user_info = self.users_df[self.users_df['userId'] == user_id].iloc[0]
user_gender = user_info['gender']
user_age = user_info['age']
user_occupation = user_info['occupation']
# 构建样本
sample = {
'userId': torch.tensor(user_id, dtype=torch.long),
'movieId': torch.tensor(movie_id, dtype=torch.long),
'rating': torch.tensor(rating, dtype=torch.float),
'movie_title_matrix': torch.tensor(movie_title_matrix, dtype=torch.float),
'movie_genres_vector': torch.tensor(movie_genres_vector, dtype=torch.long),
'user_gender': torch.tensor(user_gender, dtype=torch.long),
'user_age': torch.tensor(user_age, dtype=torch.long),
'user_occupation': torch.tensor(user_occupation, dtype=torch.long)
}
if self.transform:
sample = self.transform(sample)
return sample
def process_movie_title(self, title):
"""
处理电影标题,去掉年份并转小写。
"""
title = re.sub(r'\s\(\d{4}\)$', '', title) # 删除年份
return title.lower()
def load_glove_vectors(self, glove_file):
"""
加载 GloVe 词向量文件,并将词与词向量映射存储为字典。
"""
glove_vectors = {}
with open(glove_file, 'r', encoding='utf-8') as f:
for line in f:
values = line.split()
word = values[0]
vector = np.array(values[1:], dtype='float32')
glove_vectors[word] = vector
return glove_vectors
def get_title_matrix(self, title, max_words=10):
"""
获取电影标题对应的 GloVe 词向量矩阵(固定大小 max_words)。
如果某个词没有词向量,则忽略该词。
超过 max_words 的部分会被截断,不足的部分会被填充为零。
"""
title_words = title.split()
title_matrix = []
# 选择有效的词向量
for word in title_words:
if word in self.glove_vectors:
title_matrix.append(self.glove_vectors[word])
# 如果有效词向量数量不足 max_words,使用零向量填充
while len(title_matrix) < max_words:
title_matrix.append(np.zeros(50)) # 添加 50 维的零向量
# 如果有效词向量数量超过 max_words,截断
title_matrix = title_matrix[:max_words]
# 转换为 (max_words, 50) 的矩阵
return np.array(title_matrix)
def get_genres_vector(self, genres):
"""
将电影类型转为类独热编码向量。
"""
genre_list = genres.split('|')
genre_set = set(genre_list)
all_genres = ['Action', 'Adventure', 'Animation', 'Children\'s', 'Comedy', 'Crime', 'Documentary',
'Drama', 'Fantasy', 'Film-Noir', 'Horror', 'Musical', 'Mystery', 'Romance', 'Sci-Fi',
'Thriller', 'War', 'Western']
genre_vector = np.zeros(len(all_genres))
for genre in genre_set:
if genre in all_genres:
genre_vector[all_genres.index(genre)] = all_genres.index(genre) + 1
return genre_vector
"""
# 使用示例
# 文件路径
ratings_file = 'data/ml-1m/ratings.dat'
movies_file = 'data/ml-1m/movies.dat'
users_file = 'data/ml-1m/users.dat'
glove_file = 'data/glove.6B.50d.txt'
dataset = MovieLensDataset(ratings_file, movies_file, users_file, glove_file)
# 查看一个样本
sample = dataset[0]
print(sample)
print(f"User ID: {sample['userId']}, Movie ID: {sample['movieId']}, Rating: {sample['rating']}")
print(f"Movie Title Matrix: {sample['movie_title_matrix']}")
print(f"Movie Genres Vector: {sample['movie_genres_vector']}")
print(f"User Gender: {sample['user_gender']}")
print(f"User Age:{sample['user_age']}") 拼多多帮助力入口
print(f"User Occupation:{sample['user_occupation']}")
# 使用 DataLoader 批量加载
from torch.utils.data import DataLoader
dataloader = DataLoader(dataset, batch_size=5, shuffle=True)
for batch in dataloader:
print(batch)
"""
来介绍下这段代码干了什么
首先是利用pd来读取我们的三个dat文件
电影标题的预处理
将电影名字中的每个单词转换成对应的词向量
利用glove.60b.50d,这个是预训练过的词向量,利用这个来实现。
glove.60b.50d下载链接:https://apache-mxnet.s3.cn-north-1.amazonaws.com.cn/gluon/embeddings/glove/glove.6B.zip
转换的过程注意几个点:年份我们不使用直接去除,因为glove.60b.50d单词都是小写,我们要把标题的单词全部转小写,为了模型输入的统一,我们设置标题长度最长max_words = 10个单词,如果某个词没有词向量,则忽略该词。 超过 max_words 的部分会被截断,不足的部分会被填充为零。
电影体裁的预处理
将电影的体裁转换为对应的伪独热编码
比如用一个list记录 每个位置若不为0表示该电影属于该体裁
具体是什么样子的,可以运行代码看一看,在代码尾部也有运行示例
用户信息的预处理
用户性别 M变成1,F变成0
用户年龄 ,如下转换,1变成0,18变成1,25变成2........
{1: 0, 18: 1, 25: 2, 35: 3, 45: 4, 50: 5, 56: 6}
用户的职业,就直接用它给的数字就好
本篇是(一)主要介绍了模型要干些什么,数据集如何,运行环境如何,数据的预处理方式
其余部分欢迎点击作者主页继续查看,遇到任何问题欢迎私信我
苦逼在校大学生,如果你觉得对你有用的话,欢迎打赏:
pytorch 个性化推荐系统(电影)
参考链接