-
Notifications
You must be signed in to change notification settings - Fork 0
/
IA-SmartRecomandation.txt
364 lines (277 loc) · 12.5 KB
/
IA-SmartRecomandation.txt
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package tn.esprit.pi.services;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import tn.esprit.pi.config.ValueComparator;
import tn.esprit.pi.config.ValueComparatorInt;
import tn.esprit.pi.entities.Evaluation;
import tn.esprit.pi.entities.Event;
import tn.esprit.pi.entities.User;
import tn.esprit.pi.repositories.IEvaluationRepository;
import tn.esprit.pi.repositories.IEventRepository;
import tn.esprit.pi.repositories.IUserRepository;
@Service
public class EvaluationServiceImpl implements IEvaluationService {
@Autowired
IUserRepository iUserRepository;
@Autowired
IEventRepository iEventRepository;
@Autowired
IEvaluationRepository iEvaluationRepository;
// Number of output neighbourhoods
private static final int NUM_NEIGHBOURHOODS = 10;
// Number of output recommendations
private static final int NUM_RECOMMENDATIONS = 3;
/**
* Map with the user id as key and its ratings as value that is a map with boo ASIN as key and its rating as value
*/
private Map<Integer, Map<Integer, Integer>> ratings;
/**
* Average rating of each user where the key is the user id and the value its average rating
*/
private Map<Integer, Double> averageRating;
/**
* Constructor
*/
public EvaluationServiceImpl() {
ratings = new HashMap<>();
averageRating = new HashMap<>();
}
public Map<Integer, Map<Integer, Integer>> getRatings() {
return ratings;
}
private void setRatings(Map<Integer, Map<Integer, Integer>> ratings) {
this.ratings = ratings;
}
public Map<Integer, Double> getAverageRating() {
return averageRating;
}
private void setAverageRating(Map<Integer, Double> averageRating) {
this.averageRating = averageRating;
}
@Override
public ResponseEntity<?> evaluateEvent(int idUser, int idEvent, int rate) {
// TODO Auto-generated method stub
Evaluation evaluate = new Evaluation();
User user = iUserRepository.findById(idUser).get();
Event event =iEventRepository.findById( idEvent).get();
System.out.println("event === counted ="+iEvaluationRepository.countUserRatingEvent(idUser, idEvent));
if(rate > 5) {
return ResponseEntity.ok("Rating only below or equal 5");
}
else if(rate <0) {
return ResponseEntity.ok("Rating could not be negative");
}
else if(iEvaluationRepository.countUserRatingEvent(idEvent, idUser)!=0) {
return ResponseEntity.ok("you are already rate this event");
}
else {
evaluate.setEvent(event);
evaluate.setUser(user);
evaluate.setRate(rate);
iEvaluationRepository.save(evaluate);
return ResponseEntity.ok( "Rating is done successfully");
}
}
@Override
public String updateRating(int iduser , int idproduct, int idRate, int rate) {
// TODO Auto
List<Evaluation>evaluations = iEvaluationRepository.findEvaluationByUserAndEvent(idproduct, iduser);
if(rate > 5) {
return "Rating only below or equal 5" ;
}
if(evaluations.size()!=0) {
for(int i =0 ; i<evaluations.size(); i++) {
if(idRate == evaluations.get(i).getIdEvalution()) {
evaluations.get(i).setRate(rate);
iEvaluationRepository.save(evaluations.get(i));
return "Update Evaluation successfully";
}
}
}
return "No Evaluations Found for you to update";
}
@Override
public int countRatingUserByProduct(int idp) {
// TODO Auto-generated method stub
Event p = iEventRepository.findById(idp).get();
if(p != null)
return iEvaluationRepository.countEvaluation(p.getIdEvenement());
else
return 0;
}
private Map<Integer, Double> getNeighbourhoods(Map<Integer, Integer> userRatings) {
Map<Integer, Double> neighbourhoods = new HashMap<>();
ValueComparatorInt valueComparator = new ValueComparatorInt(neighbourhoods);
Map<Integer, Double> sortedNeighbourhoods = new TreeMap<>(valueComparator);
double userAverage = getAverage(userRatings);
for (int user : ratings.keySet()) {
ArrayList<Integer> matches = new ArrayList<>();
for (int productASIN : userRatings.keySet()) {
if (ratings.get(user).containsKey(productASIN)) {
matches.add(productASIN);
}
}
double matchRate;
if (matches.size() > 0) {
double numerator = 0, userDenominator = 0,
otherUserDenominator = 0;
for (int productASIN : matches) {
double u = userRatings.get(productASIN) - userAverage;
double v = ratings.get(user).get(productASIN) - averageRating.get(user);
numerator += u * v;
userDenominator += u * u;
otherUserDenominator += v * v;
}
if (userDenominator == 0 || otherUserDenominator == 0) {
matchRate = 0;
} else {
matchRate = numerator / (Math.sqrt(userDenominator) * Math.sqrt(otherUserDenominator));
}
} else {
matchRate = 0;
}
neighbourhoods.put(user, matchRate);
}
sortedNeighbourhoods.putAll(neighbourhoods);
Map<Integer, Double> output = new TreeMap<>();
Iterator entries = sortedNeighbourhoods.entrySet().iterator();
int i = 0;
while (entries.hasNext() && i < NUM_NEIGHBOURHOODS) {
Map.Entry entry = (Map.Entry) entries.next();
if ((double) entry.getValue() > 0) {
output.put((int) entry.getKey(), (double) entry.getValue());
i++;
}
}
return output;
}
/********************************Pärtie Intelligence Articficiel / Prédiction DataSet(x,y) and deep learning (Made by Chadi)****************************
* Get predictions of each event by a user giving some ratings and its neighbourhood:
* r(u,i) = r(u) + sum(sim(u,v) * (r(v,i) - r(v))) / sum(abs(sim(u,v)))
* sim(u,v): similarity between u and v users
* r(u,i): rating of the event i by the user u
* r(u): average rating of the user u
*
* @param userRatings ratings of the user
* @param neighbourhoods nearest neighbourhoods
* @param books books in the database
* @return predictions for each event
*/
private Map<Integer, Double> getRecommendations(Map<Integer, Integer> userRatings,
Map<Integer, Double> neighbourhoods, Map<Integer, String> books) {
Map<Integer, Double> predictedRatings = new HashMap<>();
// r(u)
double userAverage = getAverage(userRatings);
for (int productASIN : books.keySet()) {
if (!userRatings.containsKey(productASIN)) {
// sum(sim(u,v) * (r(v,i) - r(v)))
double numerator = 0;
// sum(abs(sim(u,v)))
double denominator = 0;
for (int neighbourhood : neighbourhoods.keySet()) {
if (ratings.get(neighbourhood).containsKey(productASIN)) {
double matchRate = neighbourhoods.get(neighbourhood);
numerator +=
matchRate * (ratings.get(neighbourhood).get(productASIN) - averageRating.get(neighbourhood));
denominator += Math.abs(matchRate);
}
}
double predictedRating = 0;
if (denominator > 0) {
predictedRating = userAverage + numerator / denominator;
if (predictedRating > 5) {
predictedRating = 5;
}
}
predictedRatings.put(productASIN, predictedRating);
}
}
return predictedRatings;
}
/**
* Get average of the ratings of a user
*
* @param userRatings ratings of a user
* @return average or the ratings of a user
*/
private double getAverage(Map<Integer, Integer> userRatings) {
double userAverage = 0;
for (Map.Entry<Integer, Integer> longIntegerEntry : userRatings.entrySet()) {
userAverage += (int) ((Map.Entry) longIntegerEntry).getValue();
}
return userAverage / userRatings.size();
}
public String recommendedProducts(int userId) throws JSONException {
Map<Integer, Double> averageRating = new HashMap<>();
Map<Integer, Map<Integer, Integer>> setRatings = new HashMap<>();
Map<Integer, Map<Integer, Integer>> myRatesMap = new TreeMap<>();
Map<Integer, Map<Integer, Integer>> userWithRatesMap = new TreeMap<>();
iUserRepository.findAll().forEach(userItem -> {
int userID = userItem.getIdUser();
Map<Integer, Integer> userRatings = new HashMap<>();
userItem.getEvaluations().forEach(userEventRating -> {
if (userEventRating.getUser().getIdUser()==userID ) {
System.out.println(userEventRating.getRate());
System.out.println(userEventRating.getUser().getIdUser());
userRatings.put(userEventRating.getUser().getIdUser(), userEventRating.getRate());
}
}
);
if (userId==userID) {
myRatesMap.put(userID, userRatings);
} else {
userWithRatesMap.put(userID, userRatings);
setRatings(userWithRatesMap);
averageRating.put(userID, 0.0);
for (Map.Entry<Integer, Integer> longIntegerEntry : userRatings.entrySet()) {
if (ratings.containsKey(userID)) {
ratings.get(userID).put(longIntegerEntry.getKey(), longIntegerEntry.getValue());
averageRating.put(userID, averageRating.get(userID) + (double) longIntegerEntry.getValue());
} else {
Map<Integer, Integer> bookRating = new HashMap<>();
bookRating.put(longIntegerEntry.getKey(), longIntegerEntry.getValue());
ratings.put(userID, bookRating);
averageRating.put(userID, (double) longIntegerEntry.getValue());
}
}
}
});
for (Map.Entry<Integer, Double> longDoubleEntry : averageRating.entrySet()) {
if (ratings.containsKey(longDoubleEntry.getKey())) {
longDoubleEntry.setValue(longDoubleEntry.getValue() / (double) ratings.get(longDoubleEntry.getKey()).size());
}
}
setAverageRating(averageRating);
Map<Integer, String> products = new HashMap<>();
iEventRepository.findAll()
.forEach(event ->
products.put(event.getIdEvenement(), event.getTitle()));
Map<Integer, Double> neighbourhoods = getNeighbourhoods(myRatesMap.get(userId));
Map<Integer, Double> recommendations = getRecommendations(myRatesMap.get(userId), neighbourhoods, products);
ValueComparatorInt valueComparator = new ValueComparatorInt(recommendations);
Map<Integer, Double> sortedRecommendations = new TreeMap<>(valueComparator);
sortedRecommendations.putAll(recommendations);
Iterator<Map.Entry<Integer, Double>> sortedREntries = sortedRecommendations.entrySet().iterator();
JSONArray recommendedProductsArray = new JSONArray();
int i = 0;
while (sortedREntries.hasNext() && i < NUM_RECOMMENDATIONS) {
Map.Entry<Integer, Double> entry = sortedREntries.next();
JSONObject recommendedProducts = new JSONObject("{}");
recommendedProducts.put("Product Name", products.get(entry.getKey()));
recommendedProducts.put("Rate", entry.getValue());
recommendedProductsArray.put(recommendedProducts);
i++;
}
return recommendedProductsArray.toString();
}
}