Java programming implements a user based collaborative filtering recommendation algorithm code example

  • 2020-11-25 07:15:35
  • OfStack

Collaborative filtering simply is to use a certain interests, share a common experience of the group's preferences to recommend user information of interest, personal information through cooperation mechanism to give a fair degree of response (e.g., grade) and recorded in order to achieve the purpose of filtering and screening information to help others, especially interested in response to the no 1 is limited to, not interested in special information record is quite important also.

Collaborative filtering can be divided into rating (rating) or group filtering (social filtering) collaborative filtering is hot in the global Internet field with its excellent speed and robustness

UserCF core idea is the vector similarity according to the user data simulation, we according to the similarity, to find the specified users of similar users, and then bought similar users and specify the user is not recommended to specify a user of shopping recommended degree calculation is combined with the similarity of similar users and specify the accumulation. Note here we default to implicit feedback behavior of the user, so the impact factor for each item defaults to 1.


package cn.csu.CFUtils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
/** 
 *  Implementation of user-based collaborative filtering recommendation algorithm  
A a b d 
B a c 
C b e 
D c d e 
 * @author Administrator 
 * 
 */
public class UserCF {
	public static void main(String[] args) {
		/** 
   *  Enter the user --> Goods entry  1 There are multiple items for each user  
   *  The user ID  items ID A collection of  
   * A  a b d 
   * B  a c 
   * C  b e 
   * D  c d e 
   */
		Scanner scanner = new Scanner(System.in);
		System.out.println("Input the total users number:");
		// Input user total  
		int N = scanner.nextint();
		int[][] sparseMatrix = new int[N][N];
		// Establish user sparse matrix for user similarity calculation [Similarity matrix]  
		Map<String, Integer> userItemLength = new HashMap<>();
		// Each store 1 The total number of different items for each user  eg: A 3 
		Map<String, Set<String>> itemUserCollection = new HashMap<>();
		// Create an inversion list of items to users  eg: a A B 
		Set<String> items = new HashSet<>();
		// Assist in storing collections of items  
		Map<String, Integer> userID = new HashMap<>();
		// Secondary storage per 1 A user of three users ID mapping  
		Map<Integer, String> idUser = new HashMap<>();
		// Secondary storage per 1 a ID The corresponding user mapping  
		System.out.println("Input user--items maping infermation:<eg:A a b d>");
		scanner.nextLine();
		for (int i = 0; i < N ; i++){
			// Processes in turn N A user   The input data   Spaced by Spaces  
			String[] user_item = scanner.nextLine().split(" ");
			int length = user_item.length;
			userItemLength.put(user_item[0], length-1);
			//eg: A 3 
			userID.put(user_item[0], i);
			// The user ID The corresponding relation is established with sparse matrix  
			idUser.put(i, user_item[0]);
			// Set up items -- User inversion list  
			for (int j = 1; j < length; j ++){
				if(items.contains(user_item[j])){
					// If it already contains the corresponding item -- User mapping, directly add the corresponding user  
					itemUserCollection.get(user_item[j]).add(user_item[0]);
				} else{
					// Otherwise create the corresponding item -- User set mapping  
					items.add(user_item[j]);
					itemUserCollection.put(user_item[j], new HashSet<String>());
					// Create objects -- User inversion relationship  
					itemUserCollection.get(user_item[j]).add(user_item[0]);
				}
			}
		}
		System.out.println(itemUserCollection.toString());
		// Calculation of similarity matrix [Sparse]  
		Set<Entry<String, Set<String>>> entrySet = itemUserCollection.entrySet();
		Iterator<Entry<String, Set<String>>> iterator = entrySet.iterator();
		while(iterator.hasNext()){
			Set<String> commonUsers = iterator.next().getValue();
			for (String user_u : commonUsers) {
				for (String user_v : commonUsers) {
					if(user_u.equals(user_v)){
						continue;
					}
					sparseMatrix[userID.get(user_u)][userID.get(user_v)] += 1;
					// Calculate the user u With the user v Total number of items with positive feedback 
				}
			}
		}
		System.out.println(userItemLength.toString());
		System.out.println("Input the user for recommendation:<eg:A>");
		String recommendUser = scanner.nextLine();
		System.out.println(userID.get(recommendUser));
		// Calculate the similarity between users [cosine similarity]  
		int recommendUserId = userID.get(recommendUser);
		for (int j = 0;j < sparseMatrix.length; j++) {
			if(j != recommendUserId){
				System.out.println(idUser.get(recommendUserId)+"--"+idUser.get(j)+" similarity :"+sparseMatrix[recommendUserId][j]/Math.sqrt(userItemLength.get(idUser.get(recommendUserId))*userItemLength.get(idUser.get(j))));
			}
		}
		// Compute the specified user recommendUser Item recommendation  
		for (String item: items){
			// Traverse every 1 items  
			Set<String> users = itemUserCollection.get(item);
			// Gets a collection of all users who purchased the current item  
			if(!users.contains(recommendUser)){
				// If the recommended user does not purchase the current item, the recommendation is calculated  
				double itemRecommendDegree = 0.0;
				for (String user: users){
					itemRecommendDegree += sparseMatrix[userID.get(recommendUser)][userID.get(user)]/Math.sqrt(userItemLength.get(recommendUser)*userItemLength.get(user));
					// Recommendation calculation 
				}
				System.out.println("The item "+item+" for "+recommendUser +"'s recommended degree:"+itemRecommendDegree);
			}
		}
		scanner.close();
	}
}

Results:


Input the total users number:
6
Input user--items maping infermation:<eg:A a b d>
aassdd
djshgjh
2415231424
dsjkj dklsjf ladkjsf
df8g78dfg78 8787 
48787 sdfasd
{dklsjf=[dsjkj], sdfasd=[48787], 8787=[df8g78dfg78], ladkjsf=[dsjkj]}
{aassdd=0, df8g78dfg78=1, 48787=1, 2415231424=0, djshgjh=0, dsjkj=2}
Input the user for recommendation:<eg:A>
aassdd
0
aassdd--djshgjh similarity :NaN
aassdd--2415231424 similarity :NaN
aassdd--dsjkj similarity :NaN
aassdd--df8g78dfg78 similarity :NaN
aassdd--48787 similarity :NaN
The item dklsjf for aassdd's recommended degree:NaN
The item sdfasd for aassdd's recommended degree:NaN
The item 8787 for aassdd's recommended degree:NaN
The item ladkjsf for aassdd's recommended degree:NaN

conclusion

That's the end of this article on Java programming implementation of user-based collaborative filtering recommendation algorithm code sample, I hope to help you. If there is any deficiency, please let me know. Thank you for your support!


Related articles: