Skip to content
Extraits de code Groupes Projets
Valider 25cec0bf rédigé par Adrien Payen's avatar Adrien Payen
Parcourir les fichiers

commit feature methods

parent 861461d5
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
...@@ -16,6 +16,10 @@ class Constant: ...@@ -16,6 +16,10 @@ class Constant:
LABEL_COL = 'title' # Column name for item labels LABEL_COL = 'title' # Column name for item labels
GENRES_COL = 'genres' # Column name for item genres GENRES_COL = 'genres' # Column name for item genres
TAGS_FILENAME = "tags.csv"
TAG = 'tag'
# Evidence # Evidence
EVIDENCE_PATH = DATA_PATH / 'evidence' # Path to evidence data EVIDENCE_PATH = DATA_PATH / 'evidence' # Path to evidence data
# - ratings # - ratings
......
%% Cell type:markdown id:82d5ca82 tags: %% Cell type:markdown id:82d5ca82 tags:
# Packages # Packages
%% Cell type:code id:277473a3 tags: %% Cell type:code id:277473a3 tags:
``` python ``` python
%load_ext autoreload %load_ext autoreload
%autoreload 2 %autoreload 2
import numpy as np import numpy as np
import pandas as pd import pandas as pd
import random as rd import random as rd
from surprise import AlgoBase from surprise import AlgoBase
from surprise.prediction_algorithms.predictions import PredictionImpossible from surprise.prediction_algorithms.predictions import PredictionImpossible
from loaders import load_ratings from loaders import load_ratings
from loaders import load_items from loaders import load_items
from constants import Constant as C from constants import Constant as C
from sklearn.linear_model import LinearRegression from sklearn.linear_model import LinearRegression
``` ```
%% Output %% Output
The autoreload extension is already loaded. To reload it, use: The autoreload extension is already loaded. To reload it, use:
%reload_ext autoreload %reload_ext autoreload
%% Cell type:markdown id:a42c16bf tags: %% Cell type:markdown id:a42c16bf tags:
# Explore and select content features # Explore and select content features
%% Cell type:code id:e8378976 tags: %% Cell type:code id:e8378976 tags:
``` python ``` python
df_items = load_items() df_items = load_items()
df_ratings = load_ratings() df_ratings = load_ratings()
# Example 1 : create title_length features # Example 1 : create title_length features
df_features = df_items[C.LABEL_COL].apply(lambda x: len(x)).to_frame('n_character_title') df_features = df_items[C.LABEL_COL].apply(lambda x: len(x)).to_frame('n_character_title')
display(df_features.head()) display(df_features.head())
df_tag = pd.read_csv(C.CONTENT_PATH/C.TAGS_FILENAME)
df_features = df_tag[C.TAG]
display(df_features.head())
# (explore here other features) # (explore here other features)
``` ```
%% Output %% Output
%% Cell type:markdown id:a2c9a2b6 tags: %% Cell type:markdown id:a2c9a2b6 tags:
# Build a content-based model # Build a content-based model
When ready, move the following class in the *models.py* script When ready, move the following class in the *models.py* script
%% Cell type:code id:16b0a602 tags: %% Cell type:code id:16b0a602 tags:
``` python ``` python
class ContentBased(AlgoBase): class ContentBased(AlgoBase):
def __init__(self, features_method, regressor_method): def __init__(self, features_method, regressor_method):
AlgoBase.__init__(self) AlgoBase.__init__(self)
self.regressor_method = regressor_method self.regressor_method = regressor_method
self.content_features = self.create_content_features(features_method) self.content_features = self.create_content_features(features_method)
def create_content_features(self, features_method): def create_content_features(self, features_method):
"""Content Analyzer""" """Content Analyzer"""
df_items = load_items() df_items = load_items()
if features_method is None: if features_method is None:
df_features = None df_features = None
elif features_method == "title_length": # a naive method that creates only 1 feature based on title length elif features_method == "title_length": # a naive method that creates only 1 feature based on title length
df_features = df_items[C.LABEL_COL].apply(lambda x: len(x)).to_frame('n_character_title') df_features = df_items[C.LABEL_COL].apply(lambda x: len(x)).to_frame('n_character_title')
elif features_method == "movie_year" :
df_features = df_items['movie_year'] = df_items['title'].str.extract(r'\((\d{4})\)', expand=False)
elif features_method == "genres" :
genres_list = df_items['genres'].str.split('|').explode().unique()
for genre in genres_list:
df_features = df_items['genres'].str.contains(genre).astype(int)
elif features_method == "rating" :
df_features = df_ratings.groupby('movieId')['rating'].transform('mean').to_frame('avg_rating')
elif features_method == "tags" :
df_features = df_tag['tag'].apply(lambda x: len(x.split(',')))
elif features_method == "tags_length" :
df_features = df_tag['tag'].apply(lambda x: sum(len(tag) for tag in x.split(',')))
elif features_method == "timestamp" :
df_features = df_ratings['timestamp_sin'] = np.sin(2 * np.pi * df_ratings['timestamp'] / 86400)
df_features = df_ratings['timestamp_cos'] = np.cos(2 * np.pi * df_ratings['timestamp'] / 86400)
else: # (implement other feature creations here) else: # (implement other feature creations here)
raise NotImplementedError(f'Feature method {features_method} not yet implemented') raise NotImplementedError(f'Feature method {features_method} not yet implemented')
return df_features return df_features
def fit(self, trainset): def fit(self, trainset):
"""Profile Learner""" """Profile Learner"""
AlgoBase.fit(self, trainset) AlgoBase.fit(self, trainset)
# Preallocate user profiles # Preallocate user profiles
self.user_profile = {u: None for u in trainset.all_users()} self.user_profile = {u: None for u in trainset.all_users()}
if self.regressor_method == 'random_score': if self.regressor_method == 'random_score':
for u in self.user_profile : for u in self.user_profile :
self.user_profile[u] = rd.uniform(0.5,5) self.user_profile[u] = rd.uniform(0.5,5)
elif self.regressor_method == 'random_sample': elif self.regressor_method == 'random_sample':
for u in self.user_profile: for u in self.user_profile:
self.user_profile[u] = [rating for _, rating in self.trainset.ur[u]] self.user_profile[u] = [rating for _, rating in self.trainset.ur[u]]
elif self.regressor_method == 'linear_regression' : elif self.regressor_method == 'linear_regression' :
for u in self.user_profile: for u in self.user_profile:
user_ratings = [rating for _, rating in trainset.ur[u]] user_ratings = [rating for _, rating in trainset.ur[u]]
item_ids = [iid for iid, _ in trainset.ur[u]] item_ids = [iid for iid, _ in trainset.ur[u]]
df_user = pd.DataFrame({'item_id': item_ids, 'user_ratings': user_ratings}) df_user = pd.DataFrame({'item_id': item_ids, 'user_ratings': user_ratings})
df_user["item_id"] = df_user["item_id"].map(trainset.to_raw_iid) df_user["item_id"] = df_user["item_id"].map(trainset.to_raw_iid)
df_user = df_user.merge(self.content_features, left_on = "item_id", right_index = True, how = 'left') df_user = df_user.merge(self.content_features, left_on = "item_id", right_index = True, how = 'left')
X = df_user['n_character_title'].values.reshape(-1,1) X = df_user['n_character_title'].values.reshape(-1,1)
y = df_user['user_ratings'].values y = df_user['user_ratings'].values
linear_regressor = LinearRegression(fit_intercept = False) linear_regressor = LinearRegression(fit_intercept = False)
linear_regressor.fit(X,y) linear_regressor.fit(X,y)
# Store the computed user profile # Store the computed user profile
self.user_profile[u] = linear_regressor self.user_profile[u] = linear_regressor
else : else :
pass pass
# (implement here the regressor fitting) # (implement here the regressor fitting)
def estimate(self, u, i): def estimate(self, u, i):
"""Scoring component used for item filtering""" """Scoring component used for item filtering"""
# First, handle cases for unknown users and items # First, handle cases for unknown users and items
if not (self.trainset.knows_user(u) and self.trainset.knows_item(i)): if not (self.trainset.knows_user(u) and self.trainset.knows_item(i)):
raise PredictionImpossible('User and/or item is unkown.') raise PredictionImpossible('User and/or item is unkown.')
if self.regressor_method == 'random_score': if self.regressor_method == 'random_score':
rd.seed() rd.seed()
score = rd.uniform(0.5,5) score = rd.uniform(0.5,5)
elif self.regressor_method == 'random_sample': elif self.regressor_method == 'random_sample':
rd.seed() rd.seed()
score = rd.choice(self.user_profile[u]) score = rd.choice(self.user_profile[u])
elif self.regressor_method == 'linear_regression': elif self.regressor_method == 'linear_regression':
raw_item_id = self.trainset.to_raw_iid(i) raw_item_id = self.trainset.to_raw_iid(i)
item_features = self.content_features.loc[raw_item_id:raw_item_id, :].values item_features = self.content_features.loc[raw_item_id:raw_item_id, :].values
linear_regressor = self.user_profile[u] linear_regressor = self.user_profile[u]
score= linear_regressor.predict(item_features)[0] score= linear_regressor.predict(item_features)[0]
else : else :
score = None score = None
# (implement here the regressor prediction) # (implement here the regressor prediction)
return score return score
``` ```
%% Cell type:markdown id:ffd75b7e tags: %% Cell type:markdown id:ffd75b7e tags:
The following script test the ContentBased class The following script test the ContentBased class
%% Cell type:code id:69d12f7d tags: %% Cell type:code id:69d12f7d tags:
``` python ``` python
def test_contentbased_class(feature_method, regressor_method): def test_contentbased_class(feature_method, regressor_method):
"""Test the ContentBased class. """Test the ContentBased class.
Tries to make a prediction on the first (user,item ) tuple of the anti_test_set Tries to make a prediction on the first (user,item ) tuple of the anti_test_set
""" """
sp_ratings = load_ratings(surprise_format=True) sp_ratings = load_ratings(surprise_format=True)
train_set = sp_ratings.build_full_trainset() train_set = sp_ratings.build_full_trainset()
content_algo = ContentBased(feature_method, regressor_method) content_algo = ContentBased(feature_method, regressor_method)
content_algo.fit(train_set) content_algo.fit(train_set)
anti_test_set_first = train_set.build_anti_testset()[0] anti_test_set_first = train_set.build_anti_testset()[0]
prediction = content_algo.predict(anti_test_set_first[0], anti_test_set_first[1]) prediction = content_algo.predict(anti_test_set_first[0], anti_test_set_first[1])
print(prediction) print(prediction)
# (call here the test functions with different regressor methods) # (call here the test functions with different regressor methods)
test_contentbased_class(feature_method = "title_length" , regressor_method = "random_score") test_contentbased_class(feature_method = "title_length" , regressor_method = "random_score")
test_contentbased_class(feature_method = "title_length" , regressor_method = "random_sample") test_contentbased_class(feature_method = "title_length" , regressor_method = "random_sample")
test_contentbased_class(feature_method="movie_year", regressor_method="random_score")
test_contentbased_class(feature_method="movie_year", regressor_method="random_sample")
test_contentbased_class(feature_method="genres", regressor_method="random_score")
test_contentbased_class(feature_method="genres", regressor_method="random_sample")
test_contentbased_class(feature_method="rating", regressor_method="random_score")
test_contentbased_class(feature_method="rating", regressor_method="random_sample")
test_contentbased_class(feature_method="tags", regressor_method="random_score")
test_contentbased_class(feature_method="tags", regressor_method="random_sample")
test_contentbased_class(feature_method="tags_length", regressor_method="random_score")
test_contentbased_class(feature_method="tags_length", regressor_method="random_sample")
test_contentbased_class(feature_method="timestamp", regressor_method="random_score")
test_contentbased_class(feature_method="timestamp", regressor_method="random_sample")
``` ```
%% Output %% Output
user: 15 item: 942 r_ui = None est = 3.79 {'was_impossible': False} user: 11 item: 1214 r_ui = None est = 0.86 {'was_impossible': False}
user: 15 item: 942 r_ui = None est = 4.00 {'was_impossible': False} user: 11 item: 1214 r_ui = None est = 1.00 {'was_impossible': False}
user: 11 item: 1214 r_ui = None est = 4.42 {'was_impossible': False}
user: 11 item: 1214 r_ui = None est = 3.00 {'was_impossible': False}
user: 11 item: 1214 r_ui = None est = 4.53 {'was_impossible': False}
user: 11 item: 1214 r_ui = None est = 3.00 {'was_impossible': False}
user: 11 item: 1214 r_ui = None est = 0.72 {'was_impossible': False}
user: 11 item: 1214 r_ui = None est = 4.00 {'was_impossible': False}
user: 11 item: 1214 r_ui = None est = 3.33 {'was_impossible': False}
user: 11 item: 1214 r_ui = None est = 3.00 {'was_impossible': False}
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
File /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/core/indexes/base.py:3791, in Index.get_loc(self, key)
3790 try:
-> 3791 return self._engine.get_loc(casted_key)
3792 except KeyError as err:
File index.pyx:152, in pandas._libs.index.IndexEngine.get_loc()
File index.pyx:181, in pandas._libs.index.IndexEngine.get_loc()
File pandas/_libs/hashtable_class_helper.pxi:7080, in pandas._libs.hashtable.PyObjectHashTable.get_item()
File pandas/_libs/hashtable_class_helper.pxi:7088, in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'timestamp'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Cell In[44], line 33
30 test_contentbased_class(feature_method="tags_length", regressor_method="random_score")
31 test_contentbased_class(feature_method="tags_length", regressor_method="random_sample")
---> 33 test_contentbased_class(feature_method="timestamp", regressor_method="random_score")
34 test_contentbased_class(feature_method="timestamp", regressor_method="random_sample")
Cell In[44], line 7, in test_contentbased_class(feature_method, regressor_method)
5 sp_ratings = load_ratings(surprise_format=True)
6 train_set = sp_ratings.build_full_trainset()
----> 7 content_algo = ContentBased(feature_method, regressor_method)
8 content_algo.fit(train_set)
9 anti_test_set_first = train_set.build_anti_testset()[0]
Cell In[43], line 5, in ContentBased.__init__(self, features_method, regressor_method)
3 AlgoBase.__init__(self)
4 self.regressor_method = regressor_method
----> 5 self.content_features = self.create_content_features(features_method)
Cell In[43], line 33, in ContentBased.create_content_features(self, features_method)
30 df_features = df_tag['tag'].apply(lambda x: sum(len(tag) for tag in x.split(',')))
32 elif features_method == "timestamp" :
---> 33 df_features = df_items['timestamp_sin'] = np.sin(2 * np.pi * df_items['timestamp'] / 86400)
34 df_features = df_items['timestamp_cos'] = np.cos(2 * np.pi * df_items['timestamp'] / 86400)
36 else: # (implement other feature creations here)
File /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/core/frame.py:3893, in DataFrame.__getitem__(self, key)
3891 if self.columns.nlevels > 1:
3892 return self._getitem_multilevel(key)
-> 3893 indexer = self.columns.get_loc(key)
3894 if is_integer(indexer):
3895 indexer = [indexer]
File /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/core/indexes/base.py:3798, in Index.get_loc(self, key)
3793 if isinstance(casted_key, slice) or (
3794 isinstance(casted_key, abc.Iterable)
3795 and any(isinstance(x, slice) for x in casted_key)
3796 ):
3797 raise InvalidIndexError(key)
-> 3798 raise KeyError(key) from err
3799 except TypeError:
3800 # If we have a listlike key, _check_indexing_error will raise
3801 # InvalidIndexError. Otherwise we fall through and re-raise
3802 # the TypeError.
3803 self._check_indexing_error(key)
KeyError: 'timestamp'
......
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter