Sklearn Kmeans Example - Clustering Data Using K-Means
Python
1| from sklearn.cluster import KMeans 2| 3| # Step 1: Initalise kmeans clustering model for 5 clusters and 4| # fit on training data 5| k_means = KMeans(n_clusters=5, 6| random_state=101) 7| k_means.fit(X_train) 8| 9| # Step 2: Predict cluster for training and test data and add results 10| # as a column to the respective dataframes 11| X_train['cluster'] = k_means.predict(X_train) 12| X_test['cluster'] = k_means.predict(X_test) 13| 14| # Step 3: Print out cluster center arrays and inertia value 15| print('Cluster Centers:', k_means.cluster_centers_) 16| print('Inertia:', k_means.inertia_)
131
118
115
108