<s> from . models import Review , Wine , Cluster <EOL> from django . contrib . auth . models import User <EOL> from sklearn . cluster import KMeans <EOL> from scipy . sparse import dok_matrix , csr_matrix <EOL> import numpy as np <EOL> def update_clusters ( ) : <EOL> num_reviews = Review . objects . count ( ) <EOL> update_step = ( ( num_reviews / <NUM_LIT:100> ) + <NUM_LIT:1> ) * <NUM_LIT:5> <EOL> if num_reviews % update_step == <NUM_LIT:0> : <EOL> all_user_names = map ( lambda x : x . username , User . objects . only ( "<STR_LIT:username>" ) ) <EOL> all_wine_ids = set ( map ( lambda x : x . wine . id , Review . objects . only ( "<STR_LIT>" ) ) ) <EOL> num_users = len ( all_user_names ) <EOL> ratings_m = dok_matrix ( ( num_users , max ( all_wine_ids ) + <NUM_LIT:1> ) , dtype = np . float32 ) <EOL> for i in range ( num_users ) : <EOL> user_reviews = Review . objects . filter ( user_name = all_user_names [ i ] ) <EOL> for user_review in user_reviews : <EOL> ratings_m [ i , user_review . wine . id ] = user_review . rating <EOL> k = int ( num_users / <NUM_LIT:10> ) + <NUM_LIT:2> <EOL> kmeans = KMeans ( n_clusters = k ) <EOL> clustering = kmeans . fit ( ratings_m . tocsr ( ) ) <EOL> Cluster . objects . all ( ) . delete ( ) <EOL> new_clusters = { i : Cluster ( name = i ) for i in range ( k ) } <EOL> for cluster in new_clusters . values ( ) : <EOL> cluster . save ( ) <EOL> for i , cluster_label in enumerate ( clustering . labels_ ) : <EOL> new_clusters [ cluster_label ] . users . add ( User . objects . get ( username = all_user_names [ i ] ) ) </s>
