| 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 |
실행 결과


의료AI 실습 게시판