Google's AI-based personal assistant
Right data and right model
좋은 데이터와 모델은 많은 문제를 해결할 수 있으나 좋은 데이터를 찾고 좋은 모델로 학습시키는 것은 어렵다.
AI와 ML그리고 Deep Learning
AI는 General하거나 Narrow하다.
Expert System and tree search
Classification, Clustering, Regression
3가지의 학습 방법
AI Framework
Preview

기계학습의 기초
데이터셋 읽기
사이킷런(Scikit-learn) 라이브러리 설치
pip install scikit-learn 명령어로 라이브러리 설치https://sc ikit-learn.org/dev/_downloads/scikit-learn-docs.pdf에 접속하면 가장 최신 버전의 사이킷 런 사용 설명서를 무료로 다운로드할 수 있다.iris 데이터셋 읽기
from sklearn import datasets
d = datasets.load.iris() # iris 데이터셋을 읽고
print(d.DESCR) # 내용을 출력
Iris plants dataset
-------------------
**Data Set Characteristics:**
# 150개의 샘플
:Number of Instances: 150 (50 in each of three classes)
:Number of Attributes: 4 numeric, predictive attributes and the class
:Attribute Information: # 네 개의 특징(feature)
- 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!)
============= === === ===== ===== ====================
:Missing Attribute Values: None
:Class Distribution: 33.3% for each of 3 classes.
:Creator: R.A. Fisher
:Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
:Date: July, 1988
# iris의 내용 살펴보기
for i in range(0, len(d.data))): # 샘플을 순서대로 출력
print(i+1, d.data[i], d.target[i]) # index, 특징 벡터, 클래스(레이블)
1 [5.1 3.5 1.4 0.2] 0
2 [4.9 3.0 1.4 0.2] 0
3 [4.7 3.2 1.3 0.2] 0
4 [4.6 3.1 1.5 0.2] 0
...
51 [7.0 3.2 4.7 1.4] 1
52 [6.4 3.2 4.5 1.5] 1
53 [6.9 3.1 4.9 1.5] 1
54 [5.5 2.3 4.0 1.3] 1
...
101 [6.3 3.3 6.0 2.5] 2
102 [5.8 2.7 5.1 1.9] 2
103 [7.1 3.0 5.9 2.1] 2
104 [6.3 2.9 5.6 1.8] 2
기계 학습에서 데이터셋의 표현

기계 학습 적용: 모델링과 예측
기계 학습 모델 : SVM(Support vector machine)
from sklearn import svm
s = svm.SVC(gamma=0.1, C=10) # 하이퍼 매개변수
s.fit(d.data, d.target) # 훈련 집합, fit은 훈련시키는 함수
new_d = [[6.4, 3.2, 6.0, 2.5], [7.1, 3.1, 4.7, 1.35]]
res = s.predict(new_d) # 테스트 집합
print("새로운 2개 샘플의 부류는", res)
새로운 2개 샘플의 부류는 [2, 1]
훈련 집합(Training Set)과 테스트 집합(Test Set)
인공지능 제품의 설계와 구현
인공지능 제품의 핵심
실용적인 시스템 사례
인공지능 설계 사례: 과일 등급을 분류하는 기계
from sklearn import svm
s = svm.SVC(gamma=0.1, C=10)
s.fit(apple.data, apple.target) # apple 데이터로 모델링s.predict(x) # 새로운 사과에서 추출한 특징 벡터 x를 예측규칙 기반 vs 고전적 기계 학습 vs 딥러닝
머신러닝이란 무엇인가?
T를 위해 경험을 통해 학습하고E T를 통해 성능 평가를 하는 것 P 또한 주어진 T를 통해 더욱 향상시키는 것 (Tom Mitchell, 1997)Classes of Learning Problem
x = data, y = labelX → Y
x = data, no label

특징 공간에서 데이터 분포
특징이 4개이므로 4차원 특징 공간을 형성
150개 샘플 각각은 4차원 특징 공간의 한 점
차원을 하나 제외하고 3차원 공간에 데이터 분포를 그림
# iris 데이터의 분포를 특징 공간에 그리기
import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width' color='species')
fig.show(rendere="browser")

영상 데이터 사례: 필기 숫자
두 가지 필기 숫자 데이터셋
sklearn 데이터셋: 8*8맵(64개 화소), 1797개 샘플, [0, 16]명암값
MNIST 데이터셋: 28*28맵(784개 화소), 7먄개 샘플, [0, 255]명암값

from sklearn import datasets
import matplotlib.pyplot as plt
digit.datasets.load_digits()
plt.figure(figsize=(5,5))
plt.imshow(digit.images[0], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
print(digit.data[0])
print("이 숫자는 ", digit.target[0], "입니다.")

텍스트 데이터 사례: 20newsgroups
20newsgroups 데이터셋
news = datasets.fetch.20newsgroups(subset="train") # 데이터셋 열기
print("-----\n', news.data[0], "\n-----")
print("이 문서의 부류는 <", news.target.names[news[news.target[0]], "> 입니다.")
*****
From: lerxst@wam.umd.edu (where's my thing)
Subject: WHAT car is this!?
Nntp-Posting-Host: rac3.wam.umd.edu
Organization: University of Maryland, College Park
Lines: 15
I was wondering if anyone out there could enlighten me on this car I saw
the other day. It was a 2-door sports car, looked to be from the late 60s/
early 70s. It was called a Bricklin. The doors were really small. In addition,
the front bumper was separate from the rest of the body. This is
---
*****
이 문서의 부류는 < rec.autos >입니다.
특징 추출과 표현
데이터 수집 → 특징 추출 → 모델링 → 예측특징의 분별력

특징 값의 종류
필기 숫자 인식
필기 숫자 인식
x = (0,0,5,13,9,1,0,0,0,0,13,15,10,15... 64개의 특징 벡터)화소 값을 특징으로 사용
from sklearn import datasets
from sklearn import svm
digit=datasets.load_digits()
# svm의 분류기 모델 SC를 학습
s=svm.SVC(gamma=0.1, C=10)
s.fit(digit.data, digit.target) # digit 데이터로 모델링
# 훈련 집합의 앞에 있는 샘플 3개를 새로운 샘플로 간주하고 인색해봄
new_d = [digit.data[0], digit.data[1], digit.data[2]]
res = s,predict(new_d)
print("예측값은", res)
print("참값은", digit.target[0], digit.target[1], digit.target[2])
# 훈련 집합을 테스트 집합으로 간주하여 인식해보고 정확률을 측정
res = s.predict(digit.data)
correct=[i for i in range(len(res)) if res[i]==digit.targe[i]]
accuracy=len(correct)/len(res)
print("화소 특징을 사용했을 때 정확률=", accuracy*100, "%")
예측값은 [0 1 2]
참값은 0 1 2
화소 특징을 사용했을 때 정확률=100.0%
성능 측정
혼동 행렬과 성능 측정 기준

훈련/검증/테스트 집합으로 쪼개기
주어진 데이터를 적절한 비율로 훈련, 검증, 테스트 집합으로 나누어 씀

from sklearn import datasets
from sklearn import svm
from sklearn.model_selection import train_test_split
# 데이터셋을 읽고 훈련 집합과 테스트 집합으로 분할
digit = datasets.load_digits()
x_train, x_test, y_train, y_test = train_split(digit.data, digit.target, train_size=0.6)
# svm의 분류 모델 SVC를 학습
s = svm.SVC(gamma=0.001)
s.fit(x_train, y_train)
res = s.predict(x_test)
# 혼동 행렬 구함
conf=np.zeros((10,10))
for i in range(len(res)):
conf[res[i]][y_test[i]] += 1
print(conf)
# 정확률 측정하고 출력
no_correct = 0
for i in range(10):
no_correct += conf[i][i]
accuracy=no_correct/len(res)
print("테스트 집합에 대한 정확률은", accruracy*100, "%입니다.")
난수를 사용하기 때문에 실행할 때마다 다른 결과가 나오는 프로그램
교차 검증
훈련/테스트 집합 나누기의 한계
k-겹 교차 검증

digit 데이터에 교차 검증 적용
from sklearn import datasets
from sklearn import svm
from sklearn.model_selection import cross_val_score
import numpy as np
digit=datasets.load_digits()
s=svm.SVC(gamma=0.001)
accuracies=cross_val_score(s, digit.data, digit.target, cv=5) # 5-겹 교차 검증
print(accuracies)
print("정확률(평균)=%0.3f, 표준편차=%0.3f"%(accuracies.mean()*100, accuracies.std()))
[0.97527473 0.95027624 0.98328691 0.99159664 0.95774648]
정확률(평균)=97.164, 표준편차=0.015
인공지능은 어떻게 인식을 하나?
특징 공간을 분할하는 결정 경계
인공지능의 인식은 철저히 수학에 의존

특징 공간을 분할하는 결정 경계(decision boundary)

현대 기계 학습이 다루는 데이터
결정 경계를 정하는 문제에서 고려 사항

SVM의 원리

polynomial function, radial basis function, sigmoid 함수를 사용s=svm.SVC(gamma=0.1, C=10)