I try to make Content-based filtering model but get an TypeError "'numpy.float64' object is not iterable". I'm newbie in Python and would be very appreciate if you give me some advice, what should i edit.
With other dataset this code works well, but this one is the same, what can be a problem?
def get_item_profile(item_id):
idx = item_ids.index(item_id)
item_profile = tfidf_matrix[idx:idx+1]
return item_profile
def get_item_profiles(ids):
item_profiles_list = [get_item_profile(x) for x in ids]
item_profiles = scipy.sparse.vstack(item_profiles_list)
return item_profiles
def build_users_profile(person_id, interactions_indexed_df):
interactions_person_df = interactions_indexed_df.loc[person_id]
user_item_profiles = get_item_profiles(interactions_person_df['contentId'])
user_item_strengths = np.array(interactions_person_df['eventStrength']).reshape(-1,1)
#Weighted average of item profiles by the interactions strength
user_item_strengths_weighted_avg = np.sum(user_item_profiles.multiply(user_item_strengths), axis=0) / np.sum(user_item_strengths)
user_profile_norm = sklearn.preprocessing.normalize(user_item_strengths_weighted_avg)
return user_profile_norm
def build_users_profiles():
interactions_indexed_df = interactions_full_df[interactions_full_df['contentId'] \
.isin(articles_df['contentId'])].set_index('personId')
user_profiles = {}
for person_id in interactions_indexed_df.index.unique():
user_profiles[person_id] = build_users_profile(person_id, interactions_indexed_df)
return user_profiles
Error Message:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-126-1ae36c59638c> in <module>
----> 1 user_profiles = build_users_profiles()
<ipython-input-124-7a1dedc86c38> in build_users_profiles()
27 user_profiles = {}
28 for person_id in interactions_indexed_df.index.unique():
---> 29 user_profiles[person_id] = build_users_profile(person_id, interactions_indexed_df)
30 return user_profiles
<ipython-input-124-7a1dedc86c38> in build_users_profile(person_id, interactions_indexed_df)
13 def build_users_profile(person_id, interactions_indexed_df):
14 interactions_person_df = interactions_indexed_df.loc[person_id]
---> 15 user_item_profiles = get_item_profiles(interactions_person_df['contentId'])
16 print(interactions_person_df['contentId'])
17
<ipython-input-124-7a1dedc86c38> in get_item_profiles(ids)
6
7 def get_item_profiles(ids):
----> 8 item_profiles_list = [get_item_profile(x) for x in ids]
9 item_profiles = scipy.sparse.vstack(item_profiles_list)
10 return item_profiles
TypeError: 'numpy.float64' object is not iterable
If you pass in a number as ids
,
rather than some iterable sequence of numbers,
then you will trigger such a type error.
Arrange for this dataset to contain multiple IDs, similar to your other datasets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With