Data Module Reference
This section provides a detailed API reference for the datarec.data package, which
defines the core dataset abstraction, dataset builders, and supporting utilities.
On This Page
Core Data Utilities
Utilities shared across the data layer (encoders, helpers, characteristics helpers).
Encoder
A simple encoder class to encode and decode IDs.
Source code in datarec/data/utils.py
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 | |
is_encoded()
Checks if the encoding dictionary is not empty.
Returns:
| Type | Description |
|---|---|
bool
|
True if the encoding dictionary is not empty, False otherwise. |
build_encoding(lst, offset=0)
Encodes a list of public IDs into 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
|
Source code in datarec/data/utils.py
reset_encoding()
change_offset(offset)
Changes the offset of the current encoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
offset
|
int
|
The new starting integer for the private IDs. |
required |
Source code in datarec/data/utils.py
apply_encoding(encoding)
Applies an external encoding dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoding
|
dict
|
A dictionary encoding IDs. |
required |
Source code in datarec/data/utils.py
encode(lst)
Encodes a list of public IDs into integer IDs using the built encoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lst
|
list
|
A list of public IDs. |
required |
Returns:
| Type | Description |
|---|---|
list
|
A list of encoded integer IDs. |
Source code in datarec/data/utils.py
decode(lst)
Creates a reverse mapping from private IDs back to public IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lst
|
list
|
A list of private IDs. |
required |
Returns:
| Type | Description |
|---|---|
list
|
A list of decoded public IDs. |
Source code in datarec/data/utils.py
IncrementalEncoder
Streaming-friendly encoder that assigns integer IDs incrementally.
Preserves reproducibility by keeping both forward (public -> int) and reverse (int -> public) mappings without requiring the full list upfront.
Source code in datarec/data/utils.py
encode_one(key)
Encode a single key, creating a new id if unseen.
Source code in datarec/data/utils.py
encode_many(iterable)
decode_one(idx)
Decode a single id back to the original key.
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 Builders
Dataset builder used by the registry to prepare and load resources.
RegisteredDataset
Source code in datarec/data/datarec_builder.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 | |
from_url(url, folder=None)
classmethod
Build a RegisteredDataset from a remote registry YAML.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to a registry version YAML. |
required |
folder
|
str | None
|
Optional output folder override. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
RegisteredDataset |
An instance backed by the remote registry config. |
Source code in datarec/data/datarec_builder.py
prepare(*, only_required=True, use_cache=True, resource_types=None, resource_names=None)
Prepare (download and decompress) all selected resources. Args: only_required (bool): Prepare only resources marked as required when True. use_cache (bool): Use cached resources when True. resource_types (Collection[str] | str | None): Resource types to include; all when None. resource_names (Collection[str] | str | None): Specific resource names to include; all when None. Returns: dict[str, Any]: Map from resource name to the prepared artifact (e.g. local path).
Source code in datarec/data/datarec_builder.py
prepare_interactions(*, only_required=True, use_cache=True, resource_names=None)
Prepare (download and decompress) ratings resources. Args: only_required (bool): Prepare only resources marked as required when True. use_cache (bool): Use cached resources when True. resource_names (Collection[str] | str | None): Specific resource names to include; all when None. Returns: dict[str, Any]: Map from resource name to the prepared artifact (e.g. local path).
Source code in datarec/data/datarec_builder.py
load(*, use_cache=False, to_cache=False, resource_name=None, resource_type='interactions', only_required=False)
Load the dataset into a DataRec object. Args: use_cache (bool): Load from cache when True. to_cache (bool): Save to cache when True. resource_name (str | None): Specific resource name to load; all when None. resource_type (str | None): Resource type to load; all when None. only_required (bool): When True, consider only resources marked as required. Returns: DataRec: The loaded dataset.
Source code in datarec/data/datarec_builder.py
prepare_and_load()
A convenience method that runs the full prepare and load pipeline.
Returns:
| Type | Description |
|---|---|
DataRec
|
The fully prepared and loaded dataset. |
prepare_content(ctype='all')
Prepares content resources of the specified type. Args: ctype (str): The type of content to prepare. Use 'all' to prepare all content types. Raises: AssertionError: If the specified content type is not found. Returns: (None): None
Source code in datarec/data/datarec_builder.py
download()
Downloads the raw dataset files. Returns: (str): The path to the downloaded files.
Source code in datarec/data/datarec_builder.py
find_output_folder(folder=None)
Find the output folder for the given dataset and version. Args: folder (str): Explicit output folder path. Returns: (str): The output folder path.
Source code in datarec/data/datarec_builder.py
DataRec and Data Wrappers
Core dataset container and helpers.
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
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 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 | |
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.
origin
property
Returns the origin of the dataset (e.g., 'unknown', 'registry', 'file').
__init__(rawdata=None, copy=False, dataset_name='datarec', version_name='no_version_provided', *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. |
required |
registry_dataset
|
bool
|
Whether the DataRec derives from a registered dataset. |
required |
Source code in datarec/data/dataset.py
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 | |
__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
is_encoded(on)
Checks if user or item IDs are encoded to private integer IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on
|
str
|
'users' to check user encoding, 'items' for item encoding. |
required |
Returns: (bool): True if the specified IDs are encoded, False otherwise.
Source code in datarec/data/dataset.py
encode(users=True, items=True)
Converts user and item IDs to encoded integer IDs. Args: users (bool): If True, encodes user IDs. items (bool): If True, encodes item IDs.
Source code in datarec/data/dataset.py
decode(users=True, items=True)
Converts user and item IDs back to original IDs. Args: users (bool): If True, encodes user IDs. items (bool): If True, encodes item IDs.
Source code in datarec/data/dataset.py
reset_encoding(on='all')
Resets the encoding for users or items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on
|
str
|
'users' to reset user encoding, 'items' for item encoding. |
'all'
|
Source code in datarec/data/dataset.py
build_encoding(on='users', offset=0)
Builds the encoding for users or items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on
|
str
|
'users' to build user encoding, 'items' for item encoding, 'all' for both. |
'users'
|
offset
|
int
|
The starting integer for the private IDs. |
0
|
Source code in datarec/data/dataset.py
characteristic(name, **kwargs)
Retrieves a calculated dataset characteristic by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the characteristic to retrieve. |
required |
**kwargs
|
Any
|
Additional arguments to pass to the characteristic function. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The value of the requested characteristic. |
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
get_user_interactions(user_id)
Retrieves all interactions for a specific user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
Any
|
The ID of the user whose interactions are to be retrieved. |
required |
Source code in datarec/data/dataset.py
get_item_interactions(item_id)
Retrieves all interactions for a specific item.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item_id
|
Any
|
The ID of the item whose interactions are to be retrieved. |
required |
Source code in datarec/data/dataset.py
list_characteristics()
describe_characteristics()
Return a mapping name -> short docstring for each available characteristic.
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
set_origin_file(pipeline_step)
Set the origin of the dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
origin
|
str
|
A string describing the origin of the dataset (e.g., 'registry', 'file', 'unknown'). |
required |
Source code in datarec/data/dataset.py
set_origin_registry()
Set the origin of the dataset to 'registry'.
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
|
Any
|
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
to_graphrec()
Converts the current DataRec object into a GraphRec object.
This method creates a GraphRec instance representing the bipartite graph of user-item interactions contained in the DataRec object.
Returns:
| Type | Description |
|---|---|
GraphRec
|
A new GraphRec object representing the interaction graph. |
Source code in datarec/data/dataset.py
to_pickle(filepath='')
Save the current DataRec object to a pickle file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
The path (including filename) where the pickle file will be saved. |
''
|
Source code in datarec/data/dataset.py
CharacteristicAccessor
Accessor for dataset characteristics. Allows dynamic retrieval of dataset characteristics as attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dr
|
DataRec
|
The DataRec object to access characteristics from. |
required |
Source code in datarec/data/dataset.py
from_pickle(dataset_name='', version_name='', filepath='')
Load a DataRec object from a pickle file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
The name of the dataset. |
''
|
version_name
|
str
|
The version identifier of the dataset. |
''
|
filepath
|
str
|
The path to the pickle file. |
''
|
Returns: (DataRec): The loaded DataRec object.
Source code in datarec/data/dataset.py
Source
dataclass
Source code in datarec/data/source.py
is_locally_available(output_folder=None)
Check if the source file exists in the output folder.
Source code in datarec/data/source.py
prepare()
Prepares the source by downloading it if not available locally and verifying its checksum. Returns: (None)
Source code in datarec/data/source.py
resource_paths()
Returns a dictionary containing the paths of the resources inside the source. Returns: (dict): A dictionary containing the paths of the resources inside the source.
Source code in datarec/data/source.py
resources_available()
Check if all resources inside the source are available locally. Returns: (bool): True if all resources are available, False otherwise.
Source code in datarec/data/source.py
get_resources(force=False)
Returns a dictionary containing the paths of the resources inside the source. Args: force (bool): If True, forces re-extraction of resources even if they are already available. Returns: (dict): A dictionary containing the paths of the resources inside the source.
Source code in datarec/data/source.py
NestedSource
dataclass
Bases: Source
Source code in datarec/data/source.py
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 | |
link_parent_source(sources)
Links the resource to its source. Args: sources (dict): A dictionary containing dataset sources objects. Returns: (None): None
Source code in datarec/data/source.py
prepare()
Prepares the source by downloading it if not available locally and verifying its checksum. Returns: (None)
Source code in datarec/data/source.py
set_source(source_name, source_conf)
Given a resource configuration, return a new resource object Args: resource_name (str): name of the resource raw_resource (dict): resource configuration Returns: (Source): a dataset source object
Source code in datarec/data/source.py
set_sources(config, folder=None)
Given a dataset configuration, return a new dataset configuration Args: config (dict): dataset configuration folder (str): source output folder Returns: (dict): a dictionary containing dataset sources objects
Source code in datarec/data/source.py
Resource
dataclass
Source code in datarec/data/resource.py
link_source(sources)
Links the resource to its source. Args: sources (dict): A dictionary containing dataset sources objects. Returns: (None): None
Source code in datarec/data/resource.py
is_locally_available()
Checks if the resource file is available locally. Returns: (str): The local path of the resource file if available, otherwise False.
Source code in datarec/data/resource.py
prepare(*args, **kwargs)
Ensures the resource file is downloaded and available locally.
Source code in datarec/data/resource.py
path()
Returns the local path of the resource file. Raises an error if the output folder is not specified. Returns: (str): The local path of the resource file.
Source code in datarec/data/resource.py
assign_dataset_info(dataset_name, version)
Assigns dataset name and version to the resource. Args: dataset_name (str): The name of the dataset. version (str): The version of the dataset. Returns: (None): None
Source code in datarec/data/resource.py
Interactions
dataclass
Bases: Resource
Source code in datarec/data/resource.py
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 | |
cache_path()
Returns the path of the cached version of the resource. Returns: (str): The path of the cached resource file.
Source code in datarec/data/resource.py
prepare(use_cache=True, *args, **kwargs)
Prepares the resource by ensuring it is downloaded and available locally. If a cached version exists, it skips downloading.
Source code in datarec/data/resource.py
load(use_cache=True, to_cache=True)
Loads the ratings resource into a DataRec dataset. Returns: DataRec: The loaded dataset.
Source code in datarec/data/resource.py
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 | |
free_cache()
Frees the cached version of the resource if it exists. Returns: (None): None
Source code in datarec/data/resource.py
load_dataset_config(dataset_name, dataset_version='')
Load a dataset configuration from the local registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
name of the dataset |
required |
dataset_version
|
str
|
version of the dataset. When empty, load the dataset-level registry file. |
''
|
Returns: (dict): dataset configuration
Source code in datarec/data/resource.py
load_dataset_config_from_url(url)
Load a dataset configuration YAML from a remote URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL pointing to a registry dataset or version YAML. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Parsed dataset configuration. |
Source code in datarec/data/resource.py
set_resource(resource_name, resource_conf)
Given a resource configuration, return a new resource object Args: resource_name (str): name of the resource resource_conf (dict): resource configuration Returns: (Resource): a dataset resource object
Source code in datarec/data/resource.py
set_resources(config)
Given a dataset configuration, return a new dataset configuration Args: config (dict): dataset configuration Returns: (dict): a dictionary containing dataset sources objects
Source code in datarec/data/resource.py
load_class(class_import)
Given a class import name, return a class object
load_versions(dataset_name)
Given a dataset name, return a dictionary containing dataset versions and relative classes
Source code in datarec/data/resource.py
find_ratings_resource(resources)
Given a dictionary of resources, return the ratings resource Args: resources (dict): a dictionary containing dataset resources objects Returns: (Resource): the ratings resource object
Source code in datarec/data/resource.py
find_resource_by_type(resources, rtype)
Given a dictionary of resources, return the ratings resource Args: resources (dict): a dictionary containing dataset resources objects rtype (str): resource type to find Returns: (Resource): the ratings resource object
Source code in datarec/data/resource.py
Torch Dataset Wrappers
PyTorch-compatible 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
|
Any
|
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. |