from figure - we can clearly see that feature vectors having similar orientation will be very close to one another and the angle between them will be closer to deg and thus cosine similarity would be cos deg when cosine similarity is close to cos deg the angle between the documents is closer to deg indicating they are far apart and hence not very similar similarity scores close to - indicate the documents have completely opposite orientation as the angle between them would be closer to deg the following code helps us compute pairwise cosine similarity for all the documents in our sample corpus in [ ]from sklearn metrics pairwise import cosine_similarity similarity_matrix cosine_similarity(tv_matrixsimilarity_df pd dataframe(similarity_matrixsimilarity_df out[ ] from the pairwise similarity matrix obtained in the preceding outputwe can clearly see that documents and have very strong similarity among one another also documents and have strong similarity among themselves this must indicate they all have some similar features this is perfect example of grouping or clustering that can be solved by unsupervised learning let' use -means clustering to try to use the features to see if we can actually cluster or group these documents based on their feature representations in -means clusteringwe have an input parameter kwhich specifies the number of clusters it will output using the document features this clustering method is centroid based clustering methodwhere it tries to cluster these documents into clusters of equal variance it tries to create these clusters by minimizing the within-cluster sum of squares measurealso known as inertia the following snippet builds clustering model using our similarity features to cluster our text documents in [ ]from sklearn cluster import kmeans km kmeans(n_clusters= km fit_transform(similarity_dfcluster_labels km labels_ cluster_labels pd dataframe(cluster_labelscolumns=['clusterlabel']pd concat([corpus_dfcluster_labels]axis= out[ ]document category clusterlabel the sky is blue and beautiful weather love this blue and beautiful skyweather the quick brown fox jumps over the lazy dog animals the brown fox is quick and the blue dog is lazyanimals the sky is very blue and the sky is very beaut weather the dog is lazy but the brown fox is quickanimals the output obtained clearly shows us that our -means clustering model has labeled our documents into two clusters with labels and we can also see that these labels are correct where labels with value indicate documents relevant to weather and labels with value indicate documents relevant to animals thus you can see how useful these features are in document clustering and categorization