Hello im looking for exemple with python for K-Means clustering when i have data set with more than 6 feutres. thanks


It's not clear enough what you try to do. If I understand correctly, you want to train a K-Means clustering and visualize the results. However, you have 8 dimensions in your dataset and obviously, you cannot plot such a space.

What you can do is to reduce the dimensionality in 2 dimensions and then create that plot.

For example,

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans

# read my data with pandas into a dataframe
data = pd.read_csv("data.csv")

# run a KMeans model with 3 clusters. Change that number to what you want
clustering_kmeans = KMeans(n_clusters=3, precompute_distances="auto", n_jobs=-1)
clusters = clustering_kmeans.fit_predict(data)

# run PCA to reduce the dimensionality to 2 dimensions
reduced_data = PCA(n_components=2).fit_transform(data)

# create a new dataframe that contains the 2 dimensions and the cluster label
results = pd.DataFrame(reduced_data,columns=['pca1','pca2'])
results['label'] = clusters

# plot the results with a scatterplot
sns.scatterplot(x="pca1", y="pca2", hue=label, data=reduced_data)
| improve this answer | |
  • $\begingroup$ thanks for your reply my question very simple how to use k-means when i have a dataset with 8 features ??? $\endgroup$ – Mapp Feb 21 '19 at 1:07
  • $\begingroup$ Just pass the dataframe with the 8 features into the .fit_predict() and you will get the k-means. It doesn't matter that you have 8 features. The PCA is needed only if you want to visualize the results $\endgroup$ – Tasos Feb 21 '19 at 7:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.