### 1일차 : 데이터 베이스 다루기

 

1. 데이터 타입 알아보기

숫자형 데이터 / 날짜형 데이터 / 문자형 데이터

 

2. 기본적인 데이터 다뤄 보기

- 함수를 사용하여 서로 타입 변환이 가능

 

Query 1. 숫자를 문자로 변환

SELECT CAST(123 AS VARCHAR(20));

Query 2. 문자를 숫자로 변환

SELECT CONVERT('1004',INT);

Query 3. 문자를 날짜로 변환

SELECT DATE_FORMAT('20211225','%Y-%m-%d')

 

3. 데이터 베이스 쿼리문법

# 데이터베이스 만들기
CREATE DATABASE pokemon;

# 데이터베이스 목록 보기
SHOW DATABASES;

# 데이터베이스 사용하기
USE pokemon;

 

4.  테이블 쿼리문법

- 테이블 만들기

# 테이블 만들기
CREATE TABLE idol(
		name VARCHAR(20),
        age INT,
        group VARCAHR(50)
        );
# 새로운 컬럼 추가하기
ALTER TABLE idols ADD COLUMN age INT;

# 기존 컬럼 타입 변경하기
ALTER TABLE idols MODIFY COLUMN age FLOAT;

# 기존 컬럼 이름과 타입 변경하기
ALTER TABLE idols
CHANGE COLUMN age new_age FLOAT;

 

# 데이터베이스 지우기
DROP DATABASE pokemon

# 테이블 지우기
DROP TABLE idols;

# 테이블 값만 지우기
TRUNCATE TABLE idols;

# 컬럼 지우기
ALTER TABLE idols DROP COLUMN new_age;
# 데이터베이스/테이블이 존재한다면 지우기

DROP DATABASE IF EXISTS pokemon;

DROP TABLE IF EXISTS idols;

 

5. 데이터 삽입, 삭제 수정하기

# 데이터 하나 삽입하기
INSERT INTO idol (name, age, group)
VALUES ('제니', 27, '블랙핑크');

# 데이터 여러개 삽입하기
INSERT INTO idol (name, age, group)
VALUES ('제니', 27, '블랙핑크'),
('지수', 28, '블랙핑크');

# 데이터 삭제하기
DELETE FROM [테이블 이름]
WHERE [조건 값];

# 데이터 수정하기
UPDATE [테이블 이름]
SET [컬럼 이름] = [새 값]
WHERE [조건 값];

 

 

 

 

### 2021.12.24

 

 

 

나이브 베이스 분류기(Naive Bayes Classification)

  • 베이즈 정리를 적용한 확률적 분류 알고리즘
  • 모든 특성들이 독립임을 가정 (naive 가정)
  • 입력 특성에 따라 3개의 분류기 존재
    • 가우시안 나이브 베이즈 분류기
    • 베르누이 나이브 베이즈 분류기
    • 다항 나이브 베이즈 분류기

 

나이브 베이즈 분류기의 확률 모델

 

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB
from sklearn.datasets import fetch_covtype, fetch_20newsgroups
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.feature_extraction.text import CountVectorizer, HashingVectorizer, TfidfVectorizer
from sklearn import metrics
#In[]
#나이브 베이스 기본 동작 모형
prior = [0.45, 0.3, 0.15, 0.1] #발생확률 가정
likelihood = [[0.3, 0.3, 0.4], [0.7, 0.2, 0.1], [0.15, 0.5, 0.35], [0.6,0.2,0.2]]

idx = 0
for c, xs in zip(prior, likelihood):
    result = 1.
    
    for x in xs :
        result *= x
    result *= c
    
    idx += 1
    print(f"{idx}번째 클래스의 가능성 : {result}")
    
#Out[]
1번째 클래스의 가능성 : 0.0162
2번째 클래스의 가능성 : 0.0042
3번째 클래스의 가능성 : 0.0039375
4번째 클래스의 가능성 : 0.0024000000000000002

 

1. 산림 토양 데이터

#In[]
covtype = fetch_covtype()
print(covtype.DESCR)

#Out[]
.. _covtype_dataset:

Forest covertypes
-----------------

The samples in this dataset correspond to 30×30m patches of forest in the US,
collected for the task of predicting each patch's cover type,
i.e. the dominant species of tree.
There are seven covertypes, making this a multiclass classification problem.
Each sample has 54 features, described on the
`dataset's homepage <https://archive.ics.uci.edu/ml/datasets/Covertype>`__.
Some of the features are boolean indicators,
while others are discrete or continuous measurements.

**Data Set Characteristics:**

    =================   ============
    Classes                        7
    Samples total             581012
    Dimensionality                54
    Features                     int
    =================   ============

:func:`sklearn.datasets.fetch_covtype` will load the covertype dataset;
it returns a dictionary-like 'Bunch' object
with the feature matrix in the ``data`` member
and the target values in ``target``. If optional argument 'as_frame' is
set to 'True', it will return ``data`` and ``target`` as pandas
data frame, and there will be an additional member ``frame`` as well.
The dataset will be downloaded from the web if necessary.
#In[]
pd.DataFrame(covtype.data)

#Out[]

#In[]
covtype.target

#Out[]
array([5, 5, 2, ..., 3, 3, 3], dtype=int32)

 

1-1. 학습, 평가 데이터 분류

#In[]
covtype_X = covtype.data
covtype_y = covtype.target

covtype_X_train, covtype_X_test, covtype_y_train, covtype_y_test = train_test_split(covtype_X, covtype_y, test_size=0.2)

print("전체 데이터 크기 : {}".format(covtype_X.shape))
print("학습 데이터 크기 : {}".format(covtype_X_train.shape))
print("평가 데이터 크기 : {}".format(covtype_X_test.shape))

#Out[]
전체 데이터 크기 : (581012, 54)
학습 데이터 크기 : (464809, 54)
평가 데이터 크기 : (116203, 54)

 

1-2. 전처리

전치리 전 데이터

#In[]
covtype_df = pd.DataFrame(data=covtype_X)
covtype_df.describe()

#Out[]

#In[]
covtype_train_df = pd.DataFrame(data=covtype_X_train)
covtype_train_df.describe()

#Out[]

#In[]
covtype_test_df = pd.DataFrame(data=covtype_X_test)
covtype_test_df.describe()

#Out[]

전처리 과정

  • 평균은 0에 가깝게, 표준평차는 1에 가깝게 정규화

 

#In[]
scaler = StandardScaler()
covtype_X_train_scale = scaler.fit_transform(covtype_X_train)
covtype_X_test_scale = scaler.transform(covtype_X_test)

 

전처리 후 데이터

#In[]
covtype_train_df = pd.DataFrame(data=covtype_X_train_scale)
covtype_train_df.describe()

#Out[]

#In[]
covtype_test_df = pd.DataFrame(data=covtype_X_test_scale)
covtype_test_df.describe()

#Out[]

 

2. 20 Newsgroup 데이터

  • 뉴스 기사가 어느 그룹에 속하는지 분류
  • 뉴스 기사는 텍스트 데이터이기 때문에 특별한 전처리 과정이 필요
#In[]
newsgroup = fetch_20newsgroups()
print(newsgroup.DESCR)

#Out[]
생략!!
#In[]
newsgroup.target_names

#Out[]
['alt.atheism',
 'comp.graphics',
 'comp.os.ms-windows.misc',
 'comp.sys.ibm.pc.hardware',
 'comp.sys.mac.hardware',
 'comp.windows.x',
 'misc.forsale',
 'rec.autos',
 'rec.motorcycles',
 'rec.sport.baseball',
 'rec.sport.hockey',
 'sci.crypt',
 'sci.electronics',
 'sci.med',
 'sci.space',
 'soc.religion.christian',
 'talk.politics.guns',
 'talk.politics.mideast',
 'talk.politics.misc',
 'talk.religion.misc']

 

2-1. 학습, 평가 데이터 분류

#In[]
newsgroup_train = fetch_20newsgroups(subset='train')
newsgroup_test = fetch_20newsgroups(subset='test')

X_train, y_train = newsgroup_train.data, newsgroup_train.target
X_test, y_test = newsgroup_test.data, newsgroup_test.target

 

2-2. 벡터화

  • 텍스트 데이터는 기계학습 모델에 입력 할 수 없음
  • 벡터화는 텍스트 데이터를 실수 벡터로 변환해 기계학습 모델에 입력 할 수 있도록 하는 전처리 과정
  • Scikit-learn에서는 Count, Tf-idf, Hashing 세가지 방법을 지원

2-2-1. CountVectorizer

  • 문서에 나온 단어의 수를 세서 벡터 생성
#In[]
count_vectorizer = CountVectorizer()

X_train_count = count_vectorizer.fit_transform(X_train)
X_test_count = count_vectorizer.transform(X_test)

데이터를 희소 행렬 형태로 표현

#In[]
X_train_count

#Out[]
<11314x130107 sparse matrix of type '<class 'numpy.int64'>'
	with 1787565 stored elements in Compressed Sparse Row format>
#In[]
for v in X_train_count[0]:
    print(v)
    
#Out[]
  (0, 56979)	3
  (0, 75358)	2
  (0, 123162)	2
  (0, 118280)	2
  (0, 50527)	2
  (0, 124031)	2
  (0, 85354)	1
  (0, 114688)	1
  (0, 111322)	1
  (0, 123984)	1
  (0, 37780)	5
  (0, 68532)	3
  (0, 114731)	5
  (0, 87620)	1
  (0, 95162)	1
  (0, 64095)	1
  (0, 98949)	1
  (0, 90379)	1
  (0, 118983)	1
  (0, 89362)	3
  (0, 79666)	1
  (0, 40998)	1
  (0, 92081)	1
  (0, 76032)	1
  (0, 4605)	1
  :	:
  (0, 37565)	1
  (0, 113986)	1
  (0, 83256)	1
  (0, 86001)	1
  (0, 51730)	1
  (0, 109271)	1
  (0, 128026)	1
  (0, 96144)	1
  (0, 78784)	1
  (0, 63363)	1
  (0, 90252)	1
  (0, 123989)	1
  (0, 67156)	1
  (0, 128402)	2
  (0, 62221)	1
  (0, 57308)	1
  (0, 76722)	1
  (0, 94362)	1
  (0, 78955)	1
  (0, 114428)	1
  (0, 66098)	1
  (0, 35187)	1
  (0, 35983)	1
  (0, 128420)	1
  (0, 86580)	1

 

2-2-2. HashingVectorizer

  • 각 단어를 해쉬 값으로 표현
  • 미리 정해진 크기의 벡터로 표현
#In[]
hash_vectorizer = HashingVectorizer(n_features=1000)   #1000개로 제한

X_train_hash = hash_vectorizer.fit_transform(X_train)
X_test_hash = hash_vectorizer.transform(X_test)

X_train_hash

#Out[]
<11314x1000 sparse matrix of type '<class 'numpy.float64'>'
	with 1550687 stored elements in Compressed Sparse Row format>
#In[]
print(X_train_hash[0])

#Out[]
(0, 80)	-0.0642824346533225
  (0, 108)	0.0642824346533225
  (0, 111)	-0.128564869306645
  (0, 145)	0.0642824346533225
  (0, 158)	0.0642824346533225
  (0, 159)	-0.0642824346533225
  (0, 161)	0.0642824346533225
  (0, 165)	-0.0642824346533225
  (0, 171)	0.0642824346533225
  (0, 182)	0.0642824346533225
  (0, 195)	-0.0642824346533225
  (0, 196)	0.19284730395996752
  (0, 205)	-0.0642824346533225
  (0, 209)	0.0642824346533225
  (0, 234)	0.0642824346533225
  (0, 237)	0.0642824346533225
  (0, 248)	0.0642824346533225
  (0, 265)	0.19284730395996752
  (0, 274)	0.0642824346533225
  (0, 277)	0.19284730395996752
  (0, 284)	-0.0642824346533225
  (0, 286)	-0.0642824346533225
  (0, 296)	0.0642824346533225
  (0, 362)	-0.0642824346533225
  (0, 364)	-0.0642824346533225
  :	:
  (0, 739)	0.0
  (0, 761)	-0.0642824346533225
  (0, 766)	0.0642824346533225
  (0, 800)	-0.0642824346533225
  (0, 812)	-0.0642824346533225
  (0, 842)	0.0642824346533225
  (0, 848)	-0.0642824346533225
  (0, 851)	0.0642824346533225
  (0, 863)	-0.0642824346533225
  (0, 881)	0.0642824346533225
  (0, 892)	0.0642824346533225
  (0, 897)	0.0
  (0, 899)	0.0642824346533225
  (0, 906)	-0.0642824346533225
  (0, 918)	0.128564869306645
  (0, 926)	-0.0642824346533225
  (0, 935)	0.0642824346533225
  (0, 939)	-0.0642824346533225
  (0, 951)	-0.0642824346533225
  (0, 958)	-0.38569460791993504
  (0, 960)	0.0642824346533225
  (0, 968)	-0.0642824346533225
  (0, 987)	-0.0642824346533225
  (0, 996)	0.0642824346533225
  (0, 997)	-0.128564869306645

 

2-2-3. TfidfVectorizer

#In[]
tfidf_vectorizer = TfidfVectorizer()

X_train_tfidf = tfidf_vectorizer.fit_transform(X_train)
X_test_tfidf = tfidf_vectorizer.transform(X_test)

X_train_tfidf

#Out[]
<11314x130107 sparse matrix of type '<class 'numpy.float64'>'
	with 1787565 stored elements in Compressed Sparse Row format>
#In[]
for v in X_train_tfidf[0]:
    print(v)
    
#Out[]
  (0, 86580)	0.13157118714240987
  (0, 128420)	0.04278499079283093
  (0, 35983)	0.03770448563619875
  (0, 35187)	0.09353930598317124
  (0, 66098)	0.09785515708314481
  (0, 114428)	0.05511105154696676
  (0, 78955)	0.05989856888061599
  (0, 94362)	0.055457031390147224
  (0, 76722)	0.06908779999621749
  (0, 57308)	0.1558717009157704
  (0, 62221)	0.02921527992427867
  (0, 128402)	0.05922294083277842
  (0, 67156)	0.07313443922740179
  (0, 123989)	0.08207027465330353
  (0, 90252)	0.031889368795417566
  (0, 63363)	0.08342748387969037
  (0, 78784)	0.0633940918806495
  (0, 96144)	0.10826904490745741
  (0, 128026)	0.060622095889758885
  (0, 109271)	0.10844724822064673
  (0, 51730)	0.09714744057976722
  (0, 86001)	0.07000411445838192
  (0, 83256)	0.08844382496462173
  (0, 113986)	0.17691750674853082
  (0, 37565)	0.03431760442478462
  :	:
  (0, 4605)	0.06332603952480323
  (0, 76032)	0.019219463052223086
  (0, 92081)	0.09913274493911223
  (0, 40998)	0.0780136819691811
  (0, 79666)	0.10936401252414274
  (0, 89362)	0.06521174306303763
  (0, 118983)	0.037085978050619146
  (0, 90379)	0.019928859956645867
  (0, 98949)	0.16068606055394932
  (0, 64095)	0.03542092427131355
  (0, 95162)	0.03447138409326312
  (0, 87620)	0.035671863140815795
  (0, 114731)	0.14447275512784058
  (0, 68532)	0.07325812342131596
  (0, 37780)	0.38133891259493113
  (0, 123984)	0.036854292634593756
  (0, 111322)	0.01915671802495043
  (0, 114688)	0.06214070986309586
  (0, 85354)	0.03696978508816316
  (0, 124031)	0.10798795154169122
  (0, 50527)	0.054614286588587246
  (0, 118280)	0.2118680720828169
  (0, 123162)	0.2597090245735688
  (0, 75358)	0.35383501349706165
  (0, 56979)	0.057470154074851294

 

3. 가우시안 나이브 베이즈

  • 입력 특성이 가우시안(정규) 분포를 갖는다고 가정
#In[]
model = GaussianNB()
model.fit(covtype_X_train_scale, covtype_y_train)

#Out[]
GaussianNB()

train data score

#In[]
predict = model.predict(covtype_X_train_scale)
acc = metrics.accuracy_score(covtype_y_train, predict)
f1 = metrics.f1_score(covtype_y_train, predict, average=None)

print("Train Accuracy: {}".format(acc))
print("Train F1 score : {}".format(f1))

#Out[]
Train Accuracy: 0.08788771301760508
Train F1 score : [0.03981986 0.01766797 0.33531383 0.13789636 0.04358284 0.07112195
 0.23669609]

test data score

#In[]
predict = model.predict(covtype_X_test_scale)
acc = metrics.accuracy_score(covtype_y_test, predict)
f1 = metrics.f1_score(covtype_y_test, predict, average=None)

print("Test Accuracy: {}".format(acc))
print("Test F1 score : {}".format(f1))

#Out[]
Test Accuracy: 0.0884486631154101
Test F1 score : [0.04288833 0.01908018 0.33367329 0.14015968 0.04165637 0.0736687
 0.23903186]

시각화

#In[]
from sklearn.datasets import make_blobs

def make_meshgrid(x,y,h=.02):
    x_min, x_max = x.min()-1, x.max()+1
    y_min, y_max = y.min()-1, y.max()+1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                        np.arange(y_min, y_max, h))
    
    return xx, yy
    
def plot_contours(clf, xx, yy, **params):
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    out = plt.contourf(xx, yy, Z, **params)
    
    return out
#In[]
X, y = make_blobs(n_samples=1000)

plt.scatter(X[:,0], X[:, 1], c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')

#Out[]

#In[1]
model = GaussianNB()
model.fit(X,y)

#Out[1]
GaussianNB()

#In[2]
xx, yy = make_meshgrid(X[:,0], X[:, 1])
plot_contours(model, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)
plt.scatter(X[:,0], X[:, 1], c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')

#Out[2]

 

4. 베르누이 나이브 베이즈

  • 입력 특성이 베르누이 분포에 의해 생성된 이진 값을 갖는 다고 가정

4-1. 학습 및 평가 (Count)

#In[]
model = BernoulliNB()
model.fit(X_train_count, y_train)

#Out[]
BernoulliNB()

 

#In[]
predict = model.predict(X_train_count)
acc = metrics.accuracy_score(y_train, predict)
f1 = metrics.f1_score(y_train, predict, average=None)

print('Train Accauracy : {}'.format(acc))
print('Train F1 Score : {}'.format(f1))

#Out[]
Train Accauracy : 0.7821283365741559
Train F1 Score : [0.80096502 0.8538398  0.13858268 0.70686337 0.85220126 0.87944493
 0.51627694 0.84532672 0.89064976 0.87179487 0.94561404 0.91331546
 0.84627832 0.89825848 0.9047619  0.79242424 0.84693878 0.84489796
 0.67329545 0.14742015]
#In[]
predict = model.predict(X_test_count)
acc = metrics.accuracy_score(y_test, predict)
f1 = metrics.f1_score(y_test, predict, average=None)

print('Test Accauracy : {}'.format(acc))
print('Test F1 Score : {}'.format(f1))

#Out[]
Test Accauracy : 0.6307753584705258
Test F1 Score : [0.47086247 0.60643564 0.01       0.56014047 0.6953405  0.70381232
 0.44829721 0.71878646 0.81797753 0.81893491 0.90287278 0.74794521
 0.61647059 0.64174455 0.76967096 0.63555114 0.64285714 0.77971474
 0.31382979 0.00793651]

 

4-2. 학습 및 평가 (Hash)

#In[]
model = BernoulliNB()
model.fit(X_train_hash, y_train)

#Out[]
BernoulliNB()
#In[]
predict = model.predict(X_train_hash)
acc = metrics.accuracy_score(y_train, predict)
f1 = metrics.f1_score(y_train, predict, average=None)

print('Train Accauracy : {}'.format(acc))
print('Train F1 Score : {}'.format(f1))

#Out[]
Train Accauracy : 0.5951917977726711
Train F1 Score : [0.74226804 0.49415205 0.45039019 0.59878155 0.57327935 0.63929619
 0.35390947 0.59851301 0.72695347 0.68123862 0.79809524 0.70532319
 0.54703833 0.66862745 0.61889927 0.74707471 0.6518668  0.60485269
 0.5324165  0.54576271]
#In[]
predict = model.predict(X_test_hash)
acc = metrics.accuracy_score(y_test, predict)
f1 = metrics.f1_score(y_test, predict, average=None)

print('Test Accauracy : {}'.format(acc))
print('Test F1 Score : {}'.format(f1))

#Out[]
Test Accauracy : 0.4430430164630908
Test F1 Score : [0.46678636 0.33826638 0.29391892 0.45743329 0.41939121 0.46540881
 0.34440068 0.46464646 0.62849873 0.53038674 0.63782051 0.55251799
 0.32635983 0.34266886 0.46105919 0.61780105 0.46197991 0.54591837
 0.27513228 0.3307888 ]

 

4-3. 학습 및 평가 (Tf-idf)

#In[]
model = BernoulliNB()
model.fit(X_train_tfidf, y_train)

#Out[]
BernoulliNB()
#In[]
predict = model.predict(X_train_tfidf)
acc = metrics.accuracy_score(y_train, predict)
f1 = metrics.f1_score(y_train, predict, average=None)

print('Train Accauracy : {}'.format(acc))
print('Train F1 Score : {}'.format(f1))

#Out[]
Train Accauracy : 0.7821283365741559
Train F1 Score : [0.80096502 0.8538398  0.13858268 0.70686337 0.85220126 0.87944493
 0.51627694 0.84532672 0.89064976 0.87179487 0.94561404 0.91331546
 0.84627832 0.89825848 0.9047619  0.79242424 0.84693878 0.84489796
 0.67329545 0.14742015]
#In[]
predict = model.predict(X_test_tfidf)
acc = metrics.accuracy_score(y_test, predict)
f1 = metrics.f1_score(y_test, predict, average=None)

print('Test Accauracy : {}'.format(acc))
print('Test F1 Score : {}'.format(f1))

#Out[]
Test Accauracy : 0.6307753584705258
Test F1 Score : [0.47086247 0.60643564 0.01       0.56014047 0.6953405  0.70381232
 0.44829721 0.71878646 0.81797753 0.81893491 0.90287278 0.74794521
 0.61647059 0.64174455 0.76967096 0.63555114 0.64285714 0.77971474
 0.31382979 0.00793651]

 

4-4. 시각화

#In[]
X, y = make_blobs(n_samples=1000)

plt.scatter(X[:,0], X[:, 1], c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')

#Out[]

#In[1]
model = BernoulliNB()
model.fit(X,y)

#Out[1]
BernoulliNB()

#In[2]
xx, yy = make_meshgrid(X[:,0], X[:, 1])
plot_contours(model, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)
plt.scatter(X[:,0], X[:, 1], c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')

#Out[2]

 

5. 다항 나이브 베이즈

  • 입력 특성이 다항분포에 의해 생성된 빈도수 값을 갖는 다고 가정

5-1. 학습 및 평가 (Count)

#In[]
model = MultinomialNB()
model.fit(X_train_count, y_train)

#Out[]
MultinomialNB()
#In[]
predict = model.predict(X_train_count)
acc = metrics.accuracy_score(y_train, predict)
f1 = metrics.f1_score(y_train, predict, average=None)

print('Train Accauracy : {}'.format(acc))
print('Train F1 Score : {}'.format(f1))

#Out[]
Train Accauracy : 0.9245182959165635
Train F1 Score : [0.95228426 0.904      0.25073746 0.81402003 0.96669513 0.88350983
 0.90710383 0.97014925 0.98567818 0.99325464 0.98423237 0.95399516
 0.95703454 0.98319328 0.98584513 0.95352564 0.97307002 0.97467249
 0.95157895 0.86526946]
#In[]
predict = model.predict(X_test_count)
acc = metrics.accuracy_score(y_test, predict)
f1 = metrics.f1_score(y_test, predict, average=None)

print('Test Accauracy : {}'.format(acc))
print('Test F1 Score : {}'.format(f1))

#Out[]
Test Accauracy : 0.7728359001593202
Test F1 Score : [0.77901431 0.7008547  0.00501253 0.64516129 0.79178082 0.73370166
 0.76550681 0.88779285 0.93951094 0.91390728 0.94594595 0.78459938
 0.72299169 0.84635417 0.86029412 0.80846561 0.78665077 0.89281211
 0.60465116 0.48695652]

 

5-2. 학습 및 평가 (Tf-idf)

#In[]
model = MultinomialNB()
model.fit(X_train_tfidf, y_train)

#Out[]
MultinomialNB()
#In[]
predict = model.predict(X_train_tfidf)
acc = metrics.accuracy_score(y_train, predict)
f1 = metrics.f1_score(y_train, predict, average=None)

print('Train Accauracy : {}'.format(acc))
print('Train F1 Score : {}'.format(f1))

#Out[]
Train Accauracy : 0.9326498143892522
Train F1 Score : [0.87404162 0.95414462 0.95726496 0.92863002 0.97812773 0.97440273
 0.91090909 0.97261411 0.98659966 0.98575021 0.98026316 0.94033413
 0.9594478  0.98032506 0.97755611 0.77411003 0.93506494 0.97453907
 0.90163934 0.45081967]
#In[]
predict = model.predict(X_test_tfidf)
acc = metrics.accuracy_score(y_test, predict)
f1 = metrics.f1_score(y_test, predict, average=None)

print('Test Accauracy : {}'.format(acc))
print('Test F1 Score : {}'.format(f1))

#Out[]
Test Accauracy : 0.7738980350504514
Test F1 Score : [0.63117871 0.72       0.72778561 0.72104019 0.81309686 0.81643836
 0.7958884  0.88135593 0.93450882 0.91071429 0.92917167 0.73583093
 0.69732938 0.81907433 0.86559803 0.60728118 0.76286353 0.92225201
 0.57977528 0.24390244]

 

5-3. 시각화

#In[]
X, y = make_blobs(n_samples=1000)

scaler = MinMaxScaler()
X = scaler.fit_transform(X)

plt.scatter(X[:,0], X[:, 1], c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')

#Out[]

#In[1]
model = MultinomialNB()
model.fit(X, y)

#Out[1]
MultinomialNB()

#In[2]
xx, yy = make_meshgrid(X[:,0], X[:, 1])
plot_contours(model, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)
plt.scatter(X[:,0], X[:, 1], c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')

#Out[2]

 

 

 

### 2021.12.23

 

 

 

최근접 이웃(K-Nearest Neighbor)

  • 특별한 예측 모델 없이 가장 가까운 데이터 포인트를 기반으로 예측을 수행하는 방법
  • 분류와 회귀 모두 지원

import pandas as pd
import numpy as np
import multiprocessing
import matplotlib.pyplot as plt
plt.style.use(['seaborn-whitegrid'])

from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.manifold import TSNE
from sklearn.datasets import load_iris, load_breast_cancer
from sklearn.datasets import load_boston, fetch_california_housing
from sklearn.model_selection import train_test_split, cross_validate, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline, Pipeline

 

K 최근접 이웃 분류

  • 입력 데이터 포인트와 가장 가까운 k개의 훈련 데이터 포인트가 출력
  • k개의 데이터 포인트 중 가장 많은 클래스가 예측 결과

 

붓꽃 데이터

#In[]
iris = load_iris()

iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
iris_df['Target'] = iris.target
iris_df

#Out[]

#In[]
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)

scaler = StandardScaler()
X_train_scale = scaler.fit_transform(X_train)
X_test_scale = scaler.transform(X_test)

model = KNeighborsClassifier()
model.fit(X_train, y_train)

#Out[]
KNeighborsClassifier()

데이터 전처리전 점수

#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

학습 데이터 점수 : 0.9583333333333334
평가 데이터 점수 : 1.0

데이터 전처리후 점수

#In[1]
model = KNeighborsClassifier()
model.fit(X_train_scale, y_train)

#Out[1]
KNeighborsClassifier()

#In[2]
print("학습 데이터 점수 : {}".format(model.score(X_train_scale, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test_scale, y_test)))

#Out[2]
학습 데이터 점수 : 0.9583333333333334
평가 데이터 점수 : 0.9666666666666667
#In[]
cross_validate(estimator=KNeighborsClassifier(),
              X=X, y=y,
              cv=5,
              n_jobs=multiprocessing.cpu_count(),
              verbose=True)
              
#Out[]
{'fit_time': array([0.00156212, 0.00154233, 0.00200725, 0.00164413, 0.00190806]),
 'score_time': array([0.004287  , 0.00399184, 0.00413203, 0.00383401, 0.00303102]),
 'test_score': array([0.96666667, 1.        , 0.93333333, 0.96666667, 1.        ])}
#In[]
param_grid = [{'n_neighbors' : [3,5,7],
              'weights' : ['uniform','distance'],
              'algorithm' : ['ball_tree', 'kd_tree', 'brute']}]
              
gs = GridSearchCV(estimator = KNeighborsClassifier(),
                 param_grid = param_grid,
                 n_jobs=multiprocessing.cpu_count(),
                 verbose=True)
                 
gs.fit(X,y)

#Out[]
Fitting 5 folds for each of 18 candidates, totalling 90 fits
GridSearchCV(estimator=KNeighborsClassifier(), n_jobs=4,
             param_grid=[{'algorithm': ['ball_tree', 'kd_tree', 'brute'],
                          'n_neighbors': [3, 5, 7],
                          'weights': ['uniform', 'distance']}],
             verbose=True)
#In[]
print(gs.best_estimator_)
print(gs.best_score_)
print(gs.best_params_)

#Out[]
KNeighborsClassifier(algorithm='ball_tree', n_neighbors=7)
0.9800000000000001
{'algorithm': 'ball_tree', 'n_neighbors': 7, 'weights': 'uniform'}

시각화를 위한 함수 설정

#In[]
def make_meshgrid(x,y,h=.02):
    x_min, x_max = x.min()-1, x.max()+1
    y_min, y_max = y.min()-1, y.max()+1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                        np.arange(y_min, y_max, h))
    
    return xx, yy
    
def plot_contours(clf, xx, yy, **params):
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    out = plt.contourf(xx, yy, Z, **params)
    
    return out
#In[]
#저차원 변환
tsne = TSNE(n_components=2)
X_comp = tsne.fit_transform(X)

iris_comp_df = pd.DataFrame(data=X_comp)
iris_comp_df['Target'] = y
iris_comp_df

#Out[]

#In[]
plt.scatter(X_comp[:,0], X_comp[:, 1],
           c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')
           
#Out[]

#In[]
model = KNeighborsClassifier()
model.fit(X_comp, y)
predict = model.predict(X_comp)

xx, yy = make_meshgrid(X_comp[:,0], X_comp[:,1])
plot_contours(model, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)
plt.scatter(X_comp[:,0], X_comp[:,1], c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')

#out[]

 

유방암 데이터

#In[]
cancer = load_breast_cancer()

cancer_df = pd.DataFrame(data=cancer.data, columns=cancer.feature_names)
cancer_df['target'] = cancer.target
cancer_df

#Out[]

train data, test data 분리!

#In[]
X, y = cancer.data, cancer.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

cancer_train_df = pd.DataFrame(data=X_train, columns=cancer.feature_names)
cancer_train_df['target'] = y_train
cancer_train_df

#Out[]

#In[]
cancer_test_df = pd.DataFrame(data=X_test, columns=cancer.feature_names)
cancer_test_df['target'] = y_test
cancer_test_df

#Out[]

데이터 전처리 전 점수 / 후 점수

#In[1]
scaler = StandardScaler()
X_train_scale = scaler.fit_transform(X_train)
X_test_scale = scaler.transform(X_test)

model = KNeighborsClassifier()
model.fit(X_train, y_train)

#Out[1]

#In[2]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[2]
학습 데이터 점수 : 0.9516483516483516
평가 데이터 점수 : 0.9035087719298246
#In[1]
model = KNeighborsClassifier()
model.fit(X_train_scale, y_train)

#Out[1]
KNeighborsClassifier()

#In[2]
print("학습 데이터 점수 : {}".format(model.score(X_train_scale, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test_scale, y_test)))

#Out[2]
학습 데이터 점수 : 0.978021978021978
평가 데이터 점수 : 0.9473684210526315

모델링

#In[]
estimator = make_pipeline(StandardScaler(),KNeighborsClassifier())

cross_validate(estimator=estimator,
              X=X, y=y,
              cv=5,
              n_jobs=multiprocessing.cpu_count(),
              verbose=True)
              
#Out[]
{'fit_time': array([0.00185204, 0.00381184, 0.00253701, 0.00249338, 0.00242305]),
 'score_time': array([0.00689292, 0.01440096, 0.012604  , 0.01277781, 0.01411605]),
 'test_score': array([0.96491228, 0.95614035, 0.98245614, 0.95614035, 0.96460177])}
#In[]
pipe = Pipeline(
    [('scaler', StandardScaler()),
     ('model', KNeighborsClassifier())])
     
param_grid = [{'model__n_neighbors' : [3,5,7],
              'model__weights' : ['uniform', 'distance'],
              'model__algorithm' : ['ball_tree', 'kd_tree', 'brute']}]
              
gs = GridSearchCV(estimator = pipe,
                 param_grid = param_grid,
                 n_jobs=multiprocessing.cpu_count(),
                 verbose=True)
#In[]
gs.fit(X,y)

#Out[]
Fitting 5 folds for each of 18 candidates, totalling 90 fits
Out[64]:
GridSearchCV(estimator=Pipeline(steps=[('scaler', StandardScaler()),
                                       ('model', KNeighborsClassifier())]),
             n_jobs=4,
             param_grid=[{'model__algorithm': ['ball_tree', 'kd_tree', 'brute'],
                          'model__n_neighbors': [3, 5, 7],
                          'model__weights': ['uniform', 'distance']}],
             verbose=True)
#In[]
print(gs.best_estimator_)
print(gs.best_score_)
print(gs.best_params_)

#Out[]
Pipeline(steps=[('scaler', StandardScaler()),
                ('model',
                 KNeighborsClassifier(algorithm='ball_tree', n_neighbors=7))])
0.9701288619779538
{'model__algorithm': 'ball_tree', 'model__n_neighbors': 7, 'model__weights': 'uniform'}

시각화

#In[]
tsne = TSNE(n_components=2)
X_comp = tsne.fit_transform(X)

cancer_comp_df = pd.DataFrame(data=X_comp)
cancer_comp_df['target'] = y
cancer_comp_df

#Out[]

#In[]
plt.scatter(X_comp[:,0], X_comp[:,1], c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')

#Out[]

#In[]
model = KNeighborsClassifier()
model.fit(X_comp, y)
predict = model.predict(X_comp)

xx, yy = make_meshgrid(X_comp[:, 0], X_comp[:,1])
plot_contours(model, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)
plt.scatter(X_comp[:,0], X_comp[:, 1], c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')

#Out[]

 

k 최근접 이웃 회귀

  • k 최근접 이웃 분류와 마찬가지로 예측에 이웃 데이터 포인트 사용
  • 이웃 데이터 포인트의 평균이 예측 결과

 

보스턴 주택 가격 데이터

#In[]
boston = load_boston()

boston_df = pd.DataFrame(data=boston.data, columns=boston.feature_names)
boston_df["TARGET"] = boston.target
boston_df

#Out[]

데이터 전처리 전 점수 / 후 점수

#In[1]
scaler = StandardScaler()
X_train_scale = scaler.fit_transform(X_train)
X_test_scale = scaler.transform(X_test)

model = KNeighborsRegressor()
model.fit(X_train, y_train)

#Out[1]
KNeighborsRegressor()

#In[2]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[2]
학습 데이터 점수 : 0.6850536552455034
평가 데이터 점수 : 0.44632061414558033
#In[1]
model = KNeighborsRegressor()
model.fit(X_train_scale, y_train)

#Out[1]
KNeighborsRegressor()

#In[2]
print("학습 데이터 점수 : {}".format(model.score(X_train_scale, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test_scale, y_test)))

#Out[2]
학습 데이터 점수 : 0.8399528467697587
평가 데이터 점수 : 0.7240482286290111

모델링

#In[]
estimator = make_pipeline(StandardScaler(),KNeighborsRegressor())

cross_validate(estimator=estimator,
              X=X, y=y,
              cv=5,
              n_jobs=multiprocessing.cpu_count(),
              verbose=True)
              
#Out[]
{'fit_time': array([0.00622606, 0.00805902, 0.00620103, 0.00619411, 0.00268173]),
 'score_time': array([0.00342488, 0.00330806, 0.00353193, 0.00340295, 0.00339413]),
 'test_score': array([0.56089547, 0.61917359, 0.48661916, 0.46986886, 0.23133037])}
#In[]
pipe = Pipeline(
    [('scaler', StandardScaler()),
     ('model', KNeighborsRegressor())])
     
param_grid = [{'model__n_neighbors' : [3,5,7],
              'model__weights' : ['uniform', 'distance'],
              'model__algorithm' : ['ball_tree', 'kd_tree', 'brute']}]
              
gs = GridSearchCV(estimator = pipe,
                 param_grid = param_grid,
                 n_jobs=multiprocessing.cpu_count(),
                 verbose=True)
#In[]
gs.fit(X,y)

#Out[]
Fitting 5 folds for each of 18 candidates, totalling 90 fits
Out[110]:
GridSearchCV(estimator=Pipeline(steps=[('scaler', StandardScaler()),
                                       ('model', KNeighborsRegressor())]),
             n_jobs=4,
             param_grid=[{'model__algorithm': ['ball_tree', 'kd_tree', 'brute'],
                          'model__n_neighbors': [3, 5, 7],
                          'model__weights': ['uniform', 'distance']}],
             verbose=True)
#In[]
print(gs.best_estimator_)
print(gs.best_score_)
print(gs.best_params_)

#Out[]
Pipeline(steps=[('scaler', StandardScaler()),
                ('model',
                 KNeighborsRegressor(algorithm='ball_tree', n_neighbors=7,
                                     weights='distance'))])
0.4973060611762845
{'model__algorithm': 'ball_tree', 'model__n_neighbors': 7, 'model__weights': 'distance'}

시각화

#In[]
tsne = TSNE(n_components=1)
X_comp = tsne.fit_transform(X)

boston_comp_df = pd.DataFrame(data=X_comp)
boston_comp_df['target'] = y
boston_comp_df

#Out[]

#In[]
plt.scatter(X_comp, y, c='b', cmap=plt.cm.coolwarm, s=20, edgecolors='k')

#Out[]

#In[]
model = KNeighborsRegressor()
model.fit(X_comp, y)
predict = model.predict(X_comp)

plt.scatter(X_comp, y, c='b', cmap=plt.cm.coolwarm, s=20, edgecolors='k')
plt.scatter(X_comp, predict, c='r', cmap=plt.cm.coolwarm, s=20, edgecolors='k')

#Out[]

 

 

 

### 2021.12.22

 

 

 

서포트 벡터 머신(Support Vector Machines)

  • 회귀, 분류, 이상치 탐지 등에 사용되는 지도학습 방법
  • 클래스 사이의 경계에 위치한 데이터 포인트를 서포트 벡터(support vector)라고 함
  • 각 지지 벡터가 클래스 사이의 결정 경계를 구분하는데 얼마나 중요한지를 학습
  • 각 지지 벡터 사이의 마진이 가장 큰 방향으로 학습
  • 지지 벡터 까지의 거리와 지지 벡터의 중요도를 기반으로 예측을 수행

  • H3은 두 클래스의 점들을 제대로 분류하고 있지 않음
  • H1과 H2는 두 클래스의 점들을 분류하는데, H2가 H1보다 더 큰 마진을 갖고 분류하는 것을 확인할 수 있음
import multiprocessing
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use(['seaborn-whitegrid'])

from sklearn.svm import SVR, SVC
from sklearn.datasets import load_boston, load_diabetes
from sklearn.datasets import load_breast_cancer, load_iris, load_wine
from sklearn.pipeline import make_pipeline, Pipeline
from sklearn.model_selection import train_test_split, cross_validate, GridSearchCV
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.manifold import TSNE

SVM을 이용한 회귀 모델과 분류 모델

SVM을 사용한 회귀 모델 (SVR)

#In[]
X, y = load_boston(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=123)

model = SVR()
model.fit(X_train, y_train)

print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.2177283706374875
평가 데이터 점수 : 0.13544178468518187

 

SVM을 사용한 분류 모델 (SVC)

#In[]
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=123)

model = SVC()
model.fit(X_train, y_train)

print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.9014084507042254
평가 데이터 점수 : 0.9230769230769231

 

커널 기법

  • 입력 데이터를 고차원 공간에 사상해서 비선형 특징을 학습할 수 있도록 확장하는 방법
  • scikit-learn에서는 Linear, Polynomial, RBF(Radial Basis Function)등 다양한 커널 기법을 지원

#In[]
X, y = load_boston(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=123)

linear_svr = SVR(kernel='linear')
linear_svr.fit(X_train, y_train)

print('Linear SVR 학습 데이터 점수 : {}'.format(linear_svr.score(X_train, y_train)))
print('Linear SVR 평가 데이터 점수 : {}'.format(linear_svr.score(X_test, y_test)))
print()

polynomial_svr = SVR(kernel='poly')
polynomial_svr.fit(X_train, y_train)

print('Polynomial SVR 학습 데이터 점수 : {}'.format(polynomial_svr.score(X_train, y_train)))
print('Polynomial SVR 평가 데이터 점수 : {}'.format(polynomial_svr.score(X_test, y_test)))
print()

rbf_svr = SVR(kernel='rbf')
rbf_svr.fit(X_train, y_train)

print('RBF SVR 학습 데이터 점수 : {}'.format(rbf_svr.score(X_train, y_train)))
print('RBF SVR 평가 데이터 점수 : {}'.format(rbf_svr.score(X_test, y_test)))

#Out[]
Linear SVR 학습 데이터 점수 : 0.715506620496448
Linear SVR 평가 데이터 점수 : 0.6380398541506058

Polynomial SVR 학습 데이터 점수 : 0.2024454261446289
Polynomial SVR 평가 데이터 점수 : 0.133668450367462

RBF SVR 학습 데이터 점수 : 0.2177283706374875
RBF SVR 평가 데이터 점수 : 0.13544178468518187
#In[]
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=123)

linear_svc = SVC(kernel='linear')
linear_svc.fit(X_train, y_train)

print('Linear SVC 학습 데이터 점수 : {}'.format(linear_svc.score(X_train, y_train)))
print('Linear SVC 평가 데이터 점수 : {}'.format(linear_svc.score(X_test, y_test)))
print()

polynomial_svc = SVC(kernel='poly')
polynomial_svc.fit(X_train, y_train)

print('Polynomial SVC 학습 데이터 점수 : {}'.format(polynomial_svc.score(X_train, y_train)))
print('Polynomial SVC 평가 데이터 점수 : {}'.format(polynomial_svc.score(X_test, y_test)))
print()

rbf_svc = SVC(kernel='rbf')
rbf_svc.fit(X_train, y_train)

print('RBF SVC 학습 데이터 점수 : {}'.format(rbf_svc.score(X_train, y_train)))
print('RBF SVC 평가 데이터 점수 : {}'.format(rbf_svc.score(X_test, y_test)))

#Out[]
Linear SVC 학습 데이터 점수 : 0.960093896713615
Linear SVC 평가 데이터 점수 : 0.986013986013986

Polynomial SVC 학습 데이터 점수 : 0.9014084507042254
Polynomial SVC 평가 데이터 점수 : 0.9230769230769231

RBF SVC 학습 데이터 점수 : 0.9014084507042254
RBF SVC 평가 데이터 점수 : 0.9230769230769231

 

매개변수 튜닝

  • SVM은 사용하는 커널에 따라 다양한 매개변수 설정 가능
  • 매개변수를 변경하면서 성능변화를 관찰
#In[]
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=123)

polynomial_svc = SVC(kernel='poly', degree=2, C=0.1, gamma='auto')
polynomial_svc.fit(X_train, y_train)

print("kernel=poly, degree={}, C={}, gamma={}".format(2, 0.1, 'auto'))
print('Polynomial SVC 학습 데이터 점수 : {}'.format(polynomial_svc.score(X_train, y_train)))
print('Polynomial SVC 평가 데이터 점수 : {}'.format(polynomial_svc.score(X_test, y_test)))

#Out[]
kernel=poly, degree=2, C=0.1, gamma=auto
Polynomial SVC 학습 데이터 점수 : 0.9835680751173709
Polynomial SVC 평가 데이터 점수 : 0.993006993006993
#In[]
rbf_svc = SVC(kernel='rbf', C=2.0, gamma='scale')
rbf_svc.fit(X_train, y_train)

print("kernel=poly, C={}, gamma={}".format(2.0, 'scale'))
print('RBF SVC 학습 데이터 점수 : {}'.format(rbf_svc.score(X_train, y_train)))
print('RBF SVC 평가 데이터 점수 : {}'.format(rbf_svc.score(X_test, y_test)))

#Out[]
kernel=poly, C=2.0, gamma=scale
RBF SVC 학습 데이터 점수 : 0.9154929577464789
RBF SVC 평가 데이터 점수 : 0.9370629370629371

 

데이터 전처리

  • SVM은 입력 데이터가 정규화 되어야 좋은 성능을 보임
  • 주로 모든 특성 값을 [0, 1] 범위로 맞추는 방법을 사용
  • scikit-learn의 StandardScaler 또는 MinMaxScaler를 사용해 정규화
#In[]
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=123)

model = SVC()
model.fit(X_train, y_train)

print('SVC 학습 데이터 점수 : {}'.format(model.score(X_train, y_train)))
print('SVC 평가 데이터 점수 : {}'.format(model.score(X_test, y_test)))

#Out[]
SVC 학습 데이터 점수 : 0.9014084507042254
SVC 평가 데이터 점수 : 0.9230769230769231

전처리후 (StandardScaler)

#In[]
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

model = SVC()
model.fit(X_train, y_train)

print('SVC 학습 데이터 점수 : {}'.format(model.score(X_train, y_train)))
print('SVC 평가 데이터 점수 : {}'.format(model.score(X_test, y_test)))

#Out[]
SVC 학습 데이터 점수 : 0.9835680751173709
SVC 평가 데이터 점수 : 0.986013986013986

전처리후 (MinMaxScaler)

#In[]
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

model = SVC()
model.fit(X_train, y_train)

print('SVC 학습 데이터 점수 : {}'.format(model.score(X_train, y_train)))
print('SVC 평가 데이터 점수 : {}'.format(model.score(X_test, y_test)))

#Out[]
SVC 학습 데이터 점수 : 0.9812206572769953
SVC 평가 데이터 점수 : 0.986013986013986

 

Linear SVR

보스턴 주택 가격

#In[]
X, y = load_boston(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)

scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

model = SVR(kernel='linear')
model.fit(X_train, y_train)

#Out[]
SVR(kernel='linear')
#In[]
print('SVC 학습 데이터 점수 : {}'.format(model.score(X_train, y_train)))
print('SVC 평가 데이터 점수 : {}'.format(model.score(X_test, y_test)))

#Out[]
SVC 학습 데이터 점수 : 0.7049306073822006
SVC 평가 데이터 점수 : 0.7305576277109267
#In[]
#저차원으로 단축
X_comp = TSNE(n_components=1).fit_transform(X)
plt.scatter(X_comp, y)

#Out[]

#In[]
model.fit(X_comp, y)
predict = model.predict(X_comp)
plt.scatter(X_comp, y)
plt.scatter(X_comp, predict, color='r')

#Out[]

#In[]
estimator = make_pipeline(StandardScaler(), SVR(kernel='linear'))

cross_validate(
    estimator=estimator,
    X=X, y=y,
    cv=5,
    n_jobs=multiprocessing.cpu_count(),
    verbose=True)
    
#Out[]
[Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers.
[Parallel(n_jobs=4)]: Done   5 out of   5 | elapsed:    1.8s finished
{'fit_time': array([0.02629495, 0.02607703, 0.02571988, 0.02510285, 0.02014399]),
 'score_time': array([0.00453615, 0.00336313, 0.00348997, 0.00344706, 0.00237799]),
 'test_score': array([0.76908568, 0.72180141, 0.56428426, 0.14083339, 0.07810211])}
#In[]
pipe = Pipeline([('scaler', StandardScaler()),
                ('model', SVR(kernel='linear'))])

param_grid = [{'model__gamma' : ['scale', 'auto'],
              'model__C' : [1.0, 0.1, 0.01],
              'model__epsilon' : [1.0, 0.1, 0.01]}]

gs = GridSearchCV(estimator=pipe,
                 param_grid=param_grid,
                 n_jobs=multiprocessing.cpu_count(),
                 cv=5,
                 verbose=True)

gs.fit(X,y)

#Out[]
Fitting 5 folds for each of 18 candidates, totalling 90 fits
GridSearchCV(cv=5,
             estimator=Pipeline(steps=[('scaler', StandardScaler()),
                                       ('model', SVR(kernel='linear'))]),
             n_jobs=4,
             param_grid=[{'model__C': [1.0, 0.1, 0.01],
                          'model__epsilon': [1.0, 0.1, 0.01],
                          'model__gamma': ['scale', 'auto']}],
             verbose=True)
#In[]
gs.best_estimator_

#Out[]
Pipeline(steps=[('scaler', StandardScaler()),
                ('model', SVR(C=0.1, epsilon=1.0, kernel='linear'))])

 

Kernel SVR

보스턴 주택 가격

#In[]
X, y = load_boston(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)

scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

model = SVR(kernel='rbf')
model.fit(X_train, y_train)

#Out[]
SVR()
#In[]
print('SVC 학습 데이터 점수 : {}'.format(model.score(X_train, y_train)))
print('SVC 평가 데이터 점수 : {}'.format(model.score(X_test, y_test)))

#Out[]
SVC 학습 데이터 점수 : 0.6785031123396097
SVC 평가 데이터 점수 : 0.6548972350224054
#In[]
#저차원으로 단축
X_comp = TSNE(n_components=1).fit_transform(X)
plt.scatter(X_comp, y)

#Out[]

#In[]
model.fit(X_comp, y)
predict = model.predict(X_comp)
plt.scatter(X_comp, y)
plt.scatter(X_comp, predict, color='r')

#Out[]

#In[]
estimator = make_pipeline(StandardScaler(), SVR(kernel='rbf'))

cross_validate(
    estimator=estimator,
    X=X, y=y,
    cv=5,
    n_jobs=multiprocessing.cpu_count(),
    verbose=True)
    
#Out[]
[Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers.
[Parallel(n_jobs=4)]: Done   5 out of   5 | elapsed:    0.1s finished
{'fit_time': array([0.051826  , 0.04972219, 0.03561997, 0.03072095, 0.02156925]),
 'score_time': array([0.01787186, 0.02123976, 0.02434206, 0.01307511, 0.00709677]),
 'test_score': array([ 0.75781445,  0.50211018,  0.04310107,  0.33851703, -0.75997942])}
#In[]
pipe = Pipeline([('scaler', StandardScaler()),
                ('model', SVR(kernel='rbf'))])

param_grid = [{'model__kernel' : ['rbf', 'polynomial', 'sigmoid']}]

gs = GridSearchCV(estimator=pipe,
                 param_grid=param_grid,
                 n_jobs=multiprocessing.cpu_count(),
                 cv=5,
                 verbose=True)

gs.fit(X,y)

#Out[]
Fitting 5 folds for each of 3 candidates, totalling 15 fits
GridSearchCV(cv=5,
             estimator=Pipeline(steps=[('scaler', StandardScaler()),
                                       ('model', SVR())]),
             n_jobs=4,
             param_grid=[{'model__kernel': ['rbf', 'polynomial', 'sigmoid']}],
             verbose=True)
#In[]
print(gs.best_estimator_)
print(gs.best_score_)
print(gs.best_params_)

#Out[]
Pipeline(steps=[('scaler', StandardScaler()), ('model', SVR())])
0.17631266230186618
{'model__kernel': 'rbf'}
#In[]
pipe = Pipeline([('scaler', StandardScaler()),
                ('model', SVR(kernel='rbf'))])

param_grid = [{'model__gamma' : ['scale', 'auto'],
              'model__C' : [1.0, 0.1, 0.01],
              'model__epsilon' : [1.0, 0.1, 0.01]}]

gs = GridSearchCV(estimator=pipe,
                 param_grid=param_grid,
                 n_jobs=multiprocessing.cpu_count(),
                 cv=5,
                 verbose=True)

gs.fit(X,y)

#Out[]
Fitting 5 folds for each of 18 candidates, totalling 90 fits
GridSearchCV(cv=5,
             estimator=Pipeline(steps=[('scaler', StandardScaler()),
                                       ('model', SVR())]),
             n_jobs=4,
             param_grid=[{'model__C': [1.0, 0.1, 0.01],
                          'model__epsilon': [1.0, 0.1, 0.01],
                          'model__gamma': ['scale', 'auto']}],
             verbose=True)
#In[]
print(gs.best_estimator_)
print(gs.best_score_)
print(gs.best_params_)

#Out[]
Pipeline(steps=[('scaler', StandardScaler()), ('model', SVR(epsilon=0.01))])
0.1780747543330848
{'model__C': 1.0, 'model__epsilon': 0.01, 'model__gamma': 'scale'}

 

Linear SVC

유방암

#In[]
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)

scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

model = SVC(kernel='linear')
model.fit(X_train, y_train)

#Out[]
SVC(kernel='linear')
#In[]
print('SVC 학습 데이터 점수 : {}'.format(model.score(X_train, y_train)))
print('SVC 평가 데이터 점수 : {}'.format(model.score(X_test, y_test)))

#Out[]
SVC 학습 데이터 점수 : 0.989010989010989
SVC 평가 데이터 점수 : 0.956140350877193
def make_meshgrid(x,y,h=0.02):
    x_min, x_max = x.min()-1, x.max()+1
    y_min, y_max = y.min()-1, y.max()+1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                        np.arange(y_min, y_max, h))
    
    return xx, yy
    
def plot_contours(clf, xx, yy, **params):
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    out = plt.contourf(xx, yy, Z, **params)
    
    return out
#In[]
#저차원으로 단축
X_comp = TSNE(n_components=2).fit_transform(X)
X0, X1 = X_comp[:,0], X_comp[:,1]
xx, yy = make_meshgrid(X0,X1)

model.fit(X_comp, y)

plot_contours(model, xx, yy, cmap=plt.cm.coolwarm, alpha=0.7)
plt.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')

#Out[]

#In[]
estimator = make_pipeline(StandardScaler(), SVC(kernel='linear'))

cross_validate(
    estimator=estimator,
    X=X, y=y,
    cv=5,
    n_jobs=multiprocessing.cpu_count(),
    verbose=True)
    
#Out[]
{'fit_time': array([0.00987267, 0.00888181, 0.01295686, 0.01195097, 0.01462102]),
 'score_time': array([0.00420117, 0.00178409, 0.00421095, 0.01408386, 0.00151491]),
 'test_score': array([0.96491228, 0.98245614, 0.96491228, 0.96491228, 0.98230088])}
#In[]
pipe = Pipeline([('scaler', StandardScaler()),
                ('model', SVC(kernel='linear'))])

param_grid = [{'model__gamma' : ['scale', 'auto'],
              'model__C' : [1.0, 0.1, 0.01]}]

gs = GridSearchCV(estimator=pipe,
                 param_grid=param_grid,
                 n_jobs=multiprocessing.cpu_count(),
                 cv=5,
                 verbose=True)

gs.fit(X,y)

#Out[]
GridSearchCV(cv=5,
             estimator=Pipeline(steps=[('scaler', StandardScaler()),
                                       ('model', SVC(kernel='linear'))]),
             n_jobs=4,
             param_grid=[{'model__C': [1.0, 0.1, 0.01],
                          'model__gamma': ['scale', 'auto']}],
             verbose=True)
#In[]
print(gs.best_estimator_)
print(gs.best_score_)
print(gs.best_params_)

#Out[]
Pipeline(steps=[('scaler', StandardScaler()),
                ('model', SVC(C=0.1, kernel='linear'))])
0.9736531594472908
{'model__C': 0.1, 'model__gamma': 'scale'}

 

Kernel SVC

유방암

#In[]
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)

scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

model = SVC(kernel='rbf')
model.fit(X_train, y_train)

#Out[]
SVC()
#In[]
print('SVC 학습 데이터 점수 : {}'.format(model.score(X_train, y_train)))
print('SVC 평가 데이터 점수 : {}'.format(model.score(X_test, y_test)))

#Out[]
SVC 학습 데이터 점수 : 0.989010989010989
SVC 평가 데이터 점수 : 0.9473684210526315
#In[]
#저차원으로 단축
X_comp = TSNE(n_components=2).fit_transform(X)
X0, X1 = X_comp[:,0], X_comp[:,1]
xx, yy = make_meshgrid(X0,X1)

model.fit(X_comp, y)

plot_contours(model, xx, yy, cmap=plt.cm.coolwarm, alpha=0.7)
plt.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')

#Out[]

#In[]
estimator = make_pipeline(StandardScaler(), SVC(kernel='rbf'))

cross_validate(
    estimator=estimator,
    X=X, y=y,
    cv=5,
    n_jobs=multiprocessing.cpu_count(),
    verbose=True)
    
#Out[]
{'fit_time': array([0.01440001, 0.01281619, 0.01279497, 0.01421213, 0.01107621]),
 'score_time': array([0.00482988, 0.00510478, 0.0063343 , 0.00894904, 0.00442004]),
 'test_score': array([0.97368421, 0.95614035, 1.        , 0.96491228, 0.97345133])}
#In[]
pipe = Pipeline([('scaler', StandardScaler()),
                ('model', SVC(kernel='rbf'))])

param_grid = [{'model__gamma' : ['scale', 'auto'],
              'model__C' : [1.0, 0.1, 0.01]}]

gs = GridSearchCV(estimator=pipe,
                 param_grid=param_grid,
                 n_jobs=multiprocessing.cpu_count(),
                 cv=5,
                 verbose=True)

gs.fit(X,y)

#OUt[]
GridSearchCV(cv=5,
             estimator=Pipeline(steps=[('scaler', StandardScaler()),
                                       ('model', SVC())]),
             n_jobs=4,
             param_grid=[{'model__C': [1.0, 0.1, 0.01],
                          'model__gamma': ['scale', 'auto']}],
             verbose=True)
#In[]
print(gs.best_estimator_)
print(gs.best_score_)
print(gs.best_params_)

#Out[]
Pipeline(steps=[('scaler', StandardScaler()), ('model', SVC())])
0.9736376339077782
{'model__C': 1.0, 'model__gamma': 'scale'}

 

 

 

 

 

### 2021.12.21

 

 

 

로지스틱 회귀 (Logistic Regression)

  • 로지스틱 회귀는 이름에 회귀라는 단어가 들어가지만, 가능한 클래스가 2개인 이진 분류를 위한 모델
  • 로지스틱 회귀의 예측 함수 정의

  • 𝜎 : 시그모이드 함수
  • 로지스틱 회귀 모델은 선형 회귀 모델에 시그모이드 함수를 적용
  • 로지스틱 회귀의 학습 목표는 다음과 같은 목적 함수를 최소화 하는 파라미터 𝑤w를 찾는 것

로지스틱 회귀 예제

import numpy as np
import matplotlib.pyplot as plt
plt.style.use(['seaborn-whitegrid'])

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LogisticRegression
samples = 1000
X, y = make_classification(n_samples=samples, n_features=2, 
                           n_informative=2, n_redundant=0, 
                           n_clusters_per_class=1)
#In[]
fig, ax = plt.subplots(1, 1, figsize=(10,6))

ax.grid()
ax.set_xlabel('X')
ax.set_ylabel('y')

for i in range(samples):
    if y[i] == 0:
        ax.scatter(X[i,0], X[i, 1], edgecolors='k', alpha=0.5, marker='^', color='r')
    else:
        ax.scatter(X[i,0], X[i, 1], edgecolors='k', alpha=0.5, marker='v', color='b')

plt.show()

#Out[]

#In[]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

model = LogisticRegression()
model.fit(X_train, y_train)

#Out[]
LogisticRegression()
#In[1]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[1]
학습 데이터 점수 : 0.905
평가 데이터 점수 : 0.89

#In[2]
scores = cross_val_score(model, X, y, scoring='accuracy', cv=10)
print("CV 평균 점수 : {}".format(scores.mean()))

#Out[2]
CV 평균 점수 : 0.9030000000000001
#In[]
model.intercept_, model.coef_

#Out[]
(array([0.75015253]), array([[-0.74077567,  3.20790281]]))
#In[]
x_min, x_max = X[:, 0].min() - 0.5, X[:,0].max() + 0.5
y_min, y_max = X[:, 1].min() - 0.5, X[:,1].max() + 0.5

xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])

Z = Z.reshape(xx.shape)

plt.figure(1, figsize=(10,6))
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Pastel1)

plt.scatter(X[:,0], X[:,1], c=np.abs(y-1), edgecolors='k', alpha=0.5, cmap=plt.cm.coolwarm)
plt.xlabel('X')
plt.ylabel('Y')

plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.xticks()
plt.yticks()

plt.show()

#Out[]

붓꽃 데이터

#In[]
from sklearn.datasets import load_iris

iris = load_iris()
print(iris.keys())
print(iris.DESCR)

#Out[]
dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename', 'data_module'])
.. _iris_dataset:

Iris plants dataset
--------------------

**Data Set Characteristics:**

    :Number of Instances: 150 (50 in each of three classes)
    :Number of Attributes: 4 numeric, predictive attributes and the class
    :Attribute Information:
        - sepal length in cm
        - sepal width in cm
        - petal length in cm
        - petal width in cm
        - class:
                - Iris-Setosa
                - Iris-Versicolour
                - Iris-Virginica
                
    :Summary Statistics:

    ============== ==== ==== ======= ===== ====================
                    Min  Max   Mean    SD   Class Correlation
    ============== ==== ==== ======= ===== ====================
    sepal length:   4.3  7.9   5.84   0.83    0.7826
    sepal width:    2.0  4.4   3.05   0.43   -0.4194
    petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)
    petal width:    0.1  2.5   1.20   0.76    0.9565  (high!)
    ============== ==== ==== ======= ===== ====================
#In[]
import pandas as pd

iris_df = pd.DataFrame(iris.data, columns=iris.feature_names)
species = pd.Series(iris.target, dtype='category')
species = species.cat.rename_categories(iris.target_names)
iris_df['species'] = species

iris_df.describe()

#Out[]

#In[]
iris_df.boxplot()

#Out[]

#In[]
iris_df.plot()   #3그룹이 있다는 것을 볼 수 있다.

#Out[]

#In[]
import seaborn as sns
sns.pairplot(iris_df, hue='species')

#Out

붓꽃 데이터에 대한 로지스틱 회귀

#In[]
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(iris.data[:,[2,3]], 
                                                    iris.target, test_size=0.2, 
                                                    random_state=1, stratify=iris.target) #계층구조할때 도움
#In[]
from sklearn.linear_model import LogisticRegression

model = LogisticRegression(solver='lbfgs', multi_class='auto', C=100.0, random_state=1)
model.fit(X_train, y_train)

#Out[]
LogisticRegression(C=100.0, random_state=1)
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.9666666666666667
평가 데이터 점수 : 0.9666666666666667
#In[]
import numpy as np
X = np.vstack((X_train, X_test))
y = np.hstack((y_train, y_test))
#In[]
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt

x1_min, x1_max = X[:, 0].min()-1, X[:,0].max()+1
x2_min, x2_max = X[:, 1].min()-1, X[:,1].max()+1

xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, 0.02),
                      np.arange(x2_min, x2_max, 0.02))
Z = model.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
Z = Z.reshape(xx1.shape)

species = ('Setosa', 'Versicolour', 'Virginica')
markers = ('^', 'v', 's')
colors = ('blue', 'purple', 'red')
cmap = ListedColormap(colors[:len(np.unique(y))])
plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())

for idx, cl in enumerate(np.unique(y)):
    plt.scatter(x=X[y == cl, 0], y=X[y ==cl, 1],
               alpha=0.8, c=colors[idx],
               marker=markers[idx], label=species[cl],
               edgecolor='b')

X_comb_test, y_comb_test = X[range(105, 150), :], y[range(105, 150)]
plt.scatter(X_comb_test[:, 0], X_comb_test[:, 1],
           c ='yellow', edgecolor='k', alpha=0.2,
           linewidth=1, marker='o',
           s=100, label='Test')

plt.xlabel('Petal Length (cm)')
plt.ylabel('petal Width (cm)')
plt.legend(loc='upper left')
plt.tight_layout()

#In[]
import multiprocessing
from sklearn.model_selection import GridSearchCV

param_grid = [{'penalty' : ['l1', 'l2'],
              'C' : [2.0, 2.2, 2.4, 2.6, 2.8]}]

gs = GridSearchCV(estimator=LogisticRegression(), param_grid=param_grid,
                 scoring='accuracy', cv=10, n_jobs=multiprocessing.cpu_count())

gs

#Out[]
GridSearchCV(cv=10, estimator=LogisticRegression(), n_jobs=4,
             param_grid=[{'C': [2.0, 2.2, 2.4, 2.6, 2.8],
                          'penalty': ['l1', 'l2']}],
             scoring='accuracy')
#In[]
result = gs.fit(iris.data, iris.target)

print(gs.best_estimator_)
print("최적 점수 : {}".format(gs.best_score_))
print("최적 점수 : {}".format(gs.best_params_))

pd.DataFrame(result.cv_results_)

#Out[]
LogisticRegression(C=2.4)
최적 점수 : 0.9800000000000001
최적 점수 : {'C': 2.4, 'penalty': 'l2'}

 

유방암 데이터

#In[]
from sklearn.datasets import load_breast_cancer

cancer = load_breast_cancer()
print(cancer.keys())
print(cancer.DESCR)

#Out[]
dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename', 'data_module'])
.. _breast_cancer_dataset:

Breast cancer wisconsin (diagnostic) dataset
--------------------------------------------

**Data Set Characteristics:**

    :Number of Instances: 569

    :Number of Attributes: 30 numeric, predictive attributes and the class

    :Attribute Information:
        - radius (mean of distances from center to points on the perimeter)
        - texture (standard deviation of gray-scale values)
        - perimeter
        - area
        - smoothness (local variation in radius lengths)
        - compactness (perimeter^2 / area - 1.0)
        - concavity (severity of concave portions of the contour)
        - concave points (number of concave portions of the contour)
        - symmetry
        - fractal dimension ("coastline approximation" - 1)

        The mean, standard error, and "worst" or largest (mean of the three
        worst/largest values) of these features were computed for each image,
        resulting in 30 features.  For instance, field 0 is Mean Radius, field
        10 is Radius SE, field 20 is Worst Radius.

        - class:
                - WDBC-Malignant
                - WDBC-Benign
#In[]
import pandas as pd

cancer_df = pd.DataFrame(cancer.data, columns=cancer.feature_names)
cancer_df['Target'] = cancer.target
cancer_df.head()

#Out[]

#In[]
cancer_df.describe()

#Out[]
#In[]
fig = plt.figure(figsize=[10,6])
plt.title('Breast Cancer', fontsize=15)
plt.boxplot(cancer.data)
plt.xticks(np.arange(30)+1, cancer.feature_names, rotation=90)
plt.xlabel('Features')
plt.ylabel('Scale')
plt.tight_layout()

#Out[]

유방암 데이터에 대한 로지스틱 회귀

#In[]
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y)

model = LogisticRegression(max_iter=3000)
model.fit(X_train, y_train)

#Out[]
LogisticRegression(max_iter=3000)
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.960093896713615
평가 데이터 점수 : 0.965034965034965
 

확률적 경사 하강법 (Stochastic Gradient Descent)

  • 모델을 학습 시키기 위한 간단한 방법
  • 학습 파라미터에 대한 손실 함수의 기울기를 구해 기울기가 최소화 되는 방향으로 학습

  • scikit-learn에서는 선형 SGD 회귀와 SGD 분류를 지원

SGD를 사용한 선형 회귀 분석

#In[]
from sklearn.linear_model import SGDRegressor
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

X, y = load_boston(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y)

model = make_pipeline(StandardScaler(), SGDRegressor(loss='squared_loss'))
model.fit(X_train, y_train)

#Out[]
Pipeline(steps=[('standardscaler', StandardScaler()),
                ('sgdregressor', SGDRegressor(loss='squared_loss'))])
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.7325588416046254
평가 데이터 점수 : 0.7358013246276491

 

붓꽃 데이터에 대한 SGD 분류

#In[]
from sklearn.linear_model import SGDClassifier
from sklearn.datasets import load_iris, load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y)

model = make_pipeline(StandardScaler(), SGDClassifier(loss='log'))
model.fit(X_train, y_train)

#Out[]
Pipeline(steps=[('standardscaler', StandardScaler()),
                ('sgdclassifier', SGDClassifier(loss='log'))])
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.9464285714285714
평가 데이터 점수 : 0.9210526315789473

 

유방암 데이터에 대한 SGD 분류

#In[]
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y)

model = make_pipeline(StandardScaler(), SGDClassifier(loss='log'))
model.fit(X_train, y_train)

#Out[]
Pipeline(steps=[('standardscaler', StandardScaler()),
                ('sgdclassifier', SGDClassifier(loss='log'))])
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.9812206572769953
평가 데이터 점수 : 0.972027972027972

 

 

 

 

 

 

### 2021.12.20

 

 

선형 모델(Linear Models)

  • 선형 모델은 과거 부터 지금 까지 널리 사용되고 연구 되고 있는 기계학습 방법
  • 선형 모델은 입력 데이터에 대한 선형 함수를 만들어 예측 수행
  • 회귀 분석을 위한 선형 모델은 다음과 같이 정의

  • 𝑥: 입력 데이터
  • 𝑤: 모델이 학습할 파라미터
  • 𝑤0: 편향
  • 𝑤1~𝑤𝑝: 가중치

 

선형 회귀(Linear Regression)

  • 선형 회귀(Linear Regression)또는 최소제곱법(Ordinary Least Squares)은 가장 간단한 회귀 분석을 위한 선형 모델
  • 선형 회귀는 모델의 예측과 정답 사이의 평균제곱오차(Mean Squared Error)를 최소화 하는 학습 파라미터 𝑤 를 찾음
  • 평균제곱오차는 아래와 같이 정의

  • 𝑦: 정답
  • 𝑦̂: 예측 값을 의미
  • 선형 회귀 모델에서 사용하는 다양한 오류 측정 방법
    • MAE(Mean Absoulte Error)
    • MAPE(Mean Absolute Percentage Error)
    • MSE(Mean Squared Error)
    • MPE(Mean Percentage Error)
#In[1]
import numpy as np
import matplotlib.pyplot as plt
plt.style.use(['seaborn-whitegrid'])

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

noise = np.random.rand(100, 1)
X = sorted(10 * np.random.rand(100,1)) + noise
y = sorted(10 * np.random.rand(100))

#In[2]
plt.scatter(X,y)

#Out[2]

#In[]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

model = LinearRegression()
model.fit(X_train, y_train)

#Out[]
LinearRegression()
#In[1]
print("선형 회귀 가중치 : {}".format(model.coef_))
print("선형 회귀 편향 : {}".format(model.intercept_))
#Out[1]
선형 회귀 가중치 : [1.02525962]
선형 회귀 편향 : -0.26433640350999

#In[2]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))
#Out[2]
학습 데이터 점수 : 0.9782833986327462
평가 데이터 점수 : 0.976790278445786
#In[]
predict = model.predict(X_test)

plt.scatter(X_test, y_test)
plt.plot(X_test, predict, '--r')

#Out[]

 

 

보스턴 주택 가격 데이터

  • 주택 가격 데이터는 도시에 대한 분석과 부동산, 경제적인 정보 분석 등 많은 활용 가능한 측면들이 존재
  • 보스턴 주택 가격 데이터는 카네기 멜론 대학교에서 관리하는 StatLib 라이브러리에서 가져온 것
  • 헤리슨(Harrison, D.)과 루빈펠트(Rubinfeld, D. L.)의 논문 "Hedonic prices and the demand for clean air', J. Environ. Economics & Management"에서 보스턴 데이터가 사용
  • 1970년도 인구 조사에서 보스턴의 506개 조사 구역과 주택 가격에 영향을 주는 속성 21개로 구성

#In[]
from sklearn.datasets import load_boston

boston = load_boston()
print(boston.keys())
print(boston.DESCR)

#Out[]
dict_keys(['data', 'target', 'feature_names', 'DESCR', 'filename', 'data_module'])
.. _boston_dataset:

Boston house prices dataset
---------------------------

**Data Set Characteristics:**  

    :Number of Instances: 506 

    :Number of Attributes: 13 numeric/categorical predictive. Median Value (attribute 14) is usually the target.

    :Attribute Information (in order):
        - CRIM     per capita crime rate by town
        - ZN       proportion of residential land zoned for lots over 25,000 sq.ft.
        - INDUS    proportion of non-retail business acres per town
        - CHAS     Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
        - NOX      nitric oxides concentration (parts per 10 million)
        - RM       average number of rooms per dwelling
        - AGE      proportion of owner-occupied units built prior to 1940
        - DIS      weighted distances to five Boston employment centres
        - RAD      index of accessibility to radial highways
        - TAX      full-value property-tax rate per $10,000
        - PTRATIO  pupil-teacher ratio by town
        - B        1000(Bk - 0.63)^2 where Bk is the proportion of black people by town
        - LSTAT    % lower status of the population
        - MEDV     Median value of owner-occupied homes in $1000's
#In[]
import pandas as pd

boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)
boston_df['MEDV'] = boston.target
boston_df.head()

#Out[]

#In[]
boston_df.describe()

#Out[]

#In[]
for i, col in enumerate(boston_df.columns):
    plt.figure(figsize=(8,4))
    plt.plot(boston_df[col])
    plt.title(col)
    plt.xlabel('Town')
    plt.tight_layout()

#Out[]
각 feature에 대한 그래프 출력

#In[]
for i, col in enumerate(boston_df.columns):
    plt.figure(figsize=(8,4))
    plt.scatter(boston_df[col], boston_df['MEDV'])
    plt.ylabel('MEDV', size = 12)
    plt.xlabel(col, size = 12)
    plt.tight_layout()
    
#Out[]
각 feature에 대한 그래프 출력

#In[]
import seaborn as sns
sns.pairplot(boston_df)

#Out[]
13 X 13 에 대한 그래프 출력

 

보스턴 주택 가격에 대한 선형 회귀

#In[]
from sklearn.linear_model import LinearRegression
medel = LinearRegression(normalize=True)

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.3)
model.fit(X_train, y_train)

#Out[]
LinearRegression()
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.720438846769244
평가 데이터 점수 : 0.7741844698985254
  • 데이터를 두개로 분리하고 모델을 생성 및 검증하였지만, 데이터를 분리하였기 때문에 훈련에 사용할 수 있는 양도 작아지고, 분리가 잘 안된 경우에는 잘못된 검증이 될 수 있음
  • 이럴 경우에는 테스트셋을 여러개로 구성하여 교차 검증을 진행
  • cross_val_score() 함수는 교차 검증을 수행하여 모델을 검증
  • 다음 예제에서는 모델 오류를 측정하는 점수로 NMSE(Negative Mean Squared Error)를 사용
#In[]
from sklearn.model_selection import cross_val_score

scores = cross_val_score(model, boston.data, boston.target, cv=10, scoring='neg_mean_squared_error')
print('NMSE scores : {}'.format(scores))
print('NMSE scores mean : {}'.format(scores.mean()))
print('NMSE scores std : {}'.format(scores.std()))

#Out[]
NMSE scores : [  -9.28694671  -14.15128316  -14.07360615  -35.20692433  -31.88511666
  -19.83587796   -9.94726918 -168.37537954  -33.32974507  -10.96041068]
NMSE scores mean : -34.705255944524914
NMSE scores std : 45.57399920030867
  • 회귀모델의 검증을 위한 또 다른 측정 지표 중 하나로 결정 계수(coefficient of determination, 𝑅2R2) 사용
#In[]
r2_scores = cross_val_score(model, boston.data, boston.target, cv=10, scoring='r2')

print('R2 scores : {}'.format(r2_scores))
print('R2 scores mean : {}'.format(r2_scores.mean()))
print('R2 scores std : {}'.format(r2_scores.std()))

#Out[]
R2 scores : [ 0.73376082  0.4730725  -1.00631454  0.64113984  0.54766046  0.73640292
  0.37828386 -0.12922703 -0.76843243  0.4189435 ]
R2 scores mean : 0.20252899006055863
R2 scores std : 0.5952960169512364

생성된 회귀 모델에 대해서 평가를 위해 LinearRegression 객체에 포함된 두 개의 속성 값을 통해 수식을 표현

  • intercept_: 추정된 상수항
  • coef_: 추정된 가중치 벡터
#In[]
print('y = ' + str(model.intercept_) + ' ')
for i, c in enumerate(model.coef_):
    print(str(c) + ' * x' + str(i))
    
#Out[]
y = 42.321077872060854 
-0.10105235411092622 * x0
0.04348245969543986 * x1
0.018691385811833685 * x2
3.0976529601010103 * x3
-19.887702239501845 * x4
3.136164405534508 * x5
0.008906966537697883 * x6
-1.4967491742091585 * x7
0.28631777507480266 * x8
-0.008359295564382759 * x9
-1.0235500260398487 * x10
0.009269802610719184 * x11
-0.6134051726203665 * x12
  • RMSE와 R2 score 비교
#In[]
from sklearn.metrics import mean_squared_error, r2_score

y_train_predict = model.predict(X_train)
rmse = (np.sqrt(mean_squared_error(y_train, y_train_predict)))
r2 = r2_score(y_train, y_train_predict)

print('RMSE : {}'.format(rmse))
print('R2 score : {}'.format(r2))

#Out[]
RMSE : 4.8217885054922185
R2 score : 0.720438846769244
#In[]
from sklearn.metrics import mean_squared_error, r2_score

y_test_predict = model.predict(X_test)
rmse = (np.sqrt(mean_squared_error(y_test, y_test_predict)))
r2 = r2_score(y_test, y_test_predict)

print('RMSE : {}'.format(rmse))
print('R2 score : {}'.format(r2))

#Out[]
RMSE : 4.440697444558274
R2 score : 0.7741844698985254
  • True price VS Predicted price
#In[]
def plot_boston_prices(expected, predicted):
    plt.figure(figsize=(8, 4))
    plt.scatter(expected, predicted)
    plt.plot([5, 50], [5, 50], '--r')
    plt.xlabel('True price ($1,000s)')
    plt.ylabel('Predicted price ($1,000s)')
    plt.tight_layout()
    
predicted = model.predict(X_test)
expected = y_test

plot_boston_prices(expected, predicted)

#Out[]

 

캘리포니아 주택 가격 데이터

#In[]
from sklearn.datasets import fetch_california_housing

california = fetch_california_housing()
print(california.keys())
print(california.DESCR)

#Out[]
dict_keys(['data', 'target', 'frame', 'target_names', 'feature_names', 'DESCR'])
.. _california_housing_dataset:

California Housing dataset
--------------------------

**Data Set Characteristics:**

    :Number of Instances: 20640

    :Number of Attributes: 8 numeric, predictive attributes and the target

    :Attribute Information:
        - MedInc        median income in block group
        - HouseAge      median house age in block group
        - AveRooms      average number of rooms per household
        - AveBedrms     average number of bedrooms per household
        - Population    block group population
        - AveOccup      average number of household members
        - Latitude      block group latitude
        - Longitude     block group longitude

    :Missing Attribute Values: None

This dataset was obtained from the StatLib repository.
https://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.html

The target variable is the median house value for California districts,
expressed in hundreds of thousands of dollars ($100,000).
#In[]
import pandas as pd

california_df = pd.DataFrame(california.data, columns = california.feature_names)
california_df['Target'] = california.target
california_df.head()

#Out[]

#In[]
california_df.describe()

#Out[]

#In[]
import matplotlib.pyplot as plt

for i, col in enumerate(california_df.columns):
    plt.figure(figsize=(8,5))
    plt.plot(california_df[col])
    plt.title(col)
    plt.tight_layout()
    
#Out[]
각 feature마다 그래프 출력

#In[]
import matplotlib.pyplot as plt

for i, col in enumerate(california_df.columns):
    plt.figure(figsize=(8,5))
    plt.scatter(california_df[col], california_df['Target'])
    plt.ylabel('Target', size=12)
    plt.xlabel(col,size=12)
    plt.title(col)
    plt.tight_layout()
    
#Out[]
각 feature마다 그래프 출력

#In[]
import seaborn as sns

sns.pairplot(california_df.sample(1000))

#Out[]
9 X 9개의 그래프 출력

#In[]
california_df.plot(kind='scatter', x='Longitude', y='Latitude', alpha=0.2,figsize=(12,10))

#Out[]

#In[]
california_df.plot(kind='scatter', x='Longitude', y='Latitude', alpha=0.2,
                   s=california_df['Population']/100, label='Population', figsize=(15,10),
                  c ='Target', cmap=plt.get_cmap('viridis'), colorbar=True)

#Out[]

 

캘리포니아 주택 가격에 대한 선형 회귀

#In[]
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

model= LinearRegression(normalize=True)
X_train, X_test, y_train, y_test = train_test_split(california.data, california.target, test_size=0.3)

model.fit(X_train, y_train)
print('학습 데이터 점수 : {}'.format(model.score(X_train, y_train)))
print('평가 데이터 점수 : {}'.format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.602352118468718
평가 데이터 점수 : 0.610740117378534
#In[]
from sklearn.model_selection import cross_val_score
from sklearn.metrics import mean_squared_error, r2_score

scores = cross_val_score(model, california.data, california.target, cv=10, scoring='neg_mean_squared_error')
print('NMSE mean : {}'.format(scores.mean()))
print('NMSE std : {}'.format(scores.std()))

r2_scores = cross_val_score(model, california.data, california.target, cv=10, scoring='r2')
print('R2 scores mean : {}'.format(r2_scores.mean()))

#Out[]
NMSE mean : -0.5509524296956647
NMSE std : 0.1928858295386515
R2 scores mean : 0.5110068610523766
#In[]
print('y = ' + str(model.intercept_) + ' ')

for i, c in enumerate(model.coef_):
    print()
    print(str(c) + ' * x' + str(i))
    
#Out[]
y = -36.616310741696665 
0.4317758638891808 * x0
0.00964217100767699 * x1
-0.09741188206108871 * x2
0.5806927638866005 * x3
7.059369595195281e-09 * x4
-0.007614430045996266 * x5
-0.42123968100938536 * x6
-0.4320836864988495 * x7
#In[]
y_test_predict = model.predict(X_test)

rmse = (np.sqrt(mean_squared_error(y_test, y_test_predict)))
r2 = r2_score(y_test, y_test_predict)

print( 'RMSE : {}'.format(rmse))
print('R2 Score : {}'.format(r2))

#Out[]
RMSE : 0.7223037740611354
R2 Score : 0.610740117378534
#In[]
def plot_california_prices(expected, predicted):
    plt.figure(figsize=(8, 4))
    plt.scatter(expected, predicted)
    plt.plot([0, 5], [0, 5], '--r')
    plt.xlabel('True price ($100,000)')
    plt.ylabel('Predicted price ($100,000)')
    plt.tight_layout()
    
predicted = model.predict(X_test)
expected = y_test

plot_california_prices(expected, predicted)

#Out[]

 

릿지 회귀(Ridge Regression)

  • 릿지 회귀는 선형 회귀를 개선한 선형 모델
  • 릿지 회귀는 선형 회귀와 비슷하지만, 가중치의 절대값을 최대한 작게 만든다는 것이 다름
  • 이러한 방법은 각각의 특성(feature)이 출력 값에 주는 영향을 최소한으로 만들도록 규제(regularization)를 거는 것
  • 규제를 사용하면 다중공선성(multicollinearity) 문제를 방지하기 때문에 모델의 과대적합을 막을 수 있게 됨
  • 다중공선성 문제는 두 특성이 일치에 가까울 정도로 관련성(상관관계)이 높을 경우 발생
  • 릿지 회귀는 다음과 같은 함수를 최소화 하는 파라미터 𝑤를 찾음

  • 𝛼: 사용자가 지정하는 매개변수
  • 𝛼가 크면 규제의 효과가 커지고, 𝛼가 작으면 규제의 효과가 작아짐

보스턴 주택 가격에 대한 릿지 회귀

#In[]
from sklearn.linear_model import Ridge
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split

X, y = load_boston(return_X_y=True)    #data와 target을 분리해줌!
X_train, X_test, y_train, y_test = train_test_split(X,y)

model = Ridge(alpha=0.2)
model.fit(X_train, y_train)

#Out[]
Ridge(alpha=0.2)
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.7368424082987279
평가 데이터 점수 : 0.7444343121697423
#In[]
predicted = model.predict(X_test)
expected = y_test

plot_boston_prices(expected, predicted)

#Out[]

  • 릿지 회귀는 가중치에 제약을 두기 때문에 선형 회귀 모델보다 훈련 데이터 점수가 낮을 수 있음
  • 일반화 성능은 릿지 회귀가 더 높기 때문에 평가 데이터 점수는 릿지 회귀가 더 좋음
  • 일반화 성능에 영향을 주는 매개 변수인 𝛼α 값을 조정해 보면서 릿지 회귀 분석의 성능이 어떻게 변하는지 확인 필요

 

캘리포니아 주택 가격에 대한 릿지 회귀

#In[]
from sklearn.datasets import fetch_california_housing

california = fetch_california_housing()
X_train, X_test, y_train, y_test = train_test_split(california.data, california.target, test_size=0.3)

model = Ridge(alpha=0.1)
model.fit(X_train, y_train)

#Out[]
Ridge(alpha=0.1)
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.604057267179928
평가 데이터 점수 : 0.6107536986926523
#In[]
predicted = model.predict(X_test)
expected = y_test

plot_california_prices(expected, predicted)


#Out[]

 

라쏘 회귀(Lasso Regression)

  • 선형 회귀에 규제를 적용한 또 다른 모델로 라쏘 회귀가 있음
  • 라쏘 회귀는 릿지 회귀와 비슷하게 가중치를 0에 가깝게 만들지만, 조금 다른 방식을 사용
  • 라쏘 회귀에서는 다음과 같은 함수를 최소화 하는 파라미터 𝑤를 찾음

  • 라쏘 회귀도 매개변수인 𝛼 값을 통해 규제의 강도 조절 가능

보스턴 주택 가격에 대한 라쏘 회귀

#In[]
from sklearn.linear_model import Lasso
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split

X, y = load_boston(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y)

model = Lasso(alpha=0.003)
model.fit(X_train, y_train)

#Out[]
Lasso(alpha=0.003)
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.7272293998519503
평가 데이터 점수 : 0.771712660021631
#In[]
predicted = model.predict(X_test)
expected = y_test

plot_boston_prices(expected, predicted)

#Out[]

캘리포니아 주택 가격에 대한 라쏘 회귀

#In[]
from sklearn.datasets import fetch_california_housing

california = fetch_california_housing()
X_train, X_test, y_train, y_test = train_test_split(california.data, california.target, test_size=0.3)

model = Lasso(alpha=0.001)
model.fit(X_train, y_train)

#Out[]
Lasso(alpha=0.001)
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.6142220442075574
평가 데이터 점수 : 0.5805641764424498
#In[]
predicted = model.predict(X_test)
expected = y_test

plot_california_prices(expected, predicted)

#Out[]

 

신축망 (Elastic-Net)

  • 신축망은 릿지 회귀와 라쏘 회귀, 두 모델의 모든 규제를 사용하는 선형 모델
  • 두 모델의 장점을 모두 갖고 있기 때문에 좋은 성능을 보임
  • 데이터 특성이 많거나 서로 상관 관계가 높은 특성이 존재 할 때 위의 두 모델보다 좋은 성능을 보여 줌
  • 신축망은 다음과 같은 함수를 최소화 하는 파라미터 𝑤를 찾음

  • 𝛼: 규제의 강도를 조절하는 매개변수
  • 𝜌: 라쏘 규제와 릿지 규제 사이의 가중치를 조절하는 매개변수

보스턴 주택 가격에 대한 신축망

#In[]
from sklearn.linear_model import ElasticNet
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split

X, y = load_boston(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y)

model = ElasticNet(alpha=0.01, l1_ratio=0.5)
model.fit(X_train, y_train)

#Out[]
ElasticNet(alpha=0.01)
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.7267947849019141
평가 데이터 점수 : 0.7183794503068747
#In[]
predicted = model.predict(X_test)
expected = y_test

plot_boston_prices(expected, predicted)

#Out[]

캘리포니아 주택 가격에 대한 신축망

#In[]
from sklearn.linear_model import ElasticNet
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split

california = fetch_california_housing()
X_train, X_test, y_train, y_test = train_test_split(california.data, california.target, test_size=0.3)

model = ElasticNet(alpha=0.01, l1_ratio=0.5)
model.fit(X_train, y_train)

#Out[]
ElasticNet(alpha=0.01)
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.6020991031939832
평가 데이터 점수 : 0.6116388975222378
#In[]
predicted = model.predict(X_test)
expected = y_test

plot_california_prices(expected, predicted)

#Out[]

 

직교 정합 추구 (Orthogonal Matching Pursuit)

  • 직교 정합 추구 방법은 모델에 존재하는 가중치 벡터에 특별한 제약을 거는 방법
  • 직교 정합 추구 방법은 다음을 만족하는 파라미터 𝑤를 찾는것이 목표

  • ||𝑤||0: 가중치 벡터 𝑤에서 0이 아닌 값의 개수
  • 직교 정합 추구 방법은 가중치 벡터 𝑤에서 0이 아닌 값이 𝑘개 이하가 되도록 훈련됨
  • 이러한 방법은 모델이 필요 없는 데이터 특성을 훈련 과정에서 자동으로 제거 하도록 만들 수 있음

보스턴 주택 가격에 대한 직교 정합 추구

#In[]
from sklearn.linear_model import OrthogonalMatchingPursuit
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split

X, y = load_boston(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X,y)

model = OrthogonalMatchingPursuit(n_nonzero_coefs=7)
model.fit(X_train, y_train)

#Out[]
OrthogonalMatchingPursuit(n_nonzero_coefs=7)
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.7067701687499545
평가 데이터 점수 : 0.7647457085035291
#In[]
predicted = model.predict(X_test)
expected = y_test

plot_boston_prices(expected, predicted)

#Out[]

#In[1]
model = OrthogonalMatchingPursuit(tol=1.)
model.fit(X_train, y_train)

#Out[1]
OrthogonalMatchingPursuit(tol=1.0)

#In[2]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점 수 : {}".format(model.score(X_test, y_test)))

#Out[2]
학습 데이터 점수 : 0.7255197300235632
평가 데이터 점수 : 0.7831647013824865

#In[3]
predicted = model.predict(X_test)
expected = y_test

plot_boston_prices(expected, predicted)

#Out[3]

캘리포니아 주택 가격에 대한 직교 정합 추구

#In[]
from sklearn.linear_model import OrthogonalMatchingPursuit
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split

california = fetch_california_housing()
X_train, X_test, y_train, y_test = train_test_split(california.data, california.target, test_size=0.3)

model = OrthogonalMatchingPursuit(n_nonzero_coefs=7)
model.fit(X_train, y_train)

#Out[]
OrthogonalMatchingPursuit(n_nonzero_coefs=7)
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점 수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.6043415390059861
평가 데이터 점 수 : 0.6097795468666676
#In[]
predicted = model.predict(X_test)
expected = y_test

plot_california_prices(expected, predicted)

#Out[]

#In[1]
model = OrthogonalMatchingPursuit(tol=1.)
model.fit(X_train, y_train)

#Out[1]
OrthogonalMatchingPursuit(tol=1.0)

#In[2]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[2]
학습 데이터 점수 : 0.6043682122857658
평가 데이터 점수 : 0.6097528736622835

#In[3]
predicted = model.predict(X_test)
expected = y_test

plot_california_prices(expected, predicted)

#Out[3]

 

다항 회귀 (Polynomial Regression)

  • 입력 데이터를 비선형 변환 후 사용하는 방법
  • 모델 자체는 선형 모델

  • 차수가 높아질수록 더 복잡한 데이터 학습 가능

보스턴 주택 가격에 대한 다항 회귀

#In[]
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_boston

X, y = load_boston(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=123) #고정된 형태
#In[]
model = make_pipeline(
        PolynomialFeatures(degree=2),
        StandardScaler(),
        LinearRegression())

model.fit(X_train, y_train)

#Out[]
Pipeline(steps=[('polynomialfeatures', PolynomialFeatures()),
                ('standardscaler', StandardScaler()),
                ('linearregression', LinearRegression())])
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.9346787783950696
평가 데이터 점수 : 0.825786471800239
#In[]
predicted = model.predict(X_test)
expected = y_test

plot_boston_prices(expected, predicted)

#Out[]

캘리포니아 주택 가격에 대한 다항 회귀

#In[]
from sklearn.datasets import fetch_california_housing

california = fetch_california_housing()
X_train, X_test, y_train, y_test = train_test_split(california.data, california.target, test_size=0.3)

model = make_pipeline(
        PolynomialFeatures(degree=2),
        StandardScaler(),
        LinearRegression())

model.fit(X_train, y_train)

#Out[]
Pipeline(steps=[('polynomialfeatures', PolynomialFeatures()),
                ('standardscaler', StandardScaler()),
                ('linearregression', LinearRegression())])
#In[]
print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

#Out[]
학습 데이터 점수 : 0.6846989126772143
평가 데이터 점수 : 0.6705076858975946
#In[]
predicted = model.predict(X_test)
expected = y_test

plot_california_prices(expected, predicted)

#Out[]

 

 

 

 

 

### 2021.12.13

 

from 이수안컴퓨터연구소

https://www.youtube.com/watch?v=eVxGhCRN-xA

scikit-learn 특징

  • 다양한 머신러닝 알고리즘을 구현한 파이썬 라이브러리
  • 심플하고 일관성 있는 API, 유용한 온라인 문서, 풍부한 예제
  • 머신러닝을 위한 쉽고 효율적인 개발 라이브러리 제공
  • 다양한 머신러닝 관련 알고리즘과 개발을 위한 프레임워크와 API 제공
  • 많은 사람들이 사용하며 다양한 환경에서 검증된 라이브러리

모듈설명

모듈 설명
sklearn.datasets 내장된 예제 데이터 세트
sklearn.preprocessing 다양한 데이터 전처리 기능 제공 (변환, 정규화, 스케일링 등)
sklearn.feature_selection 특징(feature)를 선택할 수 있는 기능 제공
sklearn.feature_extraction 특징(feature) 추출에 사용
sklearn.decomposition 차원 축소 관련 알고리즘 지원 (PCA, NMF, Truncated SVD 등)
sklearn.model_selection 교차 검증을 위해 데이터를 학습/테스트용으로 분리, 최적 파라미터를 추출하는 API 제공 (GridSearch 등)
sklearn.metrics 분류, 회귀, 클러스터링, Pairwise에 대한 다양한 성능 측정 방법 제공 (Accuracy, Precision, Recall, ROC-AUC, RMSE 등)
sklearn.pipeline 특징 처리 등의 변환과 ML 알고리즘 학습, 예측 등을 묶어서 실행할 수 있는 유틸리티 제공
sklearn.linear_model 선형 회귀, 릿지(Ridge), 라쏘(Lasso), 로지스틱 회귀 등 회귀 관련 알고리즘과 SGD(Stochastic Gradient Descent) 알고리즘 제공
sklearn.svm 서포트 벡터 머신 알고리즘 제공
sklearn.neighbors 최근접 이웃 알고리즘 제공 (k-NN 등)
sklearn.naive_bayes 나이브 베이즈 알고리즘 제공 (가우시안 NB, 다항 분포 NB 등)
sklearn.tree 의사 결정 트리 알고리즘 제공
sklearn.ensemble 앙상블 알고리즘 제공 (Random Forest, AdaBoost, GradientBoost 등)
sklearn.cluster 비지도 클러스터링 알고리즘 제공 (k-Means, 계층형 클러스터링, DBSCAN 등)

estimator API

  • 일관성: 모든 객체는 일관된 문서를 갖춘 제한된 메서드 집합에서 비롯된 공통 인터페이스 공유
  • 검사(inspection): 모든 지정된 파라미터 값은 공개 속성으로 노출
  • 제한된 객체 계층 구조
    • 알고리즘만 파이썬 클래스에 의해 표현
    • 데이터 세트는 표준 포맷(NumPy 배열, Pandas DataFrame, Scipy 희소 행렬)으로 표현
    • 매개변수명은 표준 파이썬 문자열 사용
  • 구성: 많은 머신러닝 작업은 기본 알고리즘의 시퀀스로 나타낼 수 있으며, Scikit-Learn은 가능한 곳이라면 어디서든 이 방식을 사용
  • 합리적인 기본값: 모델이 사용자 지정 파라미터를 필요로 할 때 라이브러리가 적절한 기본값을 정의

 

API 사용 방법

  1. Scikit-Learn으로부터 적절한 estimator 클래스를 임포트해서 모델의 클래스 선택
  2. 클래스를 원하는 값으로 인스턴스화해서 모델의 하이퍼파라미터 선택
  3. 데이터를 특징 배열과 대상 벡터로 배치
  4. 모델 인스턴스의 fit() 메서드를 호출해 모델을 데이터에 적합
  5. 모델을 새 데이터에 대해서 적용
    • 지도 학습: 대체로 predict() 메서드를 사용해 알려지지 않은 데이터에 대한 레이블 예측
    • 비지도 학습: 대체로 transform()이나 predict() 메서드를 사용해 데이터의 속성을 변환하거나 추론

 

# API 예제 

import numpy as np
import matplotlib.pyplot as plt
plt.style.use(['seaborn-whitegrid']

x = 10 * np.random.rand(50)
y = 2 * x + np.random.rand(50)
plot.scatter(x,y)

#1. 적절한 extimator 클래스를 임포트해서 모델의 클래스 선택
from sklearn.linear_model import LinearRegression

#2. 클래스를 원하는 값으로 인스턴스화해서 모델의 하이퍼파라미터 선택
model = LinearRegression(fit_intercept=True)
model

# out : LinearRegreesion(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)

 

  • copy_X            X를 복사해서 사용할 것인가
  • fit_intercept    상수인가
  • n_jobs             CPU를 병렬로 사용할것인가
  • normalize        정규화가 되어있냐
# 3.데이터를 특징 배열과 대상 벡터로 배치
X = x[:, np.newaxis]

X

# out : (50,1) 인 2차원 행렬 생성

 

# 4. 모델 인스턴스의 fit() 메서드를 호출해 모델을 데이터에 적합
model.fit(X,y)

model.coef_
# out : array([1.99630302])

model.intercept_
# out : 0.4759856348626279
#5. 모델을 새 데이터에 대해서 적용
xfit = np.linspace(-1,11)
Xfit = xfit[:, np.newaxis]
yfit = model.predict(Xfit)

plt.scatter(x,y)
plt.plot(xfit,yfit, '--r')

 

# 예제 데이터 세트

분류 또는 회귀용 데이터 세트

API 설명
datasets.load_boston() 미국 보스턴의 집에 대한 특징과 가격 데이터 (회귀용)
datasets.load_breast_cancer() 위스콘신 유방암 특징들과 악성/음성 레이블 데이터 (분류용)
datasets.load_diabetes() 당뇨 데이터 (회귀용)
datasets.load_digits() 0에서 9까지 숫자 이미지 픽셀 데이터 (분류용)
datasets.load_iris() 붓꽃에 대한 특징을 가진 데이터 (분류용)

온라인 데이터 세트

  • 데이터 크기가 커서 온라인에서 데이터를 다운로드 한 후 에 불러오는 예제 데이터 세트
API 설명
fetch_california_housing() 캘리포니아 주택 가격 데이터
fetch_covtype() 회귀 분석용 토지 조사 데이터
fetch_20newsgroups() 뉴스 그룹 텍스트 데이터
fetch_olivetti_faces() 얼굴 이미지 데이터
fetch_lfw_people() 얼굴 이미지 데이터
fetch_lfw_paris() 얼굴 이미지 데이터
fetch_rcv1() 로이터 뉴스 말뭉치 데이터
fetch_mldata() ML 웹사이트에서 다운로드

분류와 클러스터링을 위한 표본 데이터 생성

API 설명
datasets.make_classifications() 분류를 위한 데이터 세트 생성. 높은 상관도, 불필요한 속성 등의
노이즈를 고려한 데이터를 무작위로 생성
datasets.make_blobs() 클러스터링을 위한 데이터 세트 생성. 군집 지정 개수에 따라
여러 가지 클러스터링을 위한 데이터 셋트를 무작위로 생성

 

# 예제 데이터 세트 구조

  • 일반적으로 딕셔너리 형태로 구성
  • data: 특징 데이터 세트
  • target: 분류용은 레이블 값, 회귀용은 숫자 결과값 데이터
  • target_names: 개별 레이블의 이름 (분류용)
  • feature_names: 특징 이름
  • DESCR: 데이터 세트에 대한 설명과 각 특징 설명
from sklearn.datasets import load_diabetes

diabetes = load_diabetes()
print(diabetes.keys())
# dict_keys(['data', 'target', 'frame', 'DESCR', 'feature_names', 'data_filename', 'target_filename', 'data_module'])

print(diabetes.data)

[[ 0.03807591  0.05068012  0.06169621 ... -0.00259226  0.01990842
  -0.01764613]
 [-0.00188202 -0.04464164 -0.05147406 ... -0.03949338 -0.06832974
  -0.09220405]
 [ 0.08529891  0.05068012  0.04445121 ... -0.00259226  0.00286377
  -0.02593034]
 ...
 [ 0.04170844  0.05068012 -0.01590626 ... -0.01107952 -0.04687948
   0.01549073]
 [-0.04547248 -0.04464164  0.03906215 ...  0.02655962  0.04452837
  -0.02593034]
 [-0.04547248 -0.04464164 -0.0730303  ... -0.03949338 -0.00421986
   0.00306441]]

print(diabetes.target)
# 442개의 값이 나옴

print(diabetes.DESCR)
# 데이터셋에 대한 설명이 나옴

print(diabetes.feature_names)
# ['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']

print(diabetes.data_filename)
# diabetes_data.csv.gz

print(diabetes.target_filename)
# diabetes_target.csv.gz

 

model_selection 모듈

  • 학습용 데이터와 테스트 데이터로 분리
  • 교차 검증 분할 및 평가
  • Estimator의 하이퍼 파라미터 튜닝을 위한 다양한 함수와 클래스 제공

train_test_split(): 학습/테스트 데이터 세트 분리

from sklearn.linear_model import LinearRegression
from sklearn.medel_selection import train_test_split
from sklearn.datasets import load_diabetes 

diabetes = load_diabetes()

X_ train, X_test, y_train, y_test = train_test_split(diabetes.data, diabetes.target, test_size = 0.3)
# feature(독립변수) 와 target(종속변수)을 넣어줌
# test_size = 0.3.  -> train data는 70% / test data는 30%

model = LinearRegression()

# 학습용 데이터를 가져와야한다.
model.fit(X_train, y_train)

print("학습 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))
학습 데이터 점수 : 0.5077991367726067
평가 데이터 점수 : 0.515546766783626

#1.0에 가까워야지 좋은 점수
# 왜 점수가 이렇게 밖에 안나왔을까?

import matplotlib.pyplot as plt

predicted = model.predict(X_test)
expected = y_test

plt.figure(figsize=(8,4))
plt.scatter(expected, predicted)
plt.plot([30,350],[30,350], '--r')
plt.tight_layout()

점들이 선에서 벗어나있는게 많아서 신뢰도가 낮음

-> 모델을 다른 것을 쓰거나, 데이터를 다른 것을 가져와야한다.

 

cross_val_score(): 교차 검증

from sklearn.model_selection import cross_val_score, cross_validate
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_diabetes 

diabetes = load_diabetes()
scores = cross_val_score(model, diabetes.data, diabetes.target, cv=5)

print("교차 검증 정확도: {}".format(scores))
print("교차 검증 정확도: {} +/- {}".format(np.mean(scores), np.std(scores)))

#교차 검증 정확도: [0.42955643 0.52259828 0.4826784  0.42650827 0.55024923]
#교차 검증 정확도: 0.48231812211149394 +/- 0.049266197765632194

 

GridSearchCV: 교차 검증과 최적 하이퍼 파라미터 찾기

  • 훈련 단계에서 학습한 파라미터에 영향을 받아서 최상의 파라미터를 찾는 일은 항상 어려운 문제
  • 다양한 모델의 훈련 과정을 자동화하고, 교차 검사를 사용해 최적 값을 제공하는 도구 필요
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import Ridge
import pandas as pd

alpha = [0.001, 0.01, 0.1, 1, 10, 100, 1000]
param_grid = dict(alpha=alpha)

gs = GridSearchCV(estimator=Ridge(), param_grid=param_grid, cv=10)
result = gs.fit(diabetes.data, diabetes.target)

print("최적 점수 : {}".format(reshlt.best_score_))
print("최적 파라미터 : {}".format(result.best_params_))
print(gs.best_estimator_)

# 최적 점수 : 0.4633240541517593
# 최적 파라미터 : {'alpha': 0.1}
# Ridge(alpha=0.1)

pd.DataFrame(result.cv_results_)

  • multiprocessing을 이용한 GridSearchCV
import multiprocessing #모델을 페럴하게 사용하기위해
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression

iris = load_iris()

param_grid = [{'penalty' : ['l1','l2'],
               'C' : [0.5, 1.0, 1.5, 1.8, 2.0, 2.4]}]

gs = GridSearchCV(estimator=LogisticRegression(), param_grid=param_grid,
					scoring='accuracy', cv=10, n_jobs=multiprocessing.cpu_count())
                    
result = gs.fit(iris.data, iris.target)

print("최적 점수 : {}".format(reshlt.best_score_))
print("최적 파라미터 : {}".format(result.best_params_))
print(gs.best_estimator_)

# 최적 점수 : 0.9800000000000001
# 최적 파라미터 : {'C': 2.4, 'penalty': 'l2'}
# LogisticRegression(C=2.4)

pd.DataFrame(result.cv_results_)

 

preprocessing 데이터 전처리 모듈

  • 데이터의 특징 스케일링(feature scaling)을 위한 방법으로 표준화(Standardization)와 정규화(Normalization) 사용
  • 표준화 방법

  • 정규화 방법

  • scikit-learn에서는 개별 벡터 크기를 맞추는 형태로 정규화

 

StandardScaler: 표준화 클래스

iris = load_iris()
iris_df = pd.DataFrame(data=iris.data, columns = iris.feature_names)
iris_df.describe()

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
iris_scaled = scaler.fit_transform(iris_df)
# fit를 통해 정규화된 정보를 가져오고 / transform을 통해 스케일된 변환을 거친다.
iris_df_scaled = pd.DataFrame(data=iris_scaled, columns=iris.feature_names)

iris_df_scaled.describe()

X_train, X_test, y_train, y_test = train_test_split(iris_df_scaled, iris.target, test_size=0.3)

model = LogisticRegression()
model.fit(X_train, y_train)

print("훈련 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

# 훈련 데이터 점수 : 0.9809523809523809
# 평가 데이터 점수 : 0.9111111111111111

 

MinMaxScaler: 정규화 클래스

from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()
iris_scaled = scaler.fit_transform(iris_df)
iris_df_scaled = pd.DataFrame(data=iris_scaled, columns=iris.feature_names)
iris_df_scaled.describe()

X_train, X_test, y_train, y_test = train_test_split(iris_df_scaled, iris.target, test_size=0.3)

model = LogisticRegression()
model.fit(X_train, y_train)

print("훈련 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

# 훈련 데이터 점수 : 0.9142857142857143
# 평가 데이터 점수 : 0.9333333333333333

 

성능 평가 지표

정확도(Accuracy)

  • 정확도는 전체 예측 데이터 건수 중 예측 결과가 동일한 데이터 건수로 계산
  • scikit-learn에서는 accuracy_score 함수를 제공
  • 정확도만 보고 이 데이터의 신뢰도를 정확히 알 수는 없다.
from sklearn.datasets import make_classification  #데이터를 만드는 모듈
from sklearn.linear_model import LogisticRegression
from sklearn.matrics import accuracy_score
  
X, y = make_classification(n_samples=1000, n_features=2, n_informative=2,
  				n_redundant=0, n_clusters_per_class=1)
#샘플은 1000개 / feature은 2개  / 의미있는 feature가 2개  /  노이즈가 0  / 클래스당 클러스터가 1개
 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
 
model = LogisticRegression()
model.fit(X_train, y_train)
 
print("훈련 데이터 점수 : {}".format(model.score(X_train, y_train)))
print("평가 데이터 점수 : {}".format(model.score(X_test, y_test)))

# 훈련 데이터 점수 : 0.9814285714285714
# 평가 데이터 점수 : 0.9766666666666667

predict = model.predict(X_test)
print("정확도 : {}".format(accuracy_score(y_test, predict)))

# 정확도 : 0.9766666666666667

 

오차 행렬(Confusion Matrix)

  • True Negative: 예측값을 Negative 값 0으로 예측했고, 실제 값도 Negative 값 0
  • False Positive: 예측값을 Positive 값 1로 예측했는데, 실제 값은 Negative 값 0
  • False Negative: 예측값을 Negative 값 0으로 예측했는데, 실제 값은 Positive 값 1
  • True Positive: 예측값을 Positive 값 1로 예측했고, 실제 값도 Positive 값 1

 

from cklearn.metrics import confusion_matrix

confmat = confusion_matrix(y_true=y_test, y_pred=predict)
print(confmat)

# [[142   7]
#  [  0 151]]

fig, ax = plt.subplots(figsize = (2.5, 2.5))
ax.matshow(confmat, cmap=plt.cm.Blues, alpha=0.3)
for i in range(confmat.shape[0]):
    for j in range(confmat.shape[1]):
        ax.text(x=j, y=i, s=confmat[i,j], va='center', ha='center')
        
plt.xlabel('predicted label')
plt.ylabel('True label')
plt.tight_layout()
plt.show()

 

정밀도(Precision)와 재현율(Recall)

  • 정밀도 = TP / (FP + TP)
  • 재현율 = TP / (FN + TP)
  • 정확도 = (TN + TP) / (TN + FP + FN + TP)
  • 오류율 = (FN + FP) / (TN + FP + FN + TP)
from sklearn.metrics import precision_score, recall_score
 
precision = precision_score(y_test, predict)
recall = recall_score(y_test, predict)
 
print("정밀도 : {}".format(precision))
print("재현율 : {}".format(recall))
 
# 정밀도 : 0.9556962025316456
# 재현율 : 1.0

 

F1 Score(F-measure)

  • 정밀도와 재현율을 결합한 지표
  • 정밀도와 재현율이 어느 한쪽으로 치우치지 않을 때 높은 값을 가짐

from sklearn.metrics import f1_score

f1 = f1_score(y_test, predict)

print("F1 Score : {}".format(f1))

# F1 Score : 0.9773462783171522

ROC 곡선과 AUC

  • ROC 곡선은 FPR(False Positive Rate)이 변할 때 TPR(True Positive Rate)이 어떻게 변하는지 나타내는 곡선
    • TPR(True Positive Rate): TP / (FN + TP), 재현율
    • TNR(True Negative Rate): TN / (FP + TN)
    • FPR(False Positive Rate): FP / (FP + TN), 1 - TNR
  • AUC(Area Under Curve) 값은 ROC 곡선 밑에 면적을 구한 값 (1이 가까울수록 좋은 값)
from sklern.metrics import roc_curve

pred_proba_class1 = model.predict_proba(X_test)[:,1]
fprs, tprs, thresholds = roc_curve(y_test, pred_proba_class1)

plt.plot(fprs, tprs, label='ROC')
plt.plot([0,1], [0,1], '--k', label='Random')
start, end = plt.xlim()
plt.xticks(np.round(np.arange(start, end, 0.1), 2))
plt.xlim(0,1)
plt.ylim(0,1)
plt.xlabel('FPR')
plt.ylabel('TPR')
plt,legend()

from sklearn.metrics import roc_auc_score

roc_auc = roc_auc_score(y_test, predict)

print("ROC AUC Score : {}".format(roc_auc))

# ROC AUC Score : 0.963309480421352

 

 

### 2021.12.20

 

 

from 이수안컴퓨터연구소 

https://www.youtube.com/watch?v=rWz582-yKuQ

 

 

머신러닝 (Machine Learning)

  • 명시적인 프로그래밍 없이 컴퓨터가 학습하는 능력을 갖추게 하는 연구 분야
  • 머신러닝은 데이터를 통해 다양한 패턴을 감지하고, 스스로 학습할 수 있는 모델 개발에 초점

 

머신러닝 분류

지도학습(Supervised Learning)

  • 지도 학습은 주어진 입력으로 부터 출력값을 예측하고자 할 때 사용
  • 입력과 정답 데이터를 사용해 모델을 학습시킨 후 새로운 입력데이터에 대해 정확한 출력예측하도록 하는 것이 목표
  • 지도 학습 알고리즘의 학습 데이터를 만드는 것은 많은 사람들의 노력과 자원이 필요하지만 높은 성능을 기대할 수 있음

분류와 회귀

  • 지도 학습 알고리즘은 크게 분류(classification)회귀(regression)로 구분
  • 분류는 입력 데이터를 미리 정의된 여러개의 클래스 중 하나로 예측하는 것
  • 분류는 클래스의 개수가 2개인 이진 분류(binary classification)와 3개 이상인 다중 분류(multi-class classification)로 나눌 수 있음
  • 회귀는 연속적인 숫자를 예측하는 것으로 어떤 사람의 나이, 농작물의 수확량, 주식 가격 등 출력 값이 연속성을 갖는 다면 회귀 문제라고 할 수 있음

지도 학습 알고리즘

  • 선형 회귀(Linear Regression)
  • 로지스틱 회귀(Logistic Regression)
  • 서포트 벡터 머신(Support Vector Machine)
  • k-최근접 이웃(k-Nearest Neighbors)
  • 결정트리(Decision Tree)
  • 앙상블(Ensemble)
  • 신경망(Neural Networks)

 

비지도 학습(Unsupervised Learning)

  • 비지도 학습은 원하는 출력 없이 입력 데이터를 사용
  • 입력 데이터의 구조나 패턴을 찾는 것이 목표
  • 미리 정해진 결과가 없고, 방대한 양의 데이터에서 유용한 통찰력을 얻을 수 있음

클러스터링, 차원축소, 연관규칙

  • 비지도 학습 알고리즘은 크게 클러스터링(Clustering), 차원 축소(Dimensionality Reduction), 연관 규칙(Association Rules)으로 구분
  • 클러스터링은 공간상에서 서로 가깝고 유사한 데이터를 클러스터로 그룹화
  • 차원 축소는 고차원의 데이터에 대해서 너무 많은 정보를 잃지 않으면서 데이터를 축소시키는 방법
  • 연관 규칙은 데이터에서 특성 간의 연관성이 있는 흥미로운 규칙을 찾는 방법

비지도 학습 알고리즘

  • 클러스터링(Clustering)
    • k-Means : k개의 클러스터를 찾는 것
    • DBSCAN : 밀집된 클러스터를 찾는 것 (밀도)
    • 계층 군집 분석(Hieracrchical Cluster Analysis)
    • 이상치 탐지(Outlier Detection), 특이값 탐지(Novelty Detection) : ex) 신용카드 이상거래(해외 거래) - 패턴을 벗어나는 값
  • 차원축소(Dimensionality Reduction)
    • 주성분 분석(Principal Component Analysis) : 주성분을 찾아내고 그것을 기반으로 차원 축소
    • 커널 PCA(Kernel PCA)
    • t-SNE(t-Distribusted Stochastic Neighbor Embedding) : 시각화에서 많이 사용
  • 연관 규칙(Association Rule Learning)
    • Apriori
    • Eclat

 

준지도 학습(Semi-supervised Learning)

  • 레이블이 있는 것과 없는 것이 혼합된 경우 사용
  • 일반적으로는 일부 데이터에만 레이블이 있음
  • 준지도 학습 알고리즘은 대부분 지도 학습 알고리즘과 비지도 학습 알고리즘의 조합으로 구성

 

강화 학습(Reinforcement Learning)

  • 동적 환경과 함께 상호 작용하는 피드백 기반 학습 방법
  • 에이전트(Agent)가 환경을 관찰하고, 행동을 실행하고, 보상(reward)또는 벌점(penality)를 받음
  • 에이전트는 이러한 피드백을 통해 자동으로 학습하고 성능을 향상시킴
  • 어떤 지도가 없이 일정한 목표를 수행

 

온라인 vs. 배치

  • 온라인 학습(Online Learning)
    • 적은 데이터를 사용해 미니배치(mini-batch)단위로 점진적으로 학습
    • 실시간 시스템이나 메모리 부족의 경우 사용
  • 배치 학습(Batch Learning)
    • 전체 데이터를 모두 사용해 오프라인에서 학습
    • 컴퓨팅 자원이 풍부한 경우 사용

 

사례 기반 vs. 모델 기반

  • 사례 기반 학습(Instance-based Learning)
    • 훈련 데이터를 학습을 통해 기억
    • 예측을 위해 데이터 사이의 유사도 측정
    • 새로운 데이터와 학습된 데이터를 비교
  • 모델 기반 학습(Model-based Learning)
    • 훈련 데이터를 사용해 모델을 훈련
    • 훈련된 모델을 사용해 새로운 데이터를 예측

 

일반화, 과대적합, 과소적합

일반화(genearalization)

  • 일반적으로 지도 학습모델은 학습데이터로 훈련시킨 뒤 평가데이터에서도 정확하게 예측하기를 기대함
  • 훈련된 모델이 처음보는 데이터에 대해 정확하게 예측한다면, 이러한 상태모델이 일반화(generalization) 되었다고 함
  • 모델이 항상 일반화 되는 것은 아님

과대적합(overfitting)

  • 주어진 훈련 데이터에 비해 복잡한 모델을 사용한다면, 모델은 훈련 데이터에서만 정확한 성능을 보이고, 평가 데이터에서는 낮은 성능을 보임
  • 즉, 모델이 주어진 훈련 데이터는 잘 예측하지만 일반적인 특징을 학습하지 못해 평가 데이터에서는 낮은 성능을 보이는 상태를 과대적합(overfitting) 이라고 함

과소적합(underfitting)

  • 과대적합과 반대로 주어진 훈련 데이터에 비해 너무 간단한 모델을 사용하면, 모델이 데이터에 존재하는 다양한 정보들을 제대로 학습하지 못함
  • 이러한 경우 모델은 훈련 데이터에서도 나쁜 성능을 보이고 평가 데이터에서도 낮은 성능을 보이는 과소적합(underfitting) 되었다고 함 

 

모델 복잡도와 데이터셋 크기의 관계

  • 데이터의 다양성이 클수록 더 복잡한 모델을 사용하면 좋은 성능을 얻을 수 있음
  • 일반적으로 더 큰 데이터셋(데이터수, 특징 수)일수록 다양성이 높기 때문에 더 복잡한 모델을 사용할 수 있음
  • 하지만, 같은 데이터를 중복하거나 비슷한 데이터를 모으는 것은 다양성 증가에 도움이 되지 ㅇ낳음
  • 데이터를 더 많이 수집하고 적절한 모델을 만들어 사용하면 지도 학습을 사용해 놀라운 결과를 얻을 수 있음

 

훈련 세트 vs 테스트 세트 vs 검증 세트

  • 머신러민 모델의 일반화 성능을 측정하기 위해 훈련 세트, 테스트 세트로 구분
  • 훈련 세트로 모델을 학습하고 테스트 세트로 모델의 일반화 성능 측정
  • 하이퍼파라미터는 알고리즘을 조절하기 위해 사전에 정희하는 파라미터
  • 테스트 세트를 이옹해 여러 모델을 평가하면 테스트 세트에 과대적합됨
  • 모델 선택을 위해 훈련 세트, 테스트 세트, 검증 세트로 구분

 

+ Recent posts