9951 explained code solutions for 126 technologies


python-scikit-learnClustering example


from sklearn import datasets, cluster

X, y = datasets.load_iris(return_X_y=True)
model = cluster.KMeans(n_clusters = 3)
model.fit(X)

clusters = model.predict(X)ctrl + c
from sklearn import

import module from scikit-learn

load_iris

loads Iris dataset

.KMeans(

create KMeans clustering model

n_clusters

number of clusters we want to see

.fit(

train model with a given features and target variable dataset

.predict(

predict target variable based on given features dataset


Usage example

from sklearn import datasets, cluster

X, y = datasets.load_iris(return_X_y=True)
model = cluster.KMeans(n_clusters = 3)
model.fit(X)

clusters = model.predict(X)
print(clusters)
output
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0 2 0 0 0 0 2 0 0 0 0
 0 0 2 2 0 0 0 0 2 0 2 0 2 0 0 2 2 0 0 0 0 0 2 0 0 0 0 2 0 0 0 2 0 0 0 2 0
 0 2]