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

jupyter notebook

parent 1eb8178c
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
Pipeline #47668 annulé
%% Cell type:code id: tags:
``` python
#reloads modules automatically before entering the execution of code
# %load_ext autoreload
# %autoreload 2
# third parties imports
import numpy as np
import pandas as pd
import re
from constants import Constant as C
from loaders import load_ratings
from loaders import load_items
load_items()
load_ratings()
```
%% Output
Display the ratings
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[12], line 10
8 import re
9 from constants import Constant as C
---> 10 from loaders import load_ratings
11 from loaders import load_items
13 load_items()
File ~/vscodeworkspace/recomsys/Analytics_UI/loaders.py:41
39 print("\n")
40 print("Display the ratings")
---> 41 pp(load_ratings())
42 print("\n\n")
43 print("Display the movie data")
File ~/vscodeworkspace/recomsys/Analytics_UI/loaders.py:12, in load_ratings(surprise_format)
11 def load_ratings(surprise_format=False):
---> 12 df_ratings = pd.read_csv(C.EVIDENCE_PATH / C.RATINGS_FILENAME)
13 if surprise_format:
14 pass
File /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/io/parsers/readers.py:948, in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, date_format, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options, dtype_backend)
935 kwds_defaults = _refine_defaults_read(
936 dialect,
937 delimiter,
(...)
944 dtype_backend=dtype_backend,
945 )
946 kwds.update(kwds_defaults)
--> 948 return _read(filepath_or_buffer, kwds)
File /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/io/parsers/readers.py:611, in _read(filepath_or_buffer, kwds)
608 _validate_names(kwds.get("names", None))
610 # Create the parser.
--> 611 parser = TextFileReader(filepath_or_buffer, **kwds)
613 if chunksize or iterator:
614 return parser
File /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/io/parsers/readers.py:1448, in TextFileReader.__init__(self, f, engine, **kwds)
1445 self.options["has_index_names"] = kwds["has_index_names"]
1447 self.handles: IOHandles | None = None
-> 1448 self._engine = self._make_engine(f, self.engine)
File /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/io/parsers/readers.py:1705, in TextFileReader._make_engine(self, f, engine)
1703 if "b" not in mode:
1704 mode += "b"
-> 1705 self.handles = get_handle(
1706 f,
1707 mode,
1708 encoding=self.options.get("encoding", None),
1709 compression=self.options.get("compression", None),
1710 memory_map=self.options.get("memory_map", False),
1711 is_text=is_text,
1712 errors=self.options.get("encoding_errors", "strict"),
1713 storage_options=self.options.get("storage_options", None),
1714 )
1715 assert self.handles is not None
1716 f = self.handles.handle
File /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/io/common.py:863, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)
858 elif isinstance(handle, str):
859 # Check whether the filename is to be opened in binary mode.
860 # Binary mode does not support 'encoding' and 'newline'.
861 if ioargs.encoding and "b" not in ioargs.mode:
862 # Encoding
--> 863 handle = open(
864 handle,
865 ioargs.mode,
866 encoding=ioargs.encoding,
867 errors=errors,
868 newline="",
869 )
870 else:
871 # Binary mode
872 handle = open(handle, ioargs.mode)
FileNotFoundError: [Errno 2] No such file or directory: 'data/small/evidence/ratings.csv'
%% Cell type:code id: tags:
``` python
# NUMBER OF MOVIES
df_movies = pd.read_csv("data/small/content/movies.csv")
n_movies = df_movies['title'].nunique()
print("\n")
print(f"Number of movies: {n_movies}")
```
%% Output
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[10], line 2
1 # NUMBER OF MOVIES
----> 2 df_movies = pd.read_csv("data/small/content/movies.csv")
3 n_movies = df_movies['title'].nunique()
5 print("\n")
File /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/io/parsers/readers.py:948, in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, date_format, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options, dtype_backend)
935 kwds_defaults = _refine_defaults_read(
936 dialect,
937 delimiter,
(...)
944 dtype_backend=dtype_backend,
945 )
946 kwds.update(kwds_defaults)
--> 948 return _read(filepath_or_buffer, kwds)
File /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/io/parsers/readers.py:611, in _read(filepath_or_buffer, kwds)
608 _validate_names(kwds.get("names", None))
610 # Create the parser.
--> 611 parser = TextFileReader(filepath_or_buffer, **kwds)
613 if chunksize or iterator:
614 return parser
File /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/io/parsers/readers.py:1448, in TextFileReader.__init__(self, f, engine, **kwds)
1445 self.options["has_index_names"] = kwds["has_index_names"]
1447 self.handles: IOHandles | None = None
-> 1448 self._engine = self._make_engine(f, self.engine)
File /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/io/parsers/readers.py:1705, in TextFileReader._make_engine(self, f, engine)
1703 if "b" not in mode:
1704 mode += "b"
-> 1705 self.handles = get_handle(
1706 f,
1707 mode,
1708 encoding=self.options.get("encoding", None),
1709 compression=self.options.get("compression", None),
1710 memory_map=self.options.get("memory_map", False),
1711 is_text=is_text,
1712 errors=self.options.get("encoding_errors", "strict"),
1713 storage_options=self.options.get("storage_options", None),
1714 )
1715 assert self.handles is not None
1716 f = self.handles.handle
File /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/io/common.py:863, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)
858 elif isinstance(handle, str):
859 # Check whether the filename is to be opened in binary mode.
860 # Binary mode does not support 'encoding' and 'newline'.
861 if ioargs.encoding and "b" not in ioargs.mode:
862 # Encoding
--> 863 handle = open(
864 handle,
865 ioargs.mode,
866 encoding=ioargs.encoding,
867 errors=errors,
868 newline="",
869 )
870 else:
871 # Binary mode
872 handle = open(handle, ioargs.mode)
FileNotFoundError: [Errno 2] No such file or directory: 'data/small/content/movies.csv'
%% Cell type:code id: tags:
``` python
# THE YEAR RANGE
df_movies['annee'] = df_movies['title'].str.extract(r'\((.{4})\)')
df_movies['annee'] = pd.to_numeric(df_movies['annee'], errors='coerce')
# Trouver le range minimum et maximum
min_range = int(df_movies['annee'].min())
max_range = int(df_movies['annee'].max())
# Afficher le range minimum et maximum
print("\n")
print(f"Minimum range: {min_range}")
print(f"Maximum range: {max_range}")
```
%% Cell type:code id: tags:
``` python
# LIST OF MOVIE GENRES
df_movies['genres'] = df_movies['genres'].str.split('|')
df_movies = df_movies.explode('genres')
# Afficher tous les genres uniques
unique_genres = sorted(df_movies['genres'].unique())
print("List of all genres:")
for genre in unique_genres:
print(genre, "|", end = " ")
```
%% Cell type:code id: tags:
``` python
# THE TOTAL NUMBER OF RATINGS
df_ratings = pd.read_csv("data/small/evidence/ratings.csv")
n_ratings = df_ratings['rating'].count()
print(f"Number of ratings: {n_ratings}")
```
%% Cell type:code id: tags:
``` python
# THE NUMBER OF UNIQUE USERS
df_ratings = pd.read_csv("data/small/evidence/ratings.csv")
n_users = df_ratings['userId'].nunique()
print(f"Number of users: {n_users}")
```
%% Cell type:code id: tags:
``` python
# THE NUMBER OF UNIQUE MOVIES (IN THE RATING MATRIX)
```
%% Cell type:code id: tags:
``` python
# THE NUMBER OF RATINGS OF THE MOST RATED MOVIES
def most_rated_movies_ratings_count(csv_file):
# Charger le DataFrame des évaluations à partir du fichier CSV
df_ratings = pd.read_csv(csv_file)
# Grouper les évaluations par 'movieId' et compter le nombre de notes pour chaque film
movie_ratings_count = df_ratings.groupby('movieId')['rating'].count()
# Trouver le(s) film(s) le(s) plus évalué(s)
most_rated_movies = movie_ratings_count[movie_ratings_count == movie_ratings_count.max()]
# Afficher le nombre de notes du film (ou des films) le(s) plus évalué(s)
print("Number of ratings of the most rated movie(s):", most_rated_movies.max())
# Exemple d'utilisation de la fonction avec le chemin du fichier CSV
most_rated_movies_ratings_count("data/small/evidence/ratings.csv")
```
%% Cell type:code id: tags:
``` python
# THE NUMBER OF RATINGS OF THE LESS RATED MOVIES
def least_rated_movies_ratings_count(csv_file):
# Charger le DataFrame des évaluations à partir du fichier CSV
df_ratings = pd.read_csv(csv_file)
# Grouper les évaluations par 'movieId' et compter le nombre de notes pour chaque film
movie_ratings_count = df_ratings.groupby('movieId')['rating'].count()
# Trouver le(s) film(s) le(s) moins évalué(s)
least_rated_movies = movie_ratings_count[movie_ratings_count == movie_ratings_count.min()]
# Afficher le nombre de notes du film (ou des films) le(s) moins évalué(s)
print("Number of ratings of the least rated movie(s):", least_rated_movies.min())
# Exemple d'utilisation de la fonction avec le chemin du fichier CSV
least_rated_movies_ratings_count("data/small/evidence/ratings.csv")
```
%% Cell type:code id: tags:
``` python
# ALL THE POSSIBLE RATING VALUES; FROM THE SMALLEST VALUE TO THE VALUE HIGHEST
def all_possible_ratings(csv_file):
# Charger le DataFrame des évaluations à partir du fichier CSV
df_ratings = pd.read_csv(csv_file)
# Obtenir toutes les valeurs de notation uniques
rating_values = sorted(df_ratings['rating'].unique())
# Afficher toutes les valeurs de notation possibles
print("All possible rating values, from smallest to highest:")
for rating in rating_values:
print(rating)
# Exemple d'utilisation de la fonction avec le chemin du fichier CSV
all_possible_ratings("data/small/evidence/ratings.csv")
```
%% Cell type:code id: tags:
``` python
# THE NUMBER OF MOVIES THAT WERE NOT RATED AT ALL
def unrated_movies_count(ratings_csv, movies_csv):
# Charger les DataFrames des évaluations et des films à partir des fichiers CSV
df_ratings = pd.read_csv(ratings_csv)
df_movies = pd.read_csv(movies_csv)
# Obtenir la liste de tous les films présents dans le fichier de notation
rated_movies = df_ratings['movieId'].unique()
# Comparer la liste des films notés à la liste complète des films pour obtenir les films non notés
unrated_movies_count = df_movies[~df_movies['movieId'].isin(rated_movies)].shape[0]
# Afficher le nombre de films non notés
print("Number of movies that were not rated at all:", unrated_movies_count)
# Exemple d'utilisation de la fonction avec les chemins des fichiers CSV des évaluations et des films
unrated_movies_count("data/small/evidence/ratings.csv", "data/small/content/movies.csv")
```
......@@ -62,6 +62,84 @@ print(f"Number of users: {n_users}")
print("\n","C")
print("\n","D")
def most_rated_movies_ratings_count(csv_file):
# Charger le DataFrame des évaluations à partir du fichier CSV
df_ratings = pd.read_csv(csv_file)
# Grouper les évaluations par 'movieId' et compter le nombre de notes pour chaque film
movie_ratings_count = df_ratings.groupby('movieId')['rating'].count()
# Trouver le(s) film(s) le(s) plus évalué(s)
most_rated_movies = movie_ratings_count[movie_ratings_count == movie_ratings_count.max()]
# Afficher le nombre de notes du film (ou des films) le(s) plus évalué(s)
print("Number of ratings of the most rated movie(s):", most_rated_movies.max())
# Exemple d'utilisation de la fonction avec le chemin du fichier CSV
most_rated_movies_ratings_count("data/small/evidence/ratings.csv")
print("\n","E")
def least_rated_movies_ratings_count(csv_file):
# Charger le DataFrame des évaluations à partir du fichier CSV
df_ratings = pd.read_csv(csv_file)
# Grouper les évaluations par 'movieId' et compter le nombre de notes pour chaque film
movie_ratings_count = df_ratings.groupby('movieId')['rating'].count()
# Trouver le(s) film(s) le(s) moins évalué(s)
least_rated_movies = movie_ratings_count[movie_ratings_count == movie_ratings_count.min()]
# Afficher le nombre de notes du film (ou des films) le(s) moins évalué(s)
print("Number of ratings of the least rated movie(s):", least_rated_movies.min())
# Exemple d'utilisation de la fonction avec le chemin du fichier CSV
least_rated_movies_ratings_count("data/small/evidence/ratings.csv")
print("\n","F")
def all_possible_ratings(csv_file):
# Charger le DataFrame des évaluations à partir du fichier CSV
df_ratings = pd.read_csv(csv_file)
# Obtenir toutes les valeurs de notation uniques
rating_values = sorted(df_ratings['rating'].unique())
# Afficher toutes les valeurs de notation possibles
print("All possible rating values, from smallest to highest:")
for rating in rating_values:
print(rating)
# Exemple d'utilisation de la fonction avec le chemin du fichier CSV
all_possible_ratings("data/small/evidence/ratings.csv")
print("\n","G")
def unrated_movies_count(ratings_csv, movies_csv):
# Charger les DataFrames des évaluations et des films à partir des fichiers CSV
df_ratings = pd.read_csv(ratings_csv)
df_movies = pd.read_csv(movies_csv)
# Obtenir la liste de tous les films présents dans le fichier de notation
rated_movies = df_ratings['movieId'].unique()
# Comparer la liste des films notés à la liste complète des films pour obtenir les films non notés
unrated_movies_count = df_movies[~df_movies['movieId'].isin(rated_movies)].shape[0]
# Afficher le nombre de films non notés
print("Number of movies that were not rated at all:", unrated_movies_count)
# Exemple d'utilisation de la fonction avec les chemins des fichiers CSV des évaluations et des films
unrated_movies_count("data/small/evidence/ratings.csv", "data/small/content/movies.csv")
# -- display relevant informations that can be extracted from the dataset
......
# recomsys
# Group 5 - Movie Recommender System
Welcome in the README file :)
Write here a few introduction words for your project.
If you want inspiration on how to write an awesome README, check this github repo : https://github.com/navendu-pottekkat/awesome-readme . But don't spend to much time on it. This is not the topic of this course.
## Getting started
If you need help with the Markdown syntax, you might find some help here : https://www.markdownguide.org/basic-syntax/ .
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://forge.uclouvain.be/recommender_system/recomsys.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://forge.uclouvain.be/recommender_system/recomsys/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
Good luck with your project.
May the force be with you.
\ No newline at end of file
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