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 create a zero matrix using Python and Numpy?
- How do I update Python SciPy?
- How can I use Python and SciPy to generate a uniform distribution?
- How do I calculate a p-value using Python and SciPy?
- How do I install and use Python-Scipy on Ubuntu 20.04?
- How do I integrate scipy with Python?
- How do I create a numpy array of zeros using Python?
- How can I use Python and Numpy to zip files?
- How do I use the Python Scipy package?
See more codes...