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 use Python Scipy to perform a Z test?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How can I use Python and Numpy to zip files?
- 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 use the Python Scipy package?
- How do I use Scipy zeros in Python?
- 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 Python and NumPy to perform a XOR operation?
See more codes...