Skip to content

Commit 1a17166

Browse files
maibinEugen
authored andcommitted
Slope One Algorithm (eugenp#917)
* @async and Spring Security * @async with SecurityContext propagated * Spring and @async * Simulated Annealing algorithm * Simulated Annealing algorithm * Rebase * Rebase * SA further fixes * Slope One plus package refactoring
1 parent 5226c5f commit 1a17166

9 files changed

Lines changed: 219 additions & 7 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.baeldung.algorithms;
2+
3+
import java.util.Scanner;
4+
5+
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
6+
import com.baeldung.algorithms.slope_one.SlopeOne;
7+
8+
public class RunAlgorithm {
9+
10+
public static void main(String[] args) {
11+
Scanner in = new Scanner(System.in);
12+
System.out.println("Run algorithm:");
13+
System.out.println("1 - Simulated Annealing");
14+
System.out.println("2 - Slope One");
15+
int decision = in.nextInt();
16+
switch (decision) {
17+
case 1:
18+
System.out.println(
19+
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
20+
break;
21+
case 2:
22+
SlopeOne.slopeOne(3);
23+
break;
24+
default:
25+
System.out.println("Unknown option");
26+
break;
27+
}
28+
in.close();
29+
}
30+
31+
}

core-java/src/main/java/com/baeldung/algorithms/City.java renamed to core-java/src/main/java/com/baeldung/algorithms/annealing/City.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.baeldung.algorithms;
1+
package com.baeldung.algorithms.annealing;
22

33
import lombok.Data;
44

core-java/src/main/java/com/baeldung/algorithms/SimulatedAnnealing.java renamed to core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.baeldung.algorithms;
1+
package com.baeldung.algorithms.annealing;
22

33
public class SimulatedAnnealing {
44

@@ -33,8 +33,4 @@ public static double simulateAnnealing(double startingTemperature, int numberOfI
3333
return bestDistance;
3434
}
3535

36-
public static void main(String[] args) {
37-
System.out.println("Optimized distance for travel: " + simulateAnnealing(10, 10000, 0.9995));
38-
}
39-
4036
}

core-java/src/main/java/com/baeldung/algorithms/Travel.java renamed to core-java/src/main/java/com/baeldung/algorithms/annealing/Travel.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.baeldung.algorithms;
1+
package com.baeldung.algorithms.annealing;
22

33
import java.util.ArrayList;
44
import java.util.Collections;
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.baeldung.algorithms.slope_one;
2+
3+
import java.util.Arrays;
4+
import java.util.HashMap;
5+
import java.util.HashSet;
6+
import java.util.List;
7+
import java.util.Map;
8+
import java.util.Set;
9+
10+
import lombok.Data;
11+
12+
@Data
13+
public class InputData {
14+
15+
protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"),
16+
new Item("Snacks"));
17+
18+
public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) {
19+
Map<User, HashMap<Item, Double>> data = new HashMap<>();
20+
HashMap<Item, Double> newUser;
21+
Set<Item> newRecommendationSet;
22+
for (int i = 0; i < numberOfUsers; i++) {
23+
newUser = new HashMap<Item, Double>();
24+
newRecommendationSet = new HashSet<>();
25+
for (int j = 0; j < 3; j++) {
26+
newRecommendationSet.add(items.get((int) (Math.random() * 5)));
27+
}
28+
for (Item item : newRecommendationSet) {
29+
newUser.put(item, Math.random());
30+
}
31+
data.put(new User("User " + i), newUser);
32+
}
33+
return data;
34+
}
35+
36+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.baeldung.algorithms.slope_one;
2+
3+
import lombok.AllArgsConstructor;
4+
import lombok.Data;
5+
import lombok.NoArgsConstructor;
6+
7+
@Data
8+
@NoArgsConstructor
9+
@AllArgsConstructor
10+
public class Item {
11+
12+
private String itemName;
13+
}
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
package com.baeldung.algorithms.slope_one;
2+
3+
import java.text.DecimalFormat;
4+
import java.text.NumberFormat;
5+
import java.util.HashMap;
6+
import java.util.Map;
7+
import java.util.Map.Entry;
8+
9+
/**
10+
* Slope One algorithm implementation
11+
*/
12+
public class SlopeOne {
13+
14+
private static Map<Item, Map<Item, Double>> differencesMatrix = new HashMap<>();
15+
private static Map<Item, Map<Item, Integer>> frequenciesMatrix = new HashMap<>();
16+
private static Map<User, HashMap<Item, Double>> inputData;
17+
private static Map<User, HashMap<Item, Double>> outputData = new HashMap<>();
18+
19+
public static void slopeOne(int numberOfUsers) {
20+
inputData = InputData.initializeData(numberOfUsers);
21+
System.out.println("Slope One - Before the Prediction\n");
22+
buildDifferencesMatrix(inputData);
23+
System.out.println("\nSlope One - With Predictions\n");
24+
predict(inputData);
25+
}
26+
27+
/**
28+
* Based on the available data, calculate the relationships between the
29+
* items and number of occurences
30+
*
31+
* @param data existing user data and their items' ratings
32+
*/
33+
private static void buildDifferencesMatrix(Map<User, HashMap<Item, Double>> data) {
34+
for (HashMap<Item, Double> user : data.values()) {
35+
for (Entry<Item, Double> entry : user.entrySet()) {
36+
if (!differencesMatrix.containsKey(entry.getKey())) {
37+
differencesMatrix.put(entry.getKey(), new HashMap<Item, Double>());
38+
frequenciesMatrix.put(entry.getKey(), new HashMap<Item, Integer>());
39+
}
40+
for (Entry<Item, Double> entry2 : user.entrySet()) {
41+
int oldCount = 0;
42+
if (frequenciesMatrix.get(entry.getKey()).containsKey(entry2.getKey()))
43+
oldCount = frequenciesMatrix.get(entry.getKey()).get(entry2.getKey()).intValue();
44+
double oldDiff = 0.0;
45+
if (differencesMatrix.get(entry.getKey()).containsKey(entry2.getKey()))
46+
oldDiff = differencesMatrix.get(entry.getKey()).get(entry2.getKey()).doubleValue();
47+
double observedDiff = entry.getValue() - entry2.getValue();
48+
frequenciesMatrix.get(entry.getKey()).put(entry2.getKey(), oldCount + 1);
49+
differencesMatrix.get(entry.getKey()).put(entry2.getKey(), oldDiff + observedDiff);
50+
}
51+
}
52+
}
53+
for (Item j : differencesMatrix.keySet()) {
54+
for (Item i : differencesMatrix.get(j).keySet()) {
55+
double oldvalue = differencesMatrix.get(j).get(i).doubleValue();
56+
int count = frequenciesMatrix.get(j).get(i).intValue();
57+
differencesMatrix.get(j).put(i, oldvalue / count);
58+
}
59+
}
60+
printData(data);
61+
}
62+
63+
/**
64+
* Based on existing data predict all missing ratings. If prediction is not
65+
* possible, the value will be equal to -1
66+
*
67+
* @param data existing user data and their items' ratings
68+
*/
69+
private static void predict(Map<User, HashMap<Item, Double>> data) {
70+
HashMap<Item, Double> predictions = new HashMap<Item, Double>();
71+
HashMap<Item, Integer> frequencies = new HashMap<Item, Integer>();
72+
for (Item j : differencesMatrix.keySet()) {
73+
frequencies.put(j, 0);
74+
predictions.put(j, 0.0);
75+
}
76+
for (Entry<User, HashMap<Item, Double>> entry : data.entrySet()) {
77+
for (Item j : entry.getValue().keySet()) {
78+
for (Item k : differencesMatrix.keySet()) {
79+
try {
80+
double newValue = (differencesMatrix.get(k).get(j).doubleValue()
81+
+ entry.getValue().get(j).doubleValue()) * frequenciesMatrix.get(k).get(j).intValue();
82+
predictions.put(k, predictions.get(k) + newValue);
83+
frequencies.put(k, frequencies.get(k) + frequenciesMatrix.get(k).get(j).intValue());
84+
} catch (NullPointerException e) {
85+
}
86+
}
87+
}
88+
HashMap<Item, Double> cleanPredictions = new HashMap<Item, Double>();
89+
for (Item j : predictions.keySet()) {
90+
if (frequencies.get(j) > 0) {
91+
cleanPredictions.put(j, predictions.get(j).doubleValue() / frequencies.get(j).intValue());
92+
}
93+
}
94+
for (Item j : InputData.items) {
95+
if (entry.getValue().containsKey(j)) {
96+
cleanPredictions.put(j, entry.getValue().get(j));
97+
} else {
98+
cleanPredictions.put(j, -1.0);
99+
}
100+
}
101+
outputData.put(entry.getKey(), cleanPredictions);
102+
}
103+
printData(outputData);
104+
}
105+
106+
private static void printData(Map<User, HashMap<Item, Double>> data) {
107+
for (User user : data.keySet()) {
108+
System.out.println(user.getUsername() + ":");
109+
print(data.get(user));
110+
}
111+
}
112+
113+
private static void print(HashMap<Item, Double> hashMap) {
114+
NumberFormat formatter = new DecimalFormat("#0.000");
115+
for (Item j : hashMap.keySet()) {
116+
System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue()));
117+
}
118+
}
119+
120+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.baeldung.algorithms.slope_one;
2+
3+
import lombok.AllArgsConstructor;
4+
import lombok.Data;
5+
import lombok.NoArgsConstructor;
6+
7+
@Data
8+
@NoArgsConstructor
9+
@AllArgsConstructor
10+
public class User {
11+
12+
private String username;
13+
14+
}

‎core-java/src/test/java/com/baeldung/algorithms/SimulatedAnnealingTest.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import org.junit.Assert;
44
import org.junit.Test;
55

6+
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
7+
68
public class SimulatedAnnealingTest {
79

810
@Test

0 commit comments

Comments
 (0)