search
HomeBackend DevelopmentPython TutorialHow to write K-means clustering algorithm in Python?

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:

  1. 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.
  2. Assign each data point to the category represented by the nearest centroid based on its distance from the centroid.
  3. Update the position of the centroid, setting it to the average of all data points in that category.
  4. 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Why are arrays generally more memory-efficient than lists for storing numerical data?Why are arrays generally more memory-efficient than lists for storing numerical data?May 05, 2025 am 12:15 AM

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

How can you convert a Python list to a Python array?How can you convert a Python list to a Python array?May 05, 2025 am 12:10 AM

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

Can you store different data types in the same Python list? Give an example.Can you store different data types in the same Python list? Give an example.May 05, 2025 am 12:10 AM

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.

What is the difference between arrays and lists in Python?What is the difference between arrays and lists in Python?May 05, 2025 am 12:06 AM

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

What module is commonly used to create arrays in Python?What module is commonly used to create arrays in Python?May 05, 2025 am 12:02 AM

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

How do you append elements to a Python list?How do you append elements to a Python list?May 04, 2025 am 12:17 AM

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

How do you create a Python list? Give an example.How do you create a Python list? Give an example.May 04, 2025 am 12:16 AM

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

Discuss real-world use cases where efficient storage and processing of numerical data are critical.Discuss real-world use cases where efficient storage and processing of numerical data are critical.May 04, 2025 am 12:11 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

mPDF

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

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

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

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

Dreamweaver CS6

Visual web development tools