|
|
|
|
|
import os |
|
from functools import partial |
|
from pathlib import Path |
|
from typing import Dict, Iterable |
|
|
|
import datasets |
|
from datasets import DatasetDict, DownloadManager, load_dataset |
|
import pandas as pd |
|
|
|
|
|
AVAILABLE_DATASETS = { |
|
'small': 'https://files.grouplens.org/datasets/movielens/ml-latest-small.zip', |
|
'full': 'https://files.grouplens.org/datasets/movielens/ml-latest.zip', |
|
} |
|
|
|
|
|
VERSION = datasets.Version("0.0.1") |
|
|
|
|
|
class MovielensDataset(datasets.GeneratorBasedBuilder): |
|
"""MovielensDataset dataset.""" |
|
|
|
BUILDER_CONFIGS = [ |
|
datasets.BuilderConfig( |
|
name=data_name, version=VERSION, description=f"{data_name} movielens dataset" |
|
) |
|
for data_name in AVAILABLE_DATASETS |
|
] |
|
|
|
def _info(self) -> datasets.DatasetInfo: |
|
return datasets.DatasetInfo( |
|
description="", |
|
features=datasets.Features( |
|
{ |
|
"movieId": datasets.Value("string"), |
|
"title": datasets.Value("string"), |
|
"genres": datasets.Sequence(datasets.Value("string")), |
|
"tag": datasets.Sequence(datasets.Value("string")), |
|
} |
|
), |
|
supervised_keys=None, |
|
homepage="https://grouplens.org/datasets/movielens/latest/", |
|
citation="", |
|
) |
|
|
|
def _split_generators( |
|
self, dl_manager: DownloadManager |
|
) -> Iterable[datasets.SplitGenerator]: |
|
downloader = partial( |
|
lambda split: dl_manager.download_and_extract( |
|
AVAILABLE_DATASETS[self.config.name] |
|
) |
|
) |
|
|
|
folder = os.path.splitext(os.path.basename(AVAILABLE_DATASETS[self.config.name]))[ |
|
0 |
|
] |
|
|
|
|
|
return [ |
|
datasets.SplitGenerator( |
|
name=datasets.Split.TRAIN, |
|
gen_kwargs={ |
|
"root_path": downloader("train"), |
|
"split": "train", |
|
"folder": folder, |
|
}, |
|
), |
|
] |
|
|
|
def _generate_examples( |
|
self, root_path: str, split: str, folder: str |
|
) -> Iterable[Dict]: |
|
split_path = Path(root_path) / folder |
|
movies_file = split_path / "movies.csv" |
|
movies = pd.read_csv(movies_file, sep=',', encoding='utf-8') |
|
movies['genres'] = movies['genres'].str.split('|') |
|
tags_file = split_path / "tags.csv" |
|
tags = pd.read_csv(tags_file, sep=',', encoding='utf-8') |
|
tags = tags.groupby('movieId').agg({'tag': list}).reset_index() |
|
movies = movies.merge(tags, on='movieId') |
|
for idx, row in movies.iterrows(): |
|
yield idx, { |
|
'movieId': row['movieId'], |
|
'title': row['title'], |
|
'genres': row['genres'], |
|
'tag': row['tag'], |
|
} |
|
|