선형으로 분리되는 데이타 실습하기¶
전반적인 Procssing¶
1. Module Configuration¶
import sys, os
import matplotlib.pyplot as plt
import pandas as pd
import sklearn.datasets
import numpy as np
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridsearchCV
2. Data Loader¶
X, labels = read_data('../data/points_class_0.txt','../data/points_class_1.txt')
or
iris = sklearn.datasets.load_iris() # sklearn.datasets에 저장된 데이터 불러옴
3. Data Split¶
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size = 0.2 , random_state=0)
or
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size = 0.2 , shuffle=True)
4. model generator >> model = svm.SVC()¶
model = svm.SVC(kernel = 'linear')
or
model = svm.SVC(C=10.0 ,kernel = 'rbf', gamma=0.1)
5. training >> model.fit(X_train, y_train) 트레이닝할 데이터를 넣는다.¶
model.fit(X_train, y_train)
6. Prediction >> predict()¶
predict = model.predict(X_test) #테스트할 X테스트를 넣는다.
In [1]:
import sys, os
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
Custom Funtion Definition¶
In [2]:
red_RGB = (1, 0, 0)
blue_RGB = (0, 0, 1)
data_colors = [red_RGB, blue_RGB]
def read_points_file(filename):
points = []
with open(filename, "r") as f:
for point in f:
point = point.strip("\n").split()
points.append([float(point[0]), float(point[1])])
return points
def read_data(class_0_file, class_1_file):
points_label0 = read_points_file(class_0_file)
points_label1 = read_points_file(class_1_file)
points = points_label0 + points_label1
points = np.array(points)
label0, label1 = [0], [1]
num_of_label0, num_of_label1 = len(points_label0), len(points_label1)
labels = label0 * num_of_label0 + label1 * num_of_label1
return (points, labels)
def get_colors(y):
return [data_colors[label] for label in y]
def plot_data(X_train, y_train, X_test, y_test):
X = np.concatenate((X_train, X_test)) #concatenate 배열을 하나로 합침
y = np.concatenate((y_train, y_test))
colors = get_colors(y)
colors_train = get_colors(y_train)
colors_test = get_colors(y_test)
plt.figure(figsize=(8, 4))
# Plot all data plot
plt.subplot(131)
plt.axis('equal')
plt.scatter(X[:, 0], X[:, 1], c=colors, s=10, edgecolors=colors)
plt.title("Data (100%)")
# training data plot
plt.subplot(132)
plt.axis('equal')
#plt.axis('off')
plt.scatter(X_train[:, 0], X_train[:, 1], c = colors_train, s = 10, edgecolors=colors_train)
plt.title("Training Data (80%)")
# testing data plot
plt.subplot(133)
plt.axis('equal')
#plt.axis('off')
plt.scatter(X_test[:, 0], X_test[:, 1], c = colors_test, s = 10, edgecolors=colors_test)
plt.title("Test Data (20%)")
plt.tight_layout()
plt.show()
def plot_decision_function(X_train, y_train, X_test, y_test, clf):
plt.figure(figsize=(8, 4))
plt.subplot(121)
plt.title("Training data")
plot_decision_function_helper(X_train, y_train, clf)
plt.subplot(122)
plt.title("Test data")
plot_decision_function_helper(X_test, y_test, clf, True)
plt.show()
def plot_decision_function_helper(X, y, clf, show_only_decision_function = False):
colors = get_colors(y)
plt.axis('equal')
plt.tight_layout()
#plt.axis('off')
plt.scatter(X[:, 0], X[:, 1], c=colors, s=10, edgecolors=colors)
ax = plt.gca() ## get current axes
xlim = ax.get_xlim()
ylim = ax.get_ylim()
# Create grid to evaluate model
xx = np.linspace(xlim[0], xlim[1], 30)
yy = np.linspace(ylim[0], ylim[1], 30)
YY, XX = np.meshgrid(yy, xx)
xy = np.vstack([XX.ravel(), YY.ravel()]).T # xy.shape = (900, 2) ## ravel()은 flatten() 함수
Z = clf.decision_function(xy).reshape(XX.shape)
# clf.decision_function(xy).shape = (900,)
# Z.shape = (30, 30)
if show_only_decision_function:
# Plot decision boundary
ax.contour(XX, YY, Z, colors='k', levels=[0], alpha=0.5,
linestyles=['-'])
else :
# Plot decision boundary and margins
ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5,
linestyles=['--', '-', '--'])
1. DataLoader¶
In [3]:
# SVM 알고리즘을 실습하기 위해서
# 노이즈(Noise)전혀 없는 선현구분이 가능한 점들의 데이터를 가져올것.
X, labels = read_data('../data/points_class_0.txt','../data/points_class_1.txt')
In [4]:
# 지도학습 법 이라서 labels에 보면 해당 정답들이 있는 것을 알 수 있다.
# X는 특성 즉, 좌표 값을 말한다.
# sklearn에서 나오는 라이브러리는 라벨은 섞여 있지 않는다.
print(X,labels)
[[ 2.17197581e+00 3.50787500e+02]
[ 1.28709677e+00 3.09225000e+02]
[ 3.05685484e+00 2.64100000e+02]
[ 2.17197581e+00 2.01162500e+02]
[ 1.19056452e+01 1.54850000e+02]
[ 1.89846774e+01 1.39412500e+02]
[ 5.34949597e+01 1.20412500e+02]
[ 5.61495968e+01 1.23975000e+02]
[ 4.02217742e-01 4.56000000e+01]
[ 5.70344758e+01 8.83500000e+01]
[ 8.18110887e+01 1.32287500e+02]
[ 1.56140927e+02 1.58412500e+02]
[ 8.71203629e+01 1.69100000e+02]
[ 8.09262097e+01 2.05912500e+02]
[ 7.47320565e+01 2.48662500e+02]
[ 1.13666734e+02 2.58162500e+02]
[ 9.15447581e+01 2.22537500e+02]
[ 6.05739919e+01 2.17787500e+02]
[-1.36754032e+00 3.11600000e+02]
[ 2.25241935e+01 3.46037500e+02]
[ 5.79193548e+01 3.46037500e+02]
[ 8.18110887e+01 3.38912500e+02]
[ 8.88901210e+01 2.93787500e+02]
[ 1.00393548e+02 2.79537500e+02]
[ 1.41982863e+02 2.78350000e+02]
[ 1.63219960e+02 2.33225000e+02]
[ 1.87996573e+02 2.17787500e+02]
[ 2.17197581e+02 2.66475000e+02]
[ 3.00376210e+02 3.34162500e+02]
[ 2.47283468e+02 3.72162500e+02]
[ 2.13658065e+02 3.31787500e+02]
[ 2.38434677e+02 3.02100000e+02]
[ 2.59671774e+02 2.92600000e+02]
[ 2.31355645e+02 2.77162500e+02]
[ 1.61450202e+02 3.00912500e+02]
[ 1.41097984e+02 3.15162500e+02]
[ 1.03933065e+02 3.53162500e+02]
[ 7.82715726e+01 3.80475000e+02]
[ 3.40276210e+01 3.85225000e+02]
[ 5.08403226e+01 3.40100000e+02]
[ 1.24285282e+02 3.59100000e+02]
[ 1.95075605e+02 3.60287500e+02]
[ 2.80908871e+02 3.94725000e+02]
[ 3.05685484e+02 3.65037500e+02]
[ 2.75599597e+02 3.37725000e+02]
[ 3.10109879e+02 3.59100000e+02]
[ 3.16304032e+02 3.65037500e+02]
[ 3.44620161e+02 3.84037500e+02]
[ 3.61432863e+02 3.84037500e+02]
[ 3.13649395e+02 3.89975000e+02]
[ 2.75599597e+02 3.88787500e+02]
[ 2.54362500e+02 3.48412500e+02]
[ 2.13658065e+02 2.89037500e+02]
[ 1.64989718e+02 2.94975000e+02]
[ 1.53486290e+02 3.09225000e+02]
[ 1.41982863e+02 3.25850000e+02]
[ 1.67644355e+02 3.48412500e+02]
[ 2.44628831e+02 3.67412500e+02]
[ 2.95066935e+02 3.73350000e+02]
[ 3.32231855e+02 3.97100000e+02]
[ 3.75590927e+02 3.99475000e+02]
[ 3.75590927e+02 4.00662500e+02]
[ 2.41089315e+02 3.75725000e+02]
[ 1.41097984e+02 3.68600000e+02]
[ 1.03933065e+02 3.74537500e+02]
[ 9.77389113e+01 2.16600000e+02]
[ 1.20745766e+02 2.04725000e+02]
[ 1.44637500e+02 2.08287500e+02]
[ 1.67644355e+02 2.42725000e+02]
[ 3.04800605e+02 1.63162500e+02]
[ 2.72060081e+02 1.60787500e+02]
[ 2.63211290e+02 9.54750000e+01]
[ 2.07463911e+02 8.71625000e+01]
[ 1.93305847e+02 1.10912500e+02]
[ 2.23391734e+02 1.58412500e+02]
[ 2.60556653e+02 1.79787500e+02]
[ 2.83563508e+02 1.10912500e+02]
[ 2.51707863e+02 8.00375000e+01]
[ 1.54371169e+02 4.79750000e+01]
[ 1.11012097e+02 6.22250000e+01]
[ 1.28709677e+02 4.08500000e+01]
[ 1.60565323e+02 2.89750000e+01]
[ 2.25161492e+02 2.06625000e+01]
[ 2.95066935e+02 2.06625000e+01]
[ 3.40195766e+02 2.77875000e+01]
[ 3.71166532e+02 6.81625000e+01]
[ 3.57008468e+02 1.31100000e+02]
[ 3.67627016e+02 1.95225000e+02]
[ 3.83554839e+02 2.36787500e+02]
[ 3.81785081e+02 2.90225000e+02]
[ 3.73821169e+02 3.22287500e+02]
[ 3.52584073e+02 2.99725000e+02]
[ 2.96836694e+02 2.68850000e+02]
[ 2.83563508e+02 2.47475000e+02]
[ 2.57902016e+02 1.98787500e+02]
[ 2.06579032e+02 1.66725000e+02]
[ 1.77378024e+02 1.53662500e+02]
[ 1.49061895e+02 1.15662500e+02]
[ 1.19860887e+02 9.07250000e+01]
[ 9.33145161e+01 7.88500000e+01]
[ 8.44657258e+01 5.03500000e+01]
[ 7.38471774e+01 4.32250000e+01]
[ 1.19860887e+02 2.89750000e+01]
[ 1.72068750e+02 2.89750000e+01]
[ 2.27816129e+02 3.13500000e+01]
[ 2.31355645e+02 3.13500000e+01]
[ 2.52592742e+02 6.57875000e+01]
[ 2.82678629e+02 1.19225000e+02]
[ 2.60556653e+02 1.71475000e+02]
[ 2.56132258e+02 1.75037500e+02]
[ 2.49053226e+02 1.38225000e+02]
[ 2.59671774e+02 1.31100000e+02]
[ 3.22498185e+02 1.14475000e+02]
[ 3.30462097e+02 8.47875000e+01]
[ 3.06570363e+02 6.34125000e+01]
[ 2.81793750e+02 5.03500000e+01]
[ 2.19852218e+02 6.10375000e+01]
[ 2.13658065e+02 7.52875000e+01]
[ 2.14542944e+02 1.03787500e+02]
[ 2.80023992e+02 1.08537500e+02]
[ 3.10994758e+02 8.47875000e+01]
[ 3.28692339e+02 5.98500000e+01]
[ 3.48159677e+02 4.20375000e+01]
[ 3.66742137e+02 3.61000000e+01]
[ 3.94173387e+02 1.35375000e+01]
[ 3.82669960e+02 5.03500000e+01]
[ 3.82669960e+02 1.10912500e+02]
[ 3.83554839e+02 1.47725000e+02]
[ 3.83554839e+02 1.83350000e+02]
[ 3.81785081e+02 2.01162500e+02]
[ 3.71166532e+02 2.30850000e+02]
[ 3.57893347e+02 2.66475000e+02]
[ 3.41965524e+02 2.99725000e+02]
[ 3.41080645e+02 3.08037500e+02]
[ 3.77360685e+02 3.56725000e+02]
[ 3.93288508e+02 3.28225000e+02]
[ 4.03907056e+02 2.75975000e+02]
[ 3.28692339e+02 1.85725000e+02]] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
2. Data Split¶
In [5]:
# 전처리중에 가장 중요한 부분이다.
# 데이터를 섞어서 처리를 하면 좋다. - 랜덤하게 원래 들어있는 데이터를 섞는 기능
# train 데이터와 test 데이터를 잘 나누어 주면 된다.
# train_test_split 함수를 사용해서 트레이닝 과 테스트 데이터를 나눠준다.
# 할당받는 변수는 반드시 아래와 동일한 순서로 받아줘야 한다.
# random_state=0을 해주면 랜덤값을 고정 시켜준다. random.seed랑 같다고 보면된다.
# shuffle=True로 해줘도 섞임
# test_size=0.2 에서 테스트사이즈만 설정해줘도 트레이닝 사이즈는 자동 설정된다.
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size=0.2 , random_state=0)
print(y_train)
print('*'*30)
print(y_test)
[0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0]
******************************
[0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0]
In [6]:
# Plot Data
# 위의 데이터를 표로 살펴본다.
plot_data(X_train, y_train, X_test, y_test)
3. Model Generator and Training¶
In [7]:
# svm.SVC(kernel = 'linear') 인자값으로 커널속성을 linear를 선형을 단순하게 분리한다.
# 기본값이 linear이다.
clf_model = svm.SVC(kernel = 'linear')
In [8]:
# 학습시킬데이터를 넣는다.
clf_model.fit(X_train, y_train)
Out[8]:
SVC(kernel='linear')
4. Predict and Accuracy Score¶
In [9]:
# 학습이 잘 됬는지 확인 하기 위해서 Prediction을 돌려서 Accuracy Score를 확인해본다.
# predict() 함수를 사용해서 예측을 해본다.
# 인자값을 넣을때에는 테스트의 특성을 넣어야 한다.
clf_predict = clf_model.predict(X_test)
print(clf_predict)
[0 0 0 1 0 0 1 1 1 0 1 0 1 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0]
In [10]:
# plot_decision_function() 함수의 인자 값으로는
# X_train, y_train, X_test, y_test, clf_model 의 순서로 들어간다.
plot_decision_function(X_train, y_train, X_test, y_test, clf_model)
In [11]:
# 예측값 확인
sum = 0
for i in range(len(y_test)):
if clf_predict[i] == y_test[i]:
sum += 1
print(f'정확도 : {round(sum/len(y_test)*100,2)}%')
정확도 : 100.0%
선형으로 분리되지 않는 데이터 실습하기¶
cost를 높혀보자
1. Data Loader¶
In [12]:
X ,labels = read_data('../data/points_class_0_nonLinear.txt','../data/points_class_1_nonLinear.txt')
2. Data Split¶
In [13]:
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size = 0.2 , random_state=0)
plot_data(X_train, y_train, X_test, y_test)
위 그래프에서 보여지는 데이터인 경우 선형으로 분리되지 않고
빨간점 지점의 차원을 높여서 분리시켜야 한다.
이럴때 가우시간 방사 기저함수를 사용한다.
kernel = 'linear' >> 'rbf' (래디얼 베이시스 펑션)
In [14]:
# C 는 코스트 값을 말한다.
# gamma 는 감마값.
clf_model = svm.SVC(C=10.0 ,kernel = 'rbf',gamma=0.1)
In [15]:
# fit에 트레이닝할 데이터를 넣어서 학습 시킨다.
clf_model.fit(X_train, y_train)
predict = clf_model.predict(X_test)
plot_decision_function(X_train, y_train, X_test, y_test, clf_model)
Grid Search¶
Grid Search모듈을 사용해서
cost와 gamma값의 best값을 찾을 수 있다.
In [16]:
param_grid = {'C':[0.1, 1, 10, 100],'gamma':[0.001, 0.01, 0.1, 1, 10]}
clf_grid=GridSearchCV(svm.SVC(), param_grid, verbose=1) # 멘트를 넣는 속성 verbose 를 추가
In [17]:
clf_grid.fit(X_train, y_train)
# n_jobs=1 은 기본값이 우선 1인데, cpu코어 갯수를 1로 설정되었다는 것이다.
# verbose를 안주고 돌리면 속성 설명을 안해준다.
Fitting 5 folds for each of 20 candidates, totalling 100 fits
[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done 100 out of 100 | elapsed: 0.1s finished
Out[17]:
GridSearchCV(estimator=SVC(),
param_grid={'C': [0.1, 1, 10, 100],
'gamma': [0.001, 0.01, 0.1, 1, 10]},
verbose=1)
In [18]:
plot_decision_function(X_train, y_train, X_test, y_test, clf_grid)
In [19]:
# 최적의 Cost와 Gamma값을 알수 있다.
print(f'{clf_grid.best_params_}') # 파라메터의 값만 나온다.
print(clf_grid.best_estimator_) # 모델이름까지 나온다.
{'C': 1, 'gamma': 0.01}
SVC(C=1, gamma=0.01)
'workSpace > PYTHON' 카테고리의 다른 글
[ML] 타이타닉 생존자 예측해보기 (0) | 2021.01.19 |
---|---|
[ML] 타이타닉 생존자 예측하기 및 설명 (0) | 2021.01.19 |
[DL] CNN 모델 구조 (0) | 2021.01.19 |
[DL] Pytorch 연구 모델 (0) | 2021.01.18 |
[ML] SVM을 활용한 데이터 분석 (0) | 2021.01.18 |