User-based collaborative filtering recommendation algorithm

The point is to say that the similarity matrix is ​​in linear algebra, and the cosine similarity seems to be discovered earlier. It seems to be said in Wu Jun's "The Beauty of Mathematics". To understand all the details and be able to draw inferences from one case, you need to find some information.

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 ;
 
/**
 * User-based collaborative filtering recommendation algorithm implementation 
 A abd
 B ac
 C be
 D cde
 * @author Administrator
 *
 */
 public class UserCF {

    public static void main (String[] args) {
         /**
          * Input user --> item entry One user corresponds to multiple items 
          * User ID Item ID collection 
          * A abd 
          * B ac 
          * C be 
          * D cde 
          */
         Scanner scanner = new Scanner(System.in ) ;
 System.out .println ( " Input the total users number:" ) ;
 //  
 Input the total users int N = scanner.nextInt() ;
         int [][] sparseMatrix = new int [ N][N] ;                        //Create a user sparse matrix for user similarity calculation [similarity matrix]  
         Map<String , Integer> userItemLength = new HashMap<>() ; //Store the total number of different items corresponding to each user eg: A 3  
         Map< String , Set<String>> itemUserCollection = new HashMap<>() ; //Create an inverted list of items to users eg: a AB  
         Set<String> items = new HashSet<>() ; //Auxiliary storage item collection  
         Map <String , Integer> userID = new HashMap<>() ; //Auxiliary storage for each user's user ID mapping  
         Map<Integer , String> idUser = new HashMap<>() ;//Auxiliary storage of the user mapping System corresponding to each ID  
 .        out .println( "Input user--items mapping infermation:<eg:A ab d>" ) ;
 //scanner.nextLine();
 for ( int i = 0 ; i < N ; i++){ //Process N in turn User input data separated 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) ; //Create a corresponding relationship between user ID and sparse matrix  
                                                                idUser.put(i , user_item[ 0 ]) ;
 //Create items--user inverted list  
 for ( int j = 1 ; j < length ; j ++){
                 if (items.contains(user_item[j])) { //If the corresponding item--user mapping is already included, directly add the corresponding user  
 itemUserCollection.get(user_item[j]).add(user_item[ 0 ]) ;
 } else { //Otherwise create the corresponding item--user collection Mapping  
 items.add(user_item[j]) ;
 itemUserCollection.put(user_item[j] , new HashSet<String>()) ; //Create items -- user inverted relationship  
 itemUserCollection.get(user_item[j]).add (user_item[                                                                                                                        0]);
                }
            }
        }
        System.out.println(itemUserCollection.toString());
//计算相似度矩阵【稀疏】  
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 total number of items that both user u and user v have 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)+"相似度:"+sparseMatrix[recommendUserId][j]/Math.sqrt(userItemLength.get(idUser.get(recommendUserId))*userItemLength.get(idUser.get(j))));
            }
        }

        //Calculate the item recommendation degree of the specified user recommendUser  
 for (String item: items){ //Traverse each item  
 Set<String> users = itemUserCollection.get(item) ; //Get the collection of all users who purchased the current item  
 if ( !users.contains(recommendUser)){ //If the recommended user does not buy the current item, the recommendation degree 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));//推荐度计算  
                }
                System.out.println("The item "+item+" for "+recommendUser +"'s recommended degree:"+itemRecommendDegree);
            }
        }
        scanner.close();
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324404506&siteId=291194637