Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Including method SVD.get_utility_matrix #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions funk_svd/svd.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,19 @@ def _on_epoch_end(self, start, val_loss=None, val_rmse=None, val_mae=None):
print('val_mae: {:.2f}'.format(val_mae), end=' - ')

print('took {:.1f} sec'.format(end - start))

def get_utility_matrix(self, X, fillna = 0):
""" Creates an utility matrix based on a [u_id, i_id, rating] dataframe

Args:
X {pd.DataFrame} -- dataframe with columns u_id, i_id and rating
fillna {int} -- value to fill the non-existing ratings

Returns:
pd.DataFrame -- utility matrix with users as index and items as
columns
"""

return X.pivot(
index='u_id', columns='i_id', values='rating'
).fillna(fillna)
15 changes: 12 additions & 3 deletions run_experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

from sklearn.metrics import mean_absolute_error


df = fetch_ml_ratings(variant='100k')

train = df.sample(frac=0.8, random_state=7)
Expand All @@ -16,9 +15,19 @@
svd = SVD(learning_rate=0.001, regularization=0.005, n_epochs=100,
n_factors=15, min_rating=1, max_rating=5)

df_matrix_original = svd.get_utility_matrix(df)
print ("Original Utility Matrix: \n", df_matrix_original.values)

# Getting all u_id and i_id combinations
df_user_item = pd.melt(df_matrix_original.reset_index(drop=False), id_vars='u_id')

svd.fit(X=train, X_val=val, early_stopping=True, shuffle=False)

pred = svd.predict(test)
mae = mean_absolute_error(test["rating"], pred)
pred_test = svd.predict(test)
df_user_item["rating"] = svd.predict(df_user_item)

print ("Predicted Utility Matrix: \n", svd.get_utility_matrix(df_user_item).values)

mae = mean_absolute_error(test["rating"], pred_test)

print(f'Test MAE: {mae:.2f}')