본문 바로가기
AI

Day65_Ai(3)_Pm

by roaring90s 2025. 10. 29.

clusteringEx5

 ladybug 다운

from matplotlib.image import imread
import matplotlib.pyplot as plt
from numpy.ma.core import reshape
from sklearn.cluster import KMeans

image = imread('ladybug.png')
print(image)
print(type(image))
#<class 'numpy.ndarray'>
print(image.shape)
#(533, 800, 3) 세로, 가로 3차원
print()

x = image.reshape(-1, 3)
print(x.shape)
#(426400, 3)    전체 사진의 픽셀 수

kmeans = KMeans(n_clusters=2, random_state=42).fit(x)
#8개의 비슷한 색깔 끼리 뭉쳐 놓겠다.
print(kmeans.cluster_centers_)
segmented_img =kmeans.cluster_centers_[kmeans.labels_]
print(kmeans.labels_)
segmented_img =segmented_img.reshape(image.shape)
plt.imshow(segmented_img)
# plt.show()

segmented_imgs= []
n_colors = [10,8,6,4,2]
for n_clusters in n_colors:
    kmeans = KMeans(n_clusters=n_clusters, random_state=42).fit(x)
    segmented_img = kmeans.cluster_centers_[kmeans.labels_]
    segmented_imgs.append(segmented_img.reshape(image.shape))

plt.figure(figsize=(11,6))
plt.subplot(231)
plt.imshow(image)
plt.title('original image')
plt.axis('off')

for idx, n_clusters in enumerate(n_colors):
    plt.subplot(232 + idx)
    plt.imshow(segmented_imgs[idx]) #이미지를 그림
    plt.title(f'{n_clusters} colors')
    plt.axis('off')

plt.show()

 


 

clusteringEx6

import mglearn
import matplotlib.pyplot as plt

mglearn.plots.plot_agglomerative_algorithm()
plt.show()
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import AgglomerativeClustering

iris = load_iris()
features = iris.data

scaler = StandardScaler()
features_std = scaler.fit_transform(features)
cluster = AgglomerativeClustering(n_clusters=3, linkage='complete')
model = cluster.fit(features_std)
print(model.labels_)
print()
print(cluster.fit_predict((features_std)))

 


 

clusteringEx7

x, y = make_moons(n_samples=1000, noise=0.05, random_state=42)
dbscan = DBSCAN(eps=0.05, min_samples=5)
dbscan.fit(x)
print(dbscan.labels_[:10])
#[ 0  2 -1 -1  1  0  0  0  2  5] => -1은 노이즈값
#입실론 값은 데이터마다 달라지기 때문에 커질수록 왕따가 없어짐

dbscan2 = DBSCAN(eps=0.2, min_samples=5)
dbscan2.fit(x)
print(dbscan2.labels_[:10])
#[0 0 0 0 1 0 0 0 0 1]

plt.figure(figsize=(12,5))
plt.subplot(121)
plot_dbscan(dbscan, x, size=100)

plt.subplot(122)
plot_dbscan(dbscan2, x, size=100)
plt.show()

knn에선 처리 할 수 없다.

 


clusteringEx8

from numpy.f2py.cb_rules import cb_map
from sklearn.metrics.cluster import adjusted_rand_score
from sklearn.datasets import make_moons
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans, AgglomerativeClustering, DBSCAN
import mglearn
import matplotlib.pyplot as plt
import numpy as np

x,y = make_moons(n_samples=200, noise=0.05, random_state=0)

scaler = StandardScaler()
scaler.fit(x)
x_scaled = scaler.transform(x) #데이터를 변경하고 싶을때

fig, axes = plt.subplots(1,4, figsize=(15,3), subplot_kw={'xticks':[], 'yticks':[]})
algorithms = [KMeans(n_clusters=2), AgglomerativeClustering(n_clusters=2), DBSCAN()]

np.random.seed(0)
random_clusters = np.random.randint(low=0, high=2, size=len(x))
axes[0].scatter(x_scaled[:,0], x_scaled[:,1], c=random_clusters,
                cmap=mglearn.cm3, s=60, edgecolors='black')

for ax, algorithms in zip(axes[1:], algorithms):
    clusters = algorithms.fit_predict((x_scaled))
    ax.scatter(x_scaled[:, 0], x_scaled[:, 1], c=clusters, cmap=mglearn.cm3,
               s=60, edgecolors='black')
    ax.set_title(f'{algorithms.__class__.__name__} - ARI : {adjusted_rand_score(y, clusters):.2f}')


plt.show()

 


standard scaler 대신에 쓴다. robust scaler  = q3-q1 = iqr값 / 4분위값        Xmean 값을 q2로 대체

Normalizer = 벡터값을 넣고 싶을때 사용

from sklearn.preprocessing import StandardScaler, RobustScaler, minmax_scale, normalize

scalerEx

import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.datasets import make_blobs

x, _ = make_blobs(n_samples=50, centers=5, random_state=4, cluster_std=2)
# 두개로 받아야 되지만, _ 받긴 받지만 쓰지 않겠다. 문법상 오류가 없게 하기 위해
x_train, x_test= train_test_split(x, random_state=5, test_size=.1)

fig, axes = plt.subplots(1,3, figsize=(13,4))
axes[0].scatter(x_train[:, 0], x_train[:, 1], c='orange', label='train data', s=60)
axes[0].scatter(x_test[:, 0], x_test[:, 1], c='blue', label='test data', s=60, marker='^')
axes[0].legend(loc='upper left')
axes[0].set_title('real data')

scaler = MinMaxScaler()
scaler.fit(x_train)
x_train_scaled = scaler.transform(x_train)
x_test_scaled = scaler.transform(x_test)
axes[1].scatter(x_train_scaled[:, 0], x_train_scaled[:, 1], c='orange',
                label='train data', s=60)
axes[1].scatter(x_test_scaled[:, 0], x_test_scaled[:, 1], c='blue',
                label='test data', s=60, marker='^')
axes[1].legend(loc='upper left')
axes[1].set_title('scaled to train')

test_scaler = MinMaxScaler()
test_scaler.fit(x_test)
x_test_scaled_badly = test_scaler.transform(x_test)
axes[2].scatter(x_train_scaled[:, 0], x_train_scaled[:, 1], c='orange',
                label='train set', s=60)
axes[2].scatter(x_test_scaled_badly[:, 0], x_test_scaled_badly[:, 1], c='blue',
                label='test set', s=60, marker='^')
axes[2].legend(loc='upper left')
axes[2].set_title('misadjusted data')


plt.show()

 

'AI' 카테고리의 다른 글

Day66_Ai(4)_Pm / 딥러닝전 설치  (0) 2025.10.30
Day66_Ai(4)_Am  (0) 2025.10.30
Day65_Ai(3)_Am  (0) 2025.10.29
Day64_Ai(2)_Pm  (0) 2025.10.28
Day64_Ai(2)_Am  (0) 2025.10.28