python-scipyHow do I use Python Scipy Linkage to cluster data?
To use Python Scipy Linkage to cluster data, you must first import the necessary libraries:
import numpy as np
from scipy.cluster.hierarchy import linkage, dendrogram
Next, you must create a dataset, which can be done with the following code:
data = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]])
Then, you can use the linkage function to generate the hierarchical clustering:
Z = linkage(data, 'ward')
The dendrogram function can then be used to create a visualization of the hierarchical clustering:
dendrogram(Z)
The output of the dendrogram function is a visualization of the hierarchical clustering:

Code explanation
import numpy as np: imports thenumpylibrary and assigns it to the aliasnpfrom scipy.cluster.hierarchy import linkage, dendrogram: imports thelinkageanddendrogramfunctions from thescipylibrarydata = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]]): creates an array of data pointsZ = linkage(data, 'ward'): performs hierarchical clustering on the data points using thewardmethoddendrogram(Z): creates a visualization of the hierarchical clustering
Helpful links
More of Python Scipy
- How do I create a numpy array of zeros using Python?
- How can I use Python and SciPy to calculate quaternion operations?
- How can I use Python and Numpy to zip files?
- How do I create a numpy array of zeros using Python?
- How can I use Python and SciPy to find the zeros of a function?
- How can I use Python and Numpy to parse XML data?
- How can I use Python Numpy to select elements from an array based on multiple conditions?
- How can I use the x.shape function in Python Numpy?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How do I create a 2D array of zeros using Python and NumPy?
See more codes...