-
Notifications
You must be signed in to change notification settings - Fork 1
/
Basic_Recommender.py
80 lines (57 loc) · 2.47 KB
/
Basic_Recommender.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Collaborative Filtering for Final Project
Usage:
$ spark-submit Basic_Recommender.py cf_train_encode.parquet cf_val_encode.parquet ALS_Model > results.txt 2>&1
'''
# We need sys to get the command line arguments
import sys
# Other packages
import pyspark
from pyspark.sql import SparkSession
from pyspark.ml.recommendation import ALS
from pyspark.ml.evaluation import RegressionEvaluator
import itertools
from math import inf
import pandas as pd
def main(spark, train_file, val_file, model_file):
# Create dataframes
train_df = spark.read.parquet(train_file)
train_df.persist(pyspark.StorageLevel.MEMORY_AND_DISK)
val_df = spark.read.parquet(val_file)
val_df.persist(pyspark.StorageLevel.MEMORY_AND_DISK)
# Declare evaluation model object
evaluator = RegressionEvaluator(metricName="rmse", labelCol="count", predictionCol="prediction")
# Variables for hyperparameter tuning
bestRmse = 7.651545231817701
ranks = [i for i in range(9,15,3)]
regParams = [10**i for i in range(-5,-3)]
alphas = [10*i for i in range(1,5)]
# results_df = pd.DataFrame(columns=['Rank', 'Regularization', 'Alpha', 'RMSE'])
# Model training
for i,j,k in itertools.product(ranks, regParams, alphas):
als = ALS(userCol="user_num", itemCol="track_num", ratingCol="count", coldStartStrategy="drop",\
implicitPrefs=True, rank=i, regParam=j, alpha=k)
model = als.fit(train_df)
prediction = model.transform(val_df)
rmse = evaluator.evaluate(prediction)
# results_df = results_df.append({'Rank': i, 'Regularization': j, 'Alpha': k, 'RMSE':rmse}, ignore_index=True)
print("RMSE (validation) =", rmse,"for the model trained with rank =", i, "regParam = ",j,"and alpha = ", k)
if rmse < bestRmse:
bestModel = model
bestRmse = rmse
bestRank = i
bestReg = j
bestAlpha = k
bestModel.write().overwrite().save(model_file)
# Only enter this block if we're in main
if __name__ == "__main__":
# Create the spark session object
spark = SparkSession.builder.appName('recommender').getOrCreate()
# Get the filename from the command line
train_file = sys.argv[1]
val_file = sys.argv[2]
# And the location to store the trained model
model_file = sys.argv[3]
# Call our main routine
main(spark, train_file, val_file, model_file)