import datasets import pandas as pd _NEWSGROUPS = [ 'alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x', 'misc.forsale', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey', 'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.guns', 'talk.politics.mideast', 'talk.politics.misc', 'talk.religion.misc', ] _DESCRIPTION = """ The bydate version of the 20-newsgroup dataset fetched from scikit_learn and split in stratified manner into train, validation and test sets. The test set from the original 20 newsgroup dataset is retained while the original train set is split 80:20 into train and validation sets in stratified manner based on the newsgroup. The 20 different newsgroup are provided as the labels instead of config names as specified in the official huggingface dataset. Newsgroups are specified as labels to provide a simplified setup for text classification task. The 20 different newsgroup functioning as labels are: """ _DESCRIPTION += "\n".join(f"({i+1}) {j}" for i,j in enumerate(_NEWSGROUPS)) _HOMEPAGE = "http://qwone.com/~jason/20Newsgroups/" _CITATION = """ @inproceedings{Lang95, author = {Ken Lang}, title = {Newsweeder: Learning to filter netnews} year = {1995} booktitle = {Proceedings of the Twelfth International Conference on Machine Learning} pages = {331-339} } """ class Newsgroups(datasets.GeneratorBasedBuilder): VERSION = datasets.utils.Version("2.0.0") def _info(self): features = datasets.Features( { "text": datasets.Value("large_string"), "labels": datasets.features.ClassLabel(names=_NEWSGROUPS), } ) return datasets.DatasetInfo( description=_DESCRIPTION, features=features, supervised_keys=None, homepage=_HOMEPAGE, citation=_CITATION, ) def _split_generators(self, dl_manager): data_df = pd.read_csv("newsgroups.zip") train_df = data_df.query(f"split == 'train'").drop(columns="split") val_df = data_df.query(f"split == 'validation'").drop(columns="split") test_df = data_df.query(f"split == 'test'").drop(columns="split") return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"df": train_df} ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={"df": val_df} ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={"df": test_df} ), ] def _generate_examples(self, df): for idx, row in df.iterrows(): yield idx, row.to_dict()