# K-Means Clustering for data points with multiple attributes

I'm very new to K-Means clustering. Every example that I have seen has a two-dimensional data set.

I am working to classify recipes of varying ingredient composition into families. Each recipe is composed of a number of ingredients, and I want to group together the recipes that are similar to each other. Each recipe on average has 8 ingredients.

Is there any way I can use K-Means clustering to group these recipes together? Or would you suggest another unsupervised machine learning method?

• Hi Devin, I am working on a similar kind of problem. Did you find a way to achieve this with K-Means Clustering? If so, can you please share it here? – Susheel Athmakuri May 16 at 7:00

In k-means clustering, the "k" defines the amount of clusters - thus classes, you are trying to define.

You should ask yourself: how many different groups (=clusters) of recipes am I looking for?

In your case, your data points (features) (=recipes), are of variable dimensions (attributes) (avg 8 dimensions).

What you must realize is that the dimension of each datapoint must be the of the same length. (So the amount of recipes for each ingredient should be the same). This is because k-means calculates the distance of each datapoint to each centroid (k centroids).

What you can do to create datapoints of the same dimension, you can introduce "DTW". More about this here:

https://stats.stackexchange.com/questions/26100/how-to-run-k-means-clustering-on-data-points-of-varying-dimensionality

An easier solution would be that you populate your dataset with a value for each ingredient present in the dataset, and set the value to "0" when the ingredient is absent.

From docs, you can easily see an example of k-means applied on a dataset with more than 2 features.

For more examples, see Examples using sklearn.cluster.KMeans.

• These are 3 dimensional data sets. I have a dataset with 40 dimensions. How can I reduce the dimensional so that it can be displayed on a two-dimensional graph? – Devin S Feb 4 at 15:04
• You can use dimensionality reduction. See Unsupervised dimensionality reduction. – sentence Feb 4 at 17:16