정성훈
    k means (python 만으로 구현된 간단한 chatGPT 코드)



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import numpy as np
import matplotlib.pyplot as plt
 
# 거리 계산 함수 (Euclidean distance)
def euclidean_distance(x1, x2):
    return np.sqrt(np.sum((x1 - x2) ** 2))
 
# K-Means 알고리즘
class KMeans:
    def __init__(self, k=3, max_iters=100):
        self.k = k
        self.max_iters = max_iters
        self.centroids = None
        self.clusters = None
 
    def fit(self, X):
        X = np.array(X)
        n_samples, n_features = X.shape
 
        # 무작위로 k개의 중심점을 선택
        random_indices = np.random.choice(n_samples, self.k, replace=False)
        self.centroids = X[random_indices]
 
        # 반복하면서 중심점 업데이트
        for _ in range(self.max_iters):
            # 각 데이터 포인트를 가장 가까운 중심점에 할당
            self.clusters = self._create_clusters(X)
            old_centroids = self.centroids
            # 중심점 업데이트
            self.centroids = self._update_centroids(X)
 
            # 중심점이 더 이상 변화하지 않으면 종료
            if np.all(old_centroids == self.centroids):
                break
 
    def _create_clusters(self, X):
        clusters = [[] for _ in range(self.k)]
        for idx, sample in enumerate(X):
            centroid_idx = self._closest_centroid(sample)
            clusters[centroid_idx].append(idx)
        return clusters
 
    def _closest_centroid(self, sample):
        distances = [euclidean_distance(sample, centroid) for centroid in self.centroids]
        return np.argmin(distances)
 
    def _update_centroids(self, X):
        centroids = np.zeros((self.k, X.shape[1]))
        for cluster_idx, cluster in enumerate(self.clusters):
            if cluster:  # 비어 있는 경우를 방지
                cluster_mean = np.mean(X[cluster], axis=0)
                centroids[cluster_idx] = cluster_mean
        return centroids
 
    def predict(self, X):
        X = np.array(X)
        predictions = [self._closest_centroid(sample) for sample in X]
        return np.array(predictions)
 
# 예시 데이터
X = np.array([[1, 2], [2, 3], [3, 1], [8, 8], [9, 10], [10, 8]])
 
# K-Means 모델 생성 및 학습
kmeans = KMeans(k=2, max_iters=100)
kmeans.fit(X)
 
# 예측
predictions = kmeans.predict(X)
print("Cluster assignments:", predictions)
print("Centroids:", kmeans.centroids)
 
# X 데이터를 2차원에 표시
plt.scatter(X[:, 0], X[:, 1], c=predictions)
plt.scatter(kmeans.centroids[:, 0], kmeans.centroids[:, 1], marker='x', s=200, c='red')
plt.xlabel('X1')
plt.ylabel('X2')
plt.title('K-Means Clustering')
plt.show()
cs

실행 결과

 

  등록일 : 2024-09-15 [23:32] 조회 : 427 다운 : 0   
 
△ 이전글k means 2 (인공지능 2판, 천인국, 인피니티북스 2023)
▽ 다음글k nearest neighbor (kNN) 알고리즘
의료AI 실습 게시판
번호 ⓒ 제 목
인공지능 기법 참고 코드들 (다른 교재 및 인터넷 자료 모음)
실습 자료 (최승호 교수님)
의사를 위한 실전 인공지능 - 장별 실습 코드
전체 프로그램
27 인공지능 기법 참고 코드들 (다른 교재 및 인터넷 자료 모음)
26 └❶ k means 알고리즘
25    └❷ k means 1 (인공지능 2판, 천인국, 인피니티북스 2023)©
24       └❸ k means 2 (인공지능 2판, 천인국, 인피니티북스 2023)©
23    └❷ k means (python 만으로 구현된 간단한 chatGPT 코드)©
22 └❶ k nearest neighbor (kNN) 알고리즘
21    └❷ kNN 1 (인공지능 2판, 천인국, 인피니티북스 2023)©
20       └❸ kNN 2 (인공지능 2판, 천인국, 인피니티북스 2023)
19          └❹ kNN 3 (인공지능 2판, 천인국, 인피니티북스 2023)©
18    └❷ kNN (python 만으로 구현된 간단한 chatGPT 코드)©
17 실습 자료 (최승호 교수님)
16 └❶ 14주차 실습 자료 비공개o
15 └❶ 13주차 실습 자료 비공개o
14 └❶ 12주차 실습 자료 비공개o
13 └❶ 11주차 실습 자료 비공개o

[1][2]