Ratings class
The Ratings
class is the main responsible for importing a dataset containing interactions between users and items
Ratings(source, user_id_column=0, item_id_column=1, score_column=2, timestamp_column=None, score_processor=None, item_map=None, user_map=None)
Class responsible for importing an interaction frame into the framework
If the source file contains users, items and ratings in this order, no additional parameters are needed, otherwise the mapping must be explicitly specified using:
- 'user_id' column,
- 'item_id' column,
- 'score' column
The score column can also be processed: in case you would like to consider as score the sentiment of a textual review, or maybe normalizing all scores in \([0, 1]\) range. Check the example below for more
Note that, during the import phase, the user and item ids will be converted to integers and a mapping between the newly created ids and the original string ids will be created. For replicability purposes, it is possible to pass your custom item and user map instead of leaving this task to the framework. Check the example below to see how
Examples:
user_id,item_id,rating,timestamp,review
u1,i1,4,00112,good movie
u2,i1,3,00113,an average movie
u2,i32,2,00114,a bad movie
As you can see the user id column, item id column and score column are the first three column and are already in sequential order, so no additional parameter is required to the Ratings class:
>>> import clayrs.content_analyzer as ca
>>> ratings_raw_source = ca.CSVFile('ratings.csv')
>>> # add timestamp='timestamp' to the following if
>>> # you want to load also the timestamp
>>> ratings = ca.Ratings(ratings_raw_source)
In case columns in the raw source are not in the above order you must specify an appropriate mapping via positional index (useful in case your raw source doesn't have a header) or via column ids:
>>> # (mapping by index) EQUIVALENT:
>>> ratings = ca.Ratings(
>>> ca.CSVFile('ratings.csv'),
>>> user_id_column=0, # (1)
>>> item_id_column=1, # (2)
>>> score_column=2 # (3)
>>> )
- First column of raw source is the column containing all user ids
- Second column of raw source is the column containing all item ids
- Third column of raw source is the column containing all the scores
>>> # (mapping by column name) EQUIVALENT:
>>> ratings = ca.Ratings(
>>> ca.CSVFile('ratings.csv'),
>>> user_id_column='user_id', # (1)
>>> item_id_column='item_id', # (2)
>>> score_column='rating' # (3)
>>> )
- The column with id 'user_id' of raw source is the column containing all user ids
- The column with id 'item_id' of raw source is the column containing all item ids
- The column with id 'rating' of raw source is the column containing all the scores
In case you would like to use the sentiment of the review
column of the above raw source as score column,
simply specify the appropriate ScoreProcessor
object
>>> ratings_raw_source = ca.CSVFile('ratings.csv')
>>> ratings = ca.Ratings(ratings_raw_source,
>>> score_column='review',
>>> score_processor=ca.TextBlobSentimentAnalysis())
In case you would like to specify the mappings for items or users, simply specify them in the corresponding parameters
>>> ratings_raw_source = ca.CSVFile('ratings.csv')
>>> custom_item_map = {'i1': 0, 'i2': 2, 'i3': 1}
>>> custom_user_map = {'u1': 0, 'u2': 2, 'u3': 1}
>>> ratings = ca.Ratings(ratings_raw_source,
>>> item_map=custom_item_map,
>>> user_map=custom_user_map)
PARAMETER | DESCRIPTION |
---|---|
source |
Source containing the raw interaction frame
TYPE:
|
user_id_column |
Name or positional index of the field of the raw source representing users column |
item_id_column |
Name or positional index of the field of the raw source representing items column |
score_column |
Name or positional index of the field of the raw source representing score column |
timestamp_column |
Name or positional index of the field of the raw source representing timesamp column |
score_processor |
TYPE:
|
item_map |
dictionary with string keys (the item ids) and integer values (the corresponding unique integer ids) used to create the item mapping. If not specified, it will be automatically created internally |
user_map |
dictionary with string keys (the user ids) and integer values (the corresponding unique integer ids) used to create the user mapping. If not specified, it will be automatically created internally |
Source code in clayrs/content_analyzer/ratings_manager/ratings.py
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 |
|
item_id_column: np.ndarray
property
cached
item_idx_column: np.ndarray
property
cached
score_column: np.ndarray
property
cached
timestamp_column: np.ndarray
property
cached
uir: np.ndarray
property
Getter for the uir matrix created from the interaction frame. The imported ratings are converted in the form of a numpy ndarray where each row will represent an interaction. This uir matrix can be seen in a tabular representation as follows:
+----------+----------+--------+-----------+
| user_idx | item_idx | score | timestamp |
+----------+----------+--------+-----------+
| 0. | 0. | 4 | np.nan |
| 0. | 1. | 3 | np.nan |
| 1. | 4. | 1 | np.nan |
+----------+----------+--------+-----------+
Where the 'user_idx' and 'item_idx' columns contain the integer ids from the mapping of the
Ratings
object itself (these integer ids match the string ids that are in the original interaction frame)
unique_item_id_column: np.ndarray
property
cached
unique_item_idx_column: np.ndarray
property
cached
unique_user_id_column: np.ndarray
property
cached
unique_user_idx_column: np.ndarray
property
cached
user_id_column: np.ndarray
property
cached
user_idx_column: np.ndarray
property
cached
__iter__()
Note: iteration is done on integer ids, if you want to iterate over string ids you need to iterate over the 'user_id_column' or 'item_id_column'
Source code in clayrs/content_analyzer/ratings_manager/ratings.py
1179 1180 1181 1182 1183 1184 |
|
filter_ratings(user_list)
Method which will filter the rating frame by keeping only interactions of users appearing in the user_list
.
This method will return a new Ratings
object without changing the original
Examples:
+---------+---------+-------+
| user_id | item_id | score |
+---------+---------+-------+
| u1 | i1 | 4 |
| u1 | i2 | 3 |
| u2 | i5 | 1 |
+---------+---------+-------+
+----------+----------+--------+-----------+
| user_idx | item_idx | score | timestamp |
+----------+----------+--------+-----------+
| 0. | 0. | 4 | np.nan |
| 0. | 1. | 3 | np.nan |
| 1. | 4. | 1 | np.nan |
+----------+----------+--------+-----------+
>>> rating_frame.filter_ratings([0])
+---------+---------+-------+
| user_id | item_id | score |
+---------+---------+-------+
| u1 | i1 | 4 |
| u1 | i2 | 3 |
+---------+---------+-------+
+----------+----------+--------+-----------+
| user_idx | item_idx | score | timestamp |
+----------+----------+--------+-----------+
| 0. | 0. | 4 | np.nan |
| 0. | 1. | 3 | np.nan |
+----------+----------+--------+-----------+
If you don't know the integer ids for the users, you can obtain them using the user map as follows:
>>> user_idxs = rating_frame.user_map[['u1']]
>>> rating_frame.filter_ratings(user_list=user_idxs)
PARAMETER | DESCRIPTION |
---|---|
user_list |
List of user integer ids that will be present in the filtered |
Returns The filtered Ratings object which contains only interactions of selected users
Source code in clayrs/content_analyzer/ratings_manager/ratings.py
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 |
|
from_dataframe(interaction_frame, user_column=0, item_column=1, score_column=2, timestamp_column=None, user_map=None, item_map=None)
classmethod
Class method which allows to instantiate a Ratings
object by using an existing pandas DataFrame
If the pandas DataFrame contains users, items and ratings in this order, no additional parameters are needed, otherwise the mapping must be explicitly specified using:
- 'user_id' column,
- 'item_id' column,
- 'score' column
Check documentation of the Ratings
class for examples on mapping columns explicitly, the functioning is the
same
Furthermore, it is also possible to specify the user and item mapping between original string ids and
integer ones. However, differently from the Ratings
class documentation, it is possible not only to specify
them as dictionaries but also as numpy arrays or StrIntMap
objects directly. The end result will be the same
independently of the type, but it is suggested to check the StrIntMap
class documentation to understand
the differences between the three possible types
Examples:
>>> ratings_df = pd.DataFrame({'user_id': ['u1', 'u1', 'u1'],
>>> 'item_id': ['i1', 'i2', 'i3'],
>>> 'score': [4, 3, 3])
>>> Ratings.from_dataframe(ratings_df)
or
>>> user_map = {'u1': 0}
>>> item_map = {'i1': 0, 'i2': 2, 'i3': 1}
>>> ratings_df = pd.DataFrame({'user_id': ['u1', 'u1', 'u1'],
>>> 'item_id': ['i1', 'i2', 'i3'],
>>> 'score': [4, 3, 3])
>>> Ratings.from_dataframe(ratings_df, user_map=user_map, item_map=item_map)
PARAMETER | DESCRIPTION |
---|---|
interaction_frame |
pandas DataFrame which represents the original interactions frame |
user_column |
Name or positional index of the field of the DataFrame representing users column |
item_column |
Name or positional index of the field of the DataFrame representing items column |
score_column |
Name or positional index of the field of the DataFrame representing score column |
timestamp_column |
Name or positional index of the field of the raw source representing timesamp column |
item_map |
dictionary with string keys (the item ids) and integer values (the corresponding unique integer ids) used to create the item mapping. If not specified, it will be automatically created internally
TYPE:
|
user_map |
dictionary with string keys (the user ids) and integer values (the corresponding unique integer ids) used to create the user mapping. If not specified, it will be automatically created internally
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Ratings
|
|
Source code in clayrs/content_analyzer/ratings_manager/ratings.py
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 |
|
from_list(interaction_list, user_map=None, item_map=None)
classmethod
Class method which allows to instantiate a Ratings
object by using an existing list of tuples or its generator
Furthermore, it is also possible to specify the user and item mapping between original string ids and
integer ones. However, differently from the Ratings
class documentation, it is possible not only to specify
them as dictionaries but also as numpy arrays or StrIntMap
objects directly. The end result will be the same
independently of the type, but it is suggested to check the StrIntMap
class documentation to understand
the differences between the three possible types
Examples:
>>> interactions_list = [('u1', 'i1', 5), ('u2', 'i1', 4)]
>>> Ratings.from_list(interactions_list)
or
>>> user_map = {'u1': 0, 'u2': 1}
>>> item_map = {'i1': 0}
>>> interactions_list = [('u1', 'i1', 5), ('u2', 'i1', 4)]
>>> Ratings.from_list(interactions_list, user_map=user_map, item_map=item_map)
PARAMETER | DESCRIPTION |
---|---|
interaction_list |
List containing tuples or its generator |
item_map |
dictionary with string keys (the item ids) and integer values (the corresponding unique integer ids) used to create the item mapping. If not specified, it will be automatically created internally
TYPE:
|
user_map |
dictionary with string keys (the user ids) and integer values (the corresponding unique integer ids) used to create the user mapping. If not specified, it will be automatically created internally
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Ratings
|
|
Source code in clayrs/content_analyzer/ratings_manager/ratings.py
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 |
|
from_uir(uir, user_map, item_map)
classmethod
Class method which allows to instantiate a Ratings
object by using an existing uir matrix
The uir matrix should be a two-dimensional numpy ndarray where each row represents a user interaction. Each row should be in the following format:
[0. 0. 4] or [0. 0. 4 np.nan] (without or with the timestamp)
In the case of a different format for the rows, a ValueError exception will be raised. Furthermore, if the uir matrix is not of dtype np.float64, a TypeError exception will be raised.
In this case the 'user_map' and 'item_map' parameters MUST be specified, since there is no information regarding the original string ids in the uir matrix
Examples:
>>> uir_matrix = np.array([[0, 0, 4], [1, 0, 3]])
>>> user_map = {'u1': 0, 'u2': 1}
>>> item_map = {'i1': 0}
>>> Ratings.from_uir(uir_matrix, user_map=user_map, item_map=item_map)
PARAMETER | DESCRIPTION |
---|---|
uir |
uir matrix which will be used to create the new |
item_map |
dictionary with string keys (the item ids) and integer values (the corresponding unique integer ids) used to create the item mapping |
user_map |
dictionary with string keys (the user ids) and integer values (the corresponding unique integer ids) used to create the user mapping |
RETURNS | DESCRIPTION |
---|---|
Ratings
|
|
Source code in clayrs/content_analyzer/ratings_manager/ratings.py
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 |
|
get_user_interactions(user_idx, head=None, as_indices=False)
Method which returns a two-dimensional numpy array containing all the rows from the uir matrix for a single user, one for each interaction of the user. Then you can easily access the columns of the resulting array to obtain useful information
Examples:
So if the rating frame is the following:
+---------+---------+-------+
| user_id | item_id | score |
+---------+---------+-------+
| u1 | i1 | 4 |
| u1 | i2 | 3 |
| u2 | i5 | 1 |
+---------+---------+-------+
The corresponding uir matrix will be the following:
+----------+----------+--------+-----------+
| user_idx | item_idx | score | timestamp |
+----------+----------+--------+-----------+
| 0. | 0. | 4 | np.nan |
| 0. | 1. | 3 | np.nan |
| 1. | 4. | 1 | np.nan |
+----------+----------+--------+-----------+
>>> rating_frame.get_user_interactions(0)
np.ndarray([
[0. 0. 4 np.nan],
[0. 1. 3 np.nan],
])
So you could easily extract all the ratings that a user has given, for example:
>>> rating_frame.get_user_interactions(0)[:, 2]
np.ndarray([4,
3])
If you only want the first \(k\) interactions of the user, set head=k
. The interactions returned are the
first \(k\) according to their order of appearance in the rating frame:
>>> rating_frame.get_user_interactions(0, head=1)
np.ndarray([
[0. 0. 4 np.nan]
])
If you want to have the indices of the uir matrix corresponding to the user interactions instead of the
actual interactions, set as_indices=True
. This will return a numpy array containing the indexes of
the rows of the uir matrix for the interactions of the specified user
>>> rating_frame.get_user_interactions(0, as_indices=True)
np.ndarray([0, 1])
If you don't know the user_idx
for a specific user, you can obtain it using the user map as follows:
>>> user_idx = rating_frame.user_map['u1']
>>> rating_frame.get_user_interactions(user_idx=user_idx)
np.ndarray([
[0. 0. 4 np.nan],
[0. 1. 3 np.nan],
])
PARAMETER | DESCRIPTION |
---|---|
user_idx |
Integer id of the user for which you want to retrieve the interactions
TYPE:
|
head |
Integer which will cut the list of interactions of the user returned. The interactions returned are the first \(k\) according to their order of appearance
TYPE:
|
as_indices |
Instead of returning the user interactions, the indices of the rows in the uir matrix corresponding to interactions for the specified user will be returned
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
np.ndarray
|
If |
Source code in clayrs/content_analyzer/ratings_manager/ratings.py
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 |
|
take_head_all(head)
Method which will retain only \(k\) interactions for each user. The \(k\) interactions retained are the first which appear in the rating frame.
This method will return a new Ratings
object without changing the original
Examples:
+---------+---------+-------+
| user_id | item_id | score |
+---------+---------+-------+
| u1 | i1 | 4 |
| u1 | i2 | 3 |
| u2 | i5 | 1 |
| u2 | i6 | 2 |
+---------+---------+-------+
+----------+----------+--------+-----------+
| user_idx | item_idx | score | timestamp |
+----------+----------+--------+-----------+
| 0. | 0. | 4 | np.nan |
| 0. | 1. | 3 | np.nan |
| 1. | 4. | 1 | np.nan |
| 1. | 5. | 2 | np.nan |
+----------+----------+--------+-----------+
>>> rating_frame.take_head_all(head=1)
+---------+---------+-------+
| user_id | item_id | score |
+---------+---------+-------+
| u1 | i1 | 4 |
| u2 | i5 | 1 |
+---------+---------+-------+
+----------+----------+--------+-----------+
| user_idx | item_idx | score | timestamp |
+----------+----------+--------+-----------+
| 0. | 0. | 4 | np.nan |
| 1. | 4. | 1 | np.nan |
+----------+----------+--------+-----------+
PARAMETER | DESCRIPTION |
---|---|
head |
The number of interactions to retain for each user
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Ratings
|
The filtered Ratings object which contains only first \(k\) interactions for each user |
Source code in clayrs/content_analyzer/ratings_manager/ratings.py
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 |
|
to_csv(output_directory='.', file_name='ratings_frame', overwrite=False, ids_as_str=True)
Method which will save the Ratings
object to a csv
file
PARAMETER | DESCRIPTION |
---|---|
output_directory |
directory which will contain the csv file
TYPE:
|
file_name |
Name of the csv_file
TYPE:
|
overwrite |
If set to True and a csv file exists in the same output directory with the same file name, it will be overwritten
TYPE:
|
ids_as_str |
If True the original string ids for users and items will be used, otherwise their integer ids
TYPE:
|
Source code in clayrs/content_analyzer/ratings_manager/ratings.py
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 |
|
to_dataframe(ids_as_str=True)
Method which will convert the Rating
object to a pandas DataFrame object
.
The returned DataFrame object will contain the 'user_id', 'item_id' and 'score' column and optionally the 'timestamp' column, if at least one interaction has a timestamp.
PARAMETER | DESCRIPTION |
---|---|
ids_as_str |
If True, the original string ids for users and items will be used, otherwise their integer ids
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
pd.DataFrame
|
The rating frame converted to a pandas DataFrame with 'user_id', 'item_id', 'score' column and optionally the 'timestamp' column |
Source code in clayrs/content_analyzer/ratings_manager/ratings.py
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 |
|