Data Module Reference
This section provides a detailed API reference for all modules related to managing the datasets.
Core Data Utilities
These modules define the common utilities used by all splitters.
set_column_name(columns, value, rename=True, default_name=None)
Identifies a column by its name or index and optionally renames it.
This utility function provides a flexible way to handle DataFrame columns. It
can find a column based on its current name (string) or its position (integer).
If rename
is True, it replaces the found column name in the list of columns
with a default_name
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
columns
|
list
|
The list of current column names in the DataFrame. |
required |
value
|
Union[str, int]
|
The identifier for the column, either its name or its integer index. |
required |
rename
|
bool
|
If True, the identified column's name is
changed to |
True
|
default_name
|
str
|
The new name for the column if |
None
|
Returns:
Type | Description |
---|---|
tuple[list, str]
|
A tuple containing:
- The (potentially modified) list of column names.
- The final name of the selected column (either the original or the
|
Raises:
Type | Description |
---|---|
ValueError
|
If the |
Source code in datarec/data/utils.py
quartiles(count)
Assigns quartile indices (0-3) to items based on their frequency counts.
The function divides the input values into four quartiles using the median and quantiles. Each item is assigned an integer: 0: long tail (lowest quartile) 1: common 2: popular 3: most popular (highest quartile)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
count
|
dict
|
A dictionary mapping items to numeric counts or frequencies. |
required |
Returns:
Type | Description |
---|---|
dict
|
A dictionary mapping each item to its quartile index (0-3). |
Source code in datarec/data/utils.py
popularity(quartiles)
Categorizes items based on their quartile indices.
Converts quartile indices (0-3) into descriptive popularity categories: 0 -> 'long tail' 1 -> 'common' 2 -> 'popular' 3 -> 'most popular'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
quartiles
|
dict
|
A dictionary mapping items to quartile indices (0-3). |
required |
Returns:
Type | Description |
---|---|
dict
|
A dictionary mapping each popularity category to a list of items. |
Source code in datarec/data/utils.py
verify_checksum(file_path, checksum)
Verifies the MD5 checksum of a file.
This function computes the MD5 hash of the file at the given path and compares it to the expected checksum. If the file does not exist, a FileNotFoundError is raised. If the checksum does not match, a RuntimeError is raised indicating possible corruption or version mismatch.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file_path
|
str
|
The path to the file to verify. |
required |
checksum
|
str
|
The expected MD5 checksum. |
required |
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If the specified file does not exist. |
RuntimeError
|
If the computed checksum does not match the expected value. |
Source code in datarec/data/utils.py
Dataset wrappers
BaseTorchDataset
Bases: Dataset
Base class for Torch datasets wrapping a DataRec dataset.
Source code in datarec/data/torch_dataset.py
__init__(datarec, copy_data=False)
Initializes the BaseTorchDataset object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
datarec
|
DataRec
|
An instance of a DataRec dataset. |
required |
copy_data
|
bool
|
Whether to copy the dataset or use it by reference. |
False
|
Source code in datarec/data/torch_dataset.py
PointwiseTorchDataset
Bases: BaseTorchDataset
Torch dataset for pointwise recommendation tasks.
Source code in datarec/data/torch_dataset.py
__init__(datarec, copy_data=False)
Initializes the PointwiseTorchDataset object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
datarec
|
DataRec
|
An instance of a DataRec dataset. |
required |
copy_data
|
bool
|
Whether to copy the dataset or use it by reference. |
False
|
Source code in datarec/data/torch_dataset.py
__len__()
Returns the total number of samples in the dataset.
This is required by PyTorch's DataLoader to iterate over the dataset.
Returns:
Type | Description |
---|---|
int
|
Number of samples in the dataset. |
__getitem__(idx)
Returns a sample with user, item, and rating.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
idx
|
int
|
Sample index to be returned. |
required |
Returns:
Type | Description |
---|---|
dict
|
Sample with user, item, and rating. |
Source code in datarec/data/torch_dataset.py
PairwiseTorchDataset
Bases: BaseTorchDataset
Torch dataset for pairwise recommendation tasks with negative sampling.
Source code in datarec/data/torch_dataset.py
__init__(datarec, num_negatives=1, item_pool=None, copy_data=False)
Initializes the PairwiseTorchDataset object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
datarec
|
DataRec
|
An instance of a DataRec dataset. |
required |
num_negatives
|
int
|
Number of negative samples to generate per interaction. |
1
|
item_pool
|
array - like
|
Pool of items to sample from. Defaults to all items in the dataset. |
None
|
copy_data
|
bool
|
Whether to copy the dataset or use it by reference. |
False
|
Source code in datarec/data/torch_dataset.py
sample_negatives(user)
Samples negative items for a given user, avoiding known positive items.
This method is designed to be overridden to implement custom negative sampling strategies (e.g., popularity-based, adversarial, or distribution-aware sampling). The default implementation draws uniformly from the item pool, excluding items the user has already interacted with.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user
|
The user ID for which to sample negatives. |
required |
Returns:
Type | Description |
---|---|
List
|
List of sampled negative item IDs. |
Source code in datarec/data/torch_dataset.py
__len__()
Returns the total number of samples in the dataset.
This is required by PyTorch's DataLoader to iterate over the dataset.
Returns:
Type | Description |
---|---|
int
|
number of samples in the dataset. |
Source code in datarec/data/torch_dataset.py
__getitem__(idx)
Returns a sample with user, positive item, and negative items.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
idx
|
int
|
Sample index to be returned. |
required |
Returns:
Type | Description |
---|---|
dict
|
Sample with user, positive item, and negative items. |
Source code in datarec/data/torch_dataset.py
RankingTorchDataset
Bases: BaseTorchDataset
Torch dataset for full softmax-style ranking tasks.
Source code in datarec/data/torch_dataset.py
__init__(datarec, copy_data=False)
Initializes the RankingTorchDataset object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
datarec
|
DataRec
|
An instance of a DataRec dataset. |
required |
copy_data
|
bool
|
Whether to copy the dataset or use it by reference. |
False
|
Source code in datarec/data/torch_dataset.py
__len__()
Returns the total number of samples in the dataset.
This is required by PyTorch's DataLoader to iterate over the dataset.
Returns:
Type | Description |
---|---|
int
|
Number of samples in the dataset. |
Source code in datarec/data/torch_dataset.py
__getitem__(idx)
Returns a sample with user and item.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
idx
|
int
|
Sample index to be returned. |
required |
Returns:
Type | Description |
---|---|
dict
|
Sample with user and item data. |
Source code in datarec/data/torch_dataset.py
The DataRec class
These modules define the core part of the framework: the DataRec class.
BaseDataRecBuilder
Bases: ABC
Abstract base class for building DataRec
datasets.
This class defines the interface for preparing, downloading, and loading
datasets into DataRec
objects.
Source code in datarec/data/datarec_builder.py
prepare()
abstractmethod
load()
abstractmethod
prepare_and_load()
A convenience method that runs the full prepare and load pipeline.
Returns:
Type | Description |
---|---|
DataRec
|
The fully prepared and loaded dataset. |
DataRec
Core data structure for recommendation datasets in the DataRec framework.
This class wraps a Pandas DataFrame and standardizes common columns (user, item, rating, timestamp) to provide a consistent interface for recommendation tasks. It supports data preprocessing, user/item remapping (public vs private IDs), frequency analysis, sparsity/density metrics, Gini coefficients, and conversion into PyTorch datasets for training.
Source code in datarec/data/dataset.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 |
|
data
property
writable
The underlying pandas DataFrame holding the interaction data.
user_col
property
writable
The name of the user ID column.
item_col
property
writable
The name of the item ID column.
rating_col
property
writable
The name of the rating column.
timestamp_col
property
writable
The name of the timestamp column.
users
property
Returns a list of unique user IDs in the dataset.
items
property
Returns a list of unique item IDs in the dataset.
n_users
property
Returns the number of unique users.
n_items
property
Returns the number of unique items.
columns
property
writable
Returns the list of column names of the internal DataFrame.
sorted_items
property
Returns a dictionary of items sorted by their interaction count.
sorted_users
property
Returns a dictionary of users sorted by their interaction count.
transactions
property
Returns the total number of interactions (rows) in the dataset.
space_size
property
Calculates the scaled square root of the user-item interaction space.
space_size_log
property
Calculates the log10 of the space_size metric.
shape
property
Calculates the shape of the interaction matrix (n_users / n_items).
shape_log
property
Calculates the log10 of the shape metric.
density
property
Calculates the density of the user-item interaction matrix.
density_log
property
Calculates the log10 of the density metric.
gini_item
property
Calculates the Gini coefficient for item popularity.
gini_user
property
Calculates the Gini coefficient for user activity.
ratings_per_user
property
Calculates the average number of ratings per user.
ratings_per_item
property
Calculates the average number of ratings per item.
__init__(rawdata=None, copy=False, dataset_name='datarec', version_name='no_version_provided', pipeline=None, *args, **kwargs)
Initializes the DataRec object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
rawdata
|
RawData
|
The input dataset wrapped in a RawData object. If None, the DataRec is initialized empty. |
None
|
copy
|
bool
|
Whether to copy the input DataFrame to avoid modifying the original RawData. |
False
|
dataset_name
|
str
|
A name to identify the dataset. |
'datarec'
|
version_name
|
str
|
A version identifier for the dataset. |
'no_version_provided'
|
pipeline
|
Pipeline
|
A pipeline object to track preprocessing steps. |
None
|
Source code in datarec/data/dataset.py
__str__()
Returns 'self.data' as a string variable.
Returns:
Type | Description |
---|---|
str
|
'self.data' as a string variable. |
__repr__()
__len__()
Returns the total number of samples in the dataset.
Returns:
Type | Description |
---|---|
int
|
number of samples in the dataset. |
set_columns(rawdata)
Assign dataset column names from a RawData object and reorder the data accordingly.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
rawdata
|
RawData
|
A RawData object containing the column names for user, item, rating, and timestamp. |
required |
Source code in datarec/data/dataset.py
reset()
Reset cached statistics and assigned columns of the DataRec object.
This method clears all precomputed dataset statistics (e.g., sorted users, density, Gini indices, shape, ratings per user/item) and empties the list of assigned columns. It is automatically called when the underlying data is changed.
Source code in datarec/data/dataset.py
set_user_col(value=DATAREC_USER_COL, rename=True)
Identifies and optionally renames the user column.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
Union[str, int]
|
The current name or index of the user column. |
DATAREC_USER_COL
|
rename
|
bool
|
If True, renames the column to the standard internal name. |
True
|
Source code in datarec/data/dataset.py
set_item_col(value=DATAREC_ITEM_COL, rename=True)
Identifies and optionally renames the item column.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
Union[str, int]
|
The current name or index of the item column. |
DATAREC_ITEM_COL
|
rename
|
bool
|
If True, renames the column to the standard internal name. |
True
|
Source code in datarec/data/dataset.py
set_rating_col(value=DATAREC_RATING_COL, rename=True)
Identifies and optionally renames the rating column.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
Union[str, int]
|
The current name or index of the rating column. |
DATAREC_RATING_COL
|
rename
|
bool
|
If True, renames the column to the standard internal name. |
True
|
Source code in datarec/data/dataset.py
set_timestamp_col(value=DATAREC_TIMESTAMP_COL, rename=True)
Identifies and optionally renames the timestamp column.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
Union[str, int]
|
The current name or index of the timestamp column. |
DATAREC_TIMESTAMP_COL
|
rename
|
bool
|
If True, renames the column to the standard internal name. |
True
|
Source code in datarec/data/dataset.py
public_to_private(lst, offset=0)
staticmethod
Creates a mapping from public (original) IDs to private (integer) IDs.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
lst
|
list
|
A list of public IDs. |
required |
offset
|
int
|
The starting integer for the private IDs. |
0
|
Returns:
Type | Description |
---|---|
dict
|
A dictionary mapping public IDs to private integer IDs. |
Source code in datarec/data/dataset.py
private_to_public(pub_to_prvt)
staticmethod
Creates a reverse mapping from private IDs back to public IDs.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pub_to_prvt
|
dict
|
A dictionary mapping public IDs to private IDs. |
required |
Returns:
Type | Description |
---|---|
dict
|
A dictionary mapping private IDs to public IDs. |
Source code in datarec/data/dataset.py
map_users_and_items(offset=0, items_shift=False)
Generates the public-to-private and private-to-public ID mappings.
This method creates the dictionaries needed to convert user and item IDs to a dense, zero-indexed integer range suitable for machine learning models.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
offset
|
int
|
The starting integer for the ID mappings. Defaults to 0. |
0
|
items_shift
|
bool
|
If True, item private IDs will start after the last user private ID, creating a single contiguous ID space. Defaults to False. |
False
|
Source code in datarec/data/dataset.py
map_dataset(user_mapping, item_mapping)
Applies ID mappings to the user and item columns of the DataFrame.
This is an in-place operation that modifies the internal DataFrame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_mapping
|
dict
|
The dictionary to map user IDs. |
required |
item_mapping
|
dict
|
The dictionary to map item IDs. |
required |
Source code in datarec/data/dataset.py
to_public()
Converts user and item IDs back to their original (public) values.
to_private()
Converts user and item IDs to their dense, zero-indexed (private) integer values.
Source code in datarec/data/dataset.py
get_metric(metric)
Retrieves a calculated dataset metric by name.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
metric
|
str
|
The name of the metric to compute (e.g., 'density', 'gini_user'). |
required |
Returns:
Type | Description |
---|---|
The value of the computed metric. |
Source code in datarec/data/dataset.py
gini(x)
staticmethod
Calculates the Gini coefficient for a numpy array.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
ndarray
|
An array of non-negative values. |
required |
Returns:
Type | Description |
---|---|
float
|
The Gini coefficient, a measure of inequality. |
Source code in datarec/data/dataset.py
users_frequency()
Computes the absolute frequency of each user in the dataset.
Returns:
Type | Description |
---|---|
dict
|
A dictionary mapping user IDs to the number of interactions, sorted in descending order of frequency. |
Source code in datarec/data/dataset.py
users_relative_frequency()
Computes the relative frequency of each user in the dataset.
Returns:
Type | Description |
---|---|
dict
|
A dictionary mapping user IDs to their relative frequency (fraction of total transactions). |
Source code in datarec/data/dataset.py
items_frequency()
Computes the absolute frequency of each item in the dataset.
Returns:
Type | Description |
---|---|
dict
|
A dictionary mapping item IDs to the number of interactions, sorted in descending order of frequency. |
Source code in datarec/data/dataset.py
items_relative_frequency()
Computes the relative frequency of each item in the dataset.
Returns:
Type | Description |
---|---|
dict
|
A dictionary mapping item IDs to their relative frequency (fraction of total transactions). |
Source code in datarec/data/dataset.py
users_quartiles()
Assigns quartile indices to users based on their frequency.
Returns:
Type | Description |
---|---|
dict
|
A dictionary mapping each user ID to a quartile index (0-3), where 0 = lowest, 3 = highest frequency. |
Source code in datarec/data/dataset.py
items_quartiles()
Assigns quartile indices to items based on their frequency.
Returns:
Type | Description |
---|---|
dict
|
A dictionary mapping each item ID to a quartile index (0-3), where 0 = lowest, 3 = highest frequency. |
Source code in datarec/data/dataset.py
users_popularity()
Categorizes users into descriptive popularity groups based on quartiles.
Returns:
Type | Description |
---|---|
dict
|
A dictionary mapping popularity categories ('long tail', 'common', 'popular', 'most popular') to lists of user IDs. |
Source code in datarec/data/dataset.py
items_popularity()
Categorizes items into descriptive popularity groups based on quartiles.
Returns:
Type | Description |
---|---|
dict
|
A dictionary mapping popularity categories ('long tail', 'common', 'popular', 'most popular') to lists of item IDs. |
Source code in datarec/data/dataset.py
copy()
Create a deep copy of the current DataRec object.
This method duplicates the DataRec instance, including its data, metadata (user, item, rating, timestamp columns), pipeline, and internal state such as privacy settings and implicit flags.
Returns:
Type | Description |
---|---|
DataRec
|
A new DataRec object that is a deep copy of the current instance. |
Source code in datarec/data/dataset.py
to_rawdata()
Convert the current DataRec object into a RawData object.
This method creates a RawData instance containing the same data and metadata (user, item, rating, timestamp columns) as the DataRec object.
Returns:
Type | Description |
---|---|
RawData
|
A new RawData object containing the DataRec's data and column information. |
Source code in datarec/data/dataset.py
save_pipeline(filepath)
Save the current processing pipeline to a YAML file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
str
|
The path (including filename) where the pipeline YAML file will be saved. |
required |
Source code in datarec/data/dataset.py
to_torch_dataset(task='pointwise', autoprepare=True, **kwargs)
Converts the current DataRec object into a PyTorch-compatible dataset.
This method prepares the dataset (e.g., remaps user/item IDs to a dense index space)
and returns a torch.utils.data.Dataset
object suitable for training with PyTorch.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
str
|
The recommendation task type. Must be one of: - "pointwise": returns PointwiseTorchDataset - "pairwise": returns PairwiseTorchDataset - "ranking": returns RankingTorchDataset |
'pointwise'
|
autoprepare
|
bool
|
If True, automatically applies user/item remapping and switches the dataset to private IDs. If False, assumes the dataset is already properly prepared. |
True
|
**kwargs
|
Additional arguments passed to the specific torch dataset class. |
{}
|
Returns:
Type | Description |
---|---|
Dataset
|
A PyTorch dataset instance corresponding to the selected task. |
Raises:
Type | Description |
---|---|
ImportError
|
If PyTorch is not installed. |
ValueError
|
If an unknown task name is provided. |
Source code in datarec/data/dataset.py
share_info(datarec_source, datarec_target)
Copy dataset metadata and mappings from one DataRec object to another
This function transfers core attributes from a source DataRec to a target DataRec.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
datarec_source
|
DataRec
|
The source DataRec from which information is copied. |
required |
datarec_target
|
DataRec
|
The target DataRec that will be updated with the source information. |
required |