-
Notifications
You must be signed in to change notification settings - Fork 0
/
als.py
168 lines (133 loc) · 6.89 KB
/
als.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
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
__author__ = 'chhavi21'
from load_data import *
from baseline_model import *
import numpy as np
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating
################################################################################
## CREATE MAPPING
################################################################################
# ALS needs numeric user_id and business_id. Hence create mapping for both
business_id_mapping = dict()
business_id = review.select(["business_id"]).map(lambda x: x.business_id).collect()
business_id = list(set(business_id))
for i in range(len(business_id)):
business_id_mapping[business_id[i]] = i
user_id_mapping = dict()
user_id = review.select(["user_id"]).map(lambda x: x.user_id).collect()
user_id = list(set(user_id))
for i in range(len(user_id)):
user_id_mapping[user_id[i]] = i
################################################################################
## CREATE INVERSE MAPPING
################################################################################
# create inverse mapping of the mapping above incase needed.
inv_business_id_mapping = dict()
for i in business_id_mapping:
inv_business_id_mapping[business_id_mapping[i]] = i
inv_user_id_mapping = dict()
for i in user_id_mapping:
inv_user_id_mapping[user_id_mapping[i]] = i
################################################################################
## CREATE TRAIN DATA
################################################################################
als_data = review.select(['user_id', "business_id", 'r_stars']).\
map(lambda x: Rating(user_id_mapping[x[0]], business_id_mapping[x[1]], x[2]-mu))
als_data.first()
################################################################################
## BUILD MODEL
################################################################################
rank = 100
numIterations = 25
model = ALS.train(als_data, rank, numIterations, lambda_ = 0.3, seed=10)
################################################################################
## PREDICT
################################################################################
def clip(x):
# clip the ratings if they are outside permissible limits
if x<1: return 1.0
elif x>5: return 5.0
return x
#make predicitions on test data
test_data = review.select(['user_id', "business_id"]).\
map(lambda x: (user_id_mapping[x[0]], business_id_mapping[x[1]]))
predictions = model.predictAll(test_data).map(lambda r: ((r[0], r[1]), clip(r[2]+mu)))
predictions = predictions.map(lambda x: (x[0], clip(x[1])))
predictions.collect()
# getting the training data in the right format for comparison
train1 = review.select(['user_id', "business_id", 'r_stars']).\
map(lambda x: Row(user_id_mapping = user_id_mapping[x[0]],
business_id_mapping = business_id_mapping[x[1]],
rating = x[2]))
train1 = sqlContext.createDataFrame(train1)
# getting the predictions in the right format for comparison
train2 = predictions.map(lambda x: Row(user_id_mapping = x[0][0],
business_id_mapping = x[0][1],
pred = x[1]))
train2 = sqlContext.createDataFrame(train2)
################################################################################
## COMPUTE RMSE ON TRAINING DATA
################################################################################
joined = train1.join(train2, on=["user_id_mapping", "business_id_mapping"])
se = joined.map(lambda x: (x.rating - x.pred)**2).reduce(lambda a,b: a+b)
n = joined.count()
rmse = np.sqrt(se/n)
# 0.64672825592371597
################################################################################
## GET COMMON TEST DATA
################################################################################
# Note to self: try to improve this code by not taking stuff out of rdd
# get the set of known user and known business from train and test set
known_business = test_rvw.select(['business_id']).rdd.intersection(business.select(['business_id']).rdd)
known_business = known_business.map(lambda x: x.business_id).collect()
known_business = set(known_business)
known_user = test_rvw.select(['user_id']).rdd.intersection(user.select(['user_id']).rdd)
known_user = known_user.map(lambda x: x.user_id).collect()
known_user = set(known_user)
#12078 observations
known_user_and_know_business = test_rvw.drop('type').\
map(lambda x: (x.user_id, x.business_id, x.review_id)).\
filter(lambda x: (x[0] in known_user)
and (x[1] in known_business))
# fromat: (user_id, business_id, review_id)
known_user_and_know_business = known_user_and_know_business.\
map(lambda x: (user_id_mapping[x[0]],
business_id_mapping[x[1]], x[2]))
test_pred = model.predictAll(known_user_and_know_business.
map(lambda x: (x[0], x[1]))).\
map(lambda r: ((r[0], r[1]), clip(r[2]+mu)))
test_pred = test_pred.map(lambda x: Row(user_id_mapping = x[0][0],
business_id_mapping = x[0][1],
pred = x[1]))
test_pred = sqlContext.createDataFrame(test_pred)
schema = StructType([StructField("user_id_mapping", StringType(), True),
StructField("business_id_mapping", StringType(), True),
StructField("review_id", StringType(), True)])
known_user_and_know_business = sqlContext.createDataFrame(known_user_and_know_business, schema)
test_pred = test_pred.join(known_user_and_know_business, on=['user_id_mapping',
'business_id_mapping'])\
.drop('business_id_mapping')\
.drop('user_id_mapping')
#export data to pandas so that it can be written to csv.
#Spark does not have any function to export data to csv directly
p = test_pred.toPandas()
# get ratings for known-known case from ALS and rest from baseline predicitions
preds_final = preds.merge(p, on=['review_id'], how='outer')
preds_final.pred = preds_final.apply(lambda x: x.stars if np.isnan(x.pred) else x.pred, axis=1)
preds_final.drop('stars', axis=1, inplace=True)
preds_final.columns = ['review_id', 'stars']
preds_final.to_csv('submission.csv', index=None)
################################################################################
## OBSERVATIONS
################################################################################
# k=10 RMSE 1.38587
# k=8 RMSE 1.36976
# k=20 RMSE 1.33906
# k=25 RMSE 1.33433
# k=70 RMSE 1.30318
# k=100 RMSE 1.29951
#k=100 and lambda=0.5 RMSE = 1.29316
#k=100 and lambda=0.2 RMSE = 1.29096
#k=100 and lambda=0.3 RMSE =1.29070
#k=100 and lambda=0.1 RMSE =1.29322
#lambda is not helping at all
# number of iterations is limited by 25 beacuse of spark version. Need to try on AWS for final predicition