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 thenumpy
library and assigns it to the aliasnp
from scipy.cluster.hierarchy import linkage, dendrogram
: imports thelinkage
anddendrogram
functions from thescipy
librarydata = 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 theward
methoddendrogram(Z)
: creates a visualization of the hierarchical clustering
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How can I check if a certain version of Python is compatible with SciPy?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How can I use Python and SciPy to visualize data?
- How do I create a numpy array of zeros using Python?
- How do I use the numpy vstack function in Python?
- How do I use the NumPy transpose function in Python?
- How can I use Python and SciPy to find the zeros of a function?
- How do I uninstall Python Scipy?
See more codes...