Python code for k-means method in super simple case

Python code for a super simple case of k-means method

In the humanities of statistical application of the first grade of statistical test in 2019, there was a problem about the initial value dependence of the k-means method, but here, in order to confirm that k-means actually depends on the initial value, I wrote python code for a super simple case.

Set the status as follows. Set to classify: A set whose elements are (finite number) real numbers. Number of clusters: 2.

python


print("First enter the number of elements in the categorized set.")
n = int(input())
print("Then enter the elements of the set you want to classify.")
a = [float(input()) for _ in range(n)]

print("Next, enter two initial values.")
b = [float(input()) for _ in range(2)]


A = []
B = []
'''
print(A)
print(B)
'''
for i in range(n):
    if abs(b[0] - a[i]) <= abs(b[1] - a[i]):
        A.append(a[i])
        
    else:
        B.append(a[i])

if  len(A) == 0 or len(B) == 0:
    print("The first cluster is")
    print(A)
    print("The second cluster is")
    print(B)
else:
    c = sum(A)/len(A)
    d = sum(B)/len(B)
     
    while c != b[0] or d != b[1]:
        b[0] = c 
        b[1] = d
        A = []
        B = []
        for i in range(n):
            if abs(b[0] - a[i]) <= abs(b[1] - a[i]):
                A.append(a[i])
        
            else:
                B.append(a[i])
        c = sum(A)/len(A)
        d = sum(B)/len(B)
    

    print("The first cluster is")
    print(A)
    print("The second cluster is")
    print(B)

Below are two examples of running this code with different initial values. image.png

image.png

So, it was confirmed that the final cluster will be different if the initial value is actually changed. ∩ (・ ω ・) ∩ You need to be careful when performing cluster analysis using the k-means method.

Recommended Posts

Python code for k-means method in super simple case
Notes for implementing simple collaborative filtering in Python
Settings for Python coding in Visual Studio Code
Simple gRPC in Python
case class in python
Simplex method (simplex method) in Python
Private method in python
Write a super simple molecular dynamics program in python
[Python] No value for argument'self' in unbound method call
Expose settings.json for efficient Python coding in VS Code
Search for strings in Python
Python code memo for yourself
Super tiny struct in python
Techniques for sorting in Python
Python #function 2 for super beginners
[Python] Sample code for Python grammar
Simple HTTP Server for python
Python #list for super beginners
Suppressing method overrides in Python
Simple IRC client in python
About "for _ in range ():" in python
Insert Import statements needed for Python code completion in Neovim
List method argument information for classes and modules in Python
Create a Python environment for professionals in VS Code on Windows
Check for memory leaks in Python
Check for external commands in python
First simple regression analysis in Python
[Python] Generate QR code in memory
Simple OAuth 2 in Python (urllib + oauthlib)
Python for super beginners Python # dictionary type 1 for super beginners
Automatically format Python code in Vim
Try implementing extension method in python
Python #index for super beginners, slices
Implemented label propagation method in Python
Simulate Monte Carlo method in Python
Write selenium test code in python
Python #len function for super beginners
Hash method (open address method) in Python
Implementing a simple algorithm in Python 2
[Python] Reasons for overriding using super ()
Run unittests in Python (for beginners)
Run a simple algorithm in Python
Python #Hello World for super beginners
Python for super beginners Python # dictionary type 2 for super beginners
Simple gacha logic written in Python
Code tests around time in Python
Read a Python # .txt file for a super beginner in Python with a working .py
About Python code for simple moving average assuming the use of Numba
Code reading of Safe, a library for checking password strength in Python
A simple HTTP client implemented in Python
Inject is recommended for DDD in Python
Try drawing a simple animation in Python
Create a simple GUI app in Python
Tips for dealing with binaries in Python
Electron Microscopy Simulation in Python: Multislice Method (1)
Summary of various for statements in Python
Let's put together Python for super beginners
Description method for reusing variables in shellscript
(For myself) Put Flask in VS Code
Template for writing batch scripts in python
Electron Microscopy Simulation in Python: Multislice Method (2)