How to write K-means clustering algorithm in Python?
How to write K-means clustering algorithm in Python?
K-means clustering algorithm is a commonly used data mining and machine learning algorithm that can classify and cluster a set of data according to its attributes. This article will introduce how to write the K-means clustering algorithm in Python and provide specific code examples.
Before we start writing code, we need to understand the basic principles of K-means clustering algorithm.
The basic steps of K-means clustering algorithm are as follows:
- Initialize k centroids. The centroid refers to the center point of the cluster, and each data point is assigned to the category represented by its nearest centroid.
- Assign each data point to the category represented by the nearest centroid based on its distance from the centroid.
- Update the position of the centroid, setting it to the average of all data points in that category.
- Repeat steps 2 and 3 until the position of the center of mass no longer changes.
Now we can start writing code.
Import the necessary libraries
First, we need to import the necessary libraries, such as numpy and matplotlib.
import numpy as np import matplotlib.pyplot as plt
Data preparation
We need to prepare a set of data for clustering. Here we use numpy to randomly generate a set of two-dimensional data.
data = np.random.randn(100, 2)
Initializing centroids
We need to initialize k centroids for the clustering algorithm. Here we use numpy to randomly select k data points as the initial centroid.
k = 3 centroids = data[np.random.choice(range(len(data)), k, replace=False)]
Calculate distance
We need to define a function to calculate the distance between the data point and the centroid. Here we use Euclidean distance.
def compute_distances(data, centroids): return np.linalg.norm(data[:, np.newaxis] - centroids, axis=2)
Assign data points to the nearest centroid
We need to define a function to assign each data point to the category represented by the nearest centroid.
def assign_clusters(data, centroids): distances = compute_distances(data, centroids) return np.argmin(distances, axis=1)
Update the position of the centroid
We need to define a function to update the position of the centroid, that is, set it to the average of all data points in the category.
def update_centroids(data, clusters, k): centroids = [] for i in range(k): centroids.append(np.mean(data[clusters == i], axis=0)) return np.array(centroids)
Iterative clustering process
Finally, we need to iterate the clustering process until the position of the centroid no longer changes.
def kmeans(data, k, max_iter=100): centroids = data[np.random.choice(range(len(data)), k, replace=False)] for _ in range(max_iter): clusters = assign_clusters(data, centroids) new_centroids = update_centroids(data, clusters, k) if np.all(centroids == new_centroids): break centroids = new_centroids return clusters, centroids
Run the clustering algorithm
Now we can run the clustering algorithm to get the category to which each data point belongs and the final centroid.
clusters, centroids = kmeans(data, k)
Visualizing results
Finally, we can use matplotlib to visualize the results. Each data point is color-coded according to the category it belongs to, and the location of the centroid is indicated by a red circle.
plt.scatter(data[:, 0], data[:, 1], c=clusters) plt.scatter(centroids[:, 0], centroids[:, 1], s=100, c='red', marker='o') plt.show()
Through the above code examples, we can use Python to implement the K-means clustering algorithm. You can adjust the number of clusters k and other parameters according to your needs. I hope this article will help you understand and implement the K-means clustering algorithm!
The above is the detailed content of How to write K-means clustering algorithm in Python?. For more information, please follow other related articles on the PHP Chinese website!

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

Pythondoesnothavebuilt-inarrays;usethearraymoduleformemory-efficienthomogeneousdatastorage,whilelistsareversatileformixeddatatypes.Arraysareefficientforlargedatasetsofthesametype,whereaslistsofferflexibilityandareeasiertouseformixedorsmallerdatasets.

ThemostcommonlyusedmoduleforcreatingarraysinPythonisnumpy.1)Numpyprovidesefficienttoolsforarrayoperations,idealfornumericaldata.2)Arrayscanbecreatedusingnp.array()for1Dand2Dstructures.3)Numpyexcelsinelement-wiseoperationsandcomplexcalculationslikemea

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools
