Jun's Blog

클래스 분류의 정의와 SVM의 활용 예시 - (2) 본문

Python/머신 러닝

클래스 분류의 정의와 SVM의 활용 예시 - (2)

luckydadit 2025. 3. 20. 17:03
import numpy as np

dataIn, dataOut = './../dataIn/', './../dataOut/'
filename = dataIn + 'iris.csv'

data = np.loadtxt(filename, skiprows=1, delimiter=',', dtype='str')

print(f'data.nim={data.ndim}')

# 최대 10글자의 유니코드 문자열 배열
print(f'data.dtype={data.dtype}')
print(f'data.shape={data.shape}')

 

column_size = data.shape[1]
y_column = 1
x_column = column_size - y_column

x = data[:, 0:x_column]
x = x.astype(float) # 숫자 형식으로 변환
y = data[:, x_column:]

print(x[:10])

y = y.ravel() # 엉켜 있는 데이터를 풀어주다.
print(y[:10])

import pandas as pd
myframe = pd.DataFrame(x, index=y)
print(myframe)

# Index(['setosa', 'versicolor', 'virginica'], dtype='object')
print(myframe.index.unique())

 

import matplotlib.pyplot as plt
plt.rc('font', family='Malgun Gothic')
plt.rcParams['axes.unicode_minus'] = False

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

def scatter(lbl, color):
    row = myframe.loc[lbl]
    ax.scatter(row[0], row[1], c=color, label=lbl)
# end def scatter(lbl, color)

scatter('setosa', 'red')
scatter('versicolor', 'blue')
scatter('virginica', 'green')
ax.legend()

plt.title('꽃받침 길이와 너비의 산점도 그래프')
filename = 'iris-scatter.png'
plt.savefig(dataOut + filename)
print(f'{filename} 파일이 저장되었습니다.')

 

encoder = LabelEncoder()
encoder.fit(y)
y = encoder.transform(y)
print(y[:100])

x_train, x_test, y_train, y_test = \
    train_test_split(x, y, test_size=0.2, random_state=10)

def print_feature(somedata):
    for idx in range(somedata.shape[1]):
        print(f'컬럼 {(idx+1)} 범위 : [{round(min(somedata[:, idx]), 3)}, {round(max(somedata[:, idx]), 3)}]')
# end def print_feature(somedata)

 

scaler = StandardScaler()
scaler.fit(x_train)

x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test)

model = SVC(kernel='rbf', C=1, gamma=0.1)

model.fit(x_train, y_train) # 학습(훈련)

prediction = model.predict(x_test) # 테스트

accuracy = accuracy_score(y_test, prediction)
print(f'정확도 : {accuracy}' )

matrix = confusion_matrix(y_test, prediction)
print(matrix)

report = classification_report(y_test, prediction)
print(report)