1주차 품질과 신뢰성

- 유형

1. 요구 품질  2. 설계 품질  3. 제조 품질  4. 사용 품질

- 종합적 품질 : 고객 지향적인 품질 고려 필요

- 저품질 비용 : 기업 내에서 불필요하게 발생하는 이익손실비용을 측정하는 재무적 척도

- 예방 비용 : 처음부터 불량이 발생하지 않도록 하는데 소요되는 비용

- 평가 비용 : 소정의 품질 수준을 유지하는데 드는 비용

- 실패 비용 : 소정의 품질을 유지하는데 실패하여 드는 비용

- SPC(Statistical Process Control) : 공정에서 요구되는 품질이나 생산성 목표를 달성하기 위해 통계적 방법으로 공정을 효율적으로 운영해 나가는 관리방법

- 품질 변동을 고려해야 한다! 품질변동에는 우연원인과 이상원인이 존재

- QC7 Tool

- 품질은 현시점의 제품의 특성을 일컫는 반면 신뢰성은 미래의 성능과 고장을 일컫음

 

2주차 지도학습

Supervised Learning(지도학습) : 회귀와 분류. 에러, 편향, 분산

Cross-Validation

Linear Regression

Optimization

Gradient Descent

SGD : Stochastic Gradient Descent - 단 하나의 데이터를 이용하여 경사하강법 1회 진행(배치 크기가 1). 전체 데이터 중 랜덤하게 선택된 하나의 데이터로 학습. but 학습속도가 느리고 global minimum에 도달하기가 어려움

Batch gradient Descent : 전체 데이터를 하나의 배치로(배치 크기가 n)으로 묶어 학습 시키는 경사하강법

Mini-Batch Stochastic Gradient Descent - 전체 데이터를 batch size개씩 나눠 배치로 학습

Limitation : Local Optimum

Momentum : Desgined to speed up learning in high curvature and smalll/noise gradients. Exponentially weighted moving average of past gradients

모멘텀 알고리즘 공식
네스테로프 모멘텀 공식

AdaGrad : Adapts individual learning rate of each direction

RMSProp : attempts to fix the drawbacks of AdaGrad. Gradient accumulation by weighted decaying

Adam : RMSProp + momentum

 

Linear Classification : predict a discrete output y from x

ex) image recognition

Score and Margin

Zero-one loss. Hinge loss. Cross entropy loss. Sigmoid function. 

 

Advanced classification Model

Support vector Machine : Support vector란 minimum margin을 가지는 인스턴스를 일컫음. 양 사이드를 고려할 때 가장 큰 margin을 얻는 linear separator 선택.

Optimization : Optimal weight w and bias b

 

Artificial Neural Network : Non-linear classification model.

 

Ensemble Learning : Predict class label for unseen data by aggregating a set of predictions

 

ROC Curve : TPR 과 TNR을 이용하여 그룹 비교 성능 평가

 

Bagging and Boosting : Build different experts and let them vote.

Bagging : Bootstrapping + aggregating

Boosting : 오차에 집중하여 반복학습을 통해 성능 증가

 

 

3주차 딥러닝

퍼셉트론 : 뉴럴네트워크의 한 종류. Linear classifier

Forward Propagation : 입력 데이터를 기반으로 input layer에서 output layer까지 변수들을 차례로 계산하고 추론한 결과. 각 계층마다 가중치와 편향으로 계산된 값이 활성화 함수에 전달됨. 최종 활성화함수에서 출력값이 계산되고 손실함수에 실제값과 함께 연산하여 오차를 계산함. 이를 이용해 모델을 학습하는 과정을 Back Propagation이라 함.

 

다양한 활성화함수 : Sigmoid activation,Tanh Activation, ReLU Activation 등

Batch Normalization : 층으로 들어가는 입력값이 한쪽으로 쏠리게 하지 않게 하는 기법. 여러 입력값을 모은 배치에 대해 각 층의 입력값의 평균과 표준편차를 다시 맞추어 줌.

 

CNN

- 하이퍼파라미터 : 필터 개수, 필터 사이즈, 풀링 사이즈, 풀링 스트라이드, 레이어 개수, 뉴런 개수

- Advanced CNN Architectures : Alexnet, VGGNet, GoogLeNet, ResNet

 

Seq2Seq with Attention

RNN(Recurrent Neural Network)

Vanilla neural networks : one-to-one

Image Captioning : one-to-many

Sentiment Classifcation : many-to-one

Machine Translation, Video Classification on Frame Level : many-to-many

'ML' 카테고리의 다른 글

범주형 변수를 다루는 방법  (0) 2023.02.10
LG Aimers 진행중,,  (0) 2023.02.08
K-최근접 이웃 알고리즘  (0) 2022.09.26
경사하강법  (2) 2022.09.23
선형 회귀(Linear Regression)  (0) 2022.09.22

먼저 jupyter notebook으로 구현하기 위하여 가상환경을 구축해보았다.

 

이전에 pytorch와 cuda, cudnn을 미리 설치해놨어서 큰 걱정을 안했다

 

객체 인식을 위하여 opencv를 다운받고 기타 필요 라이브러리들 역시 성공적으로 다운받았다.

 

하지만, 추후에 혹시 사용될지도 모를 cuda를 이용하여 gpu를 붙이는 과정에서 지속적으로 오류가 났다.

 

torch.cuda.is_available()에서 어찌된 이유인지 계속하여 false가 나왔고

 

이를 해결하고자 구글링을 열심히 한 결과 그 정답은

 

가상환경 내 python, cuda, cudnn, pytorch의 버전이 서로 호환하지 않아서였다.

 

cuda, pytorch, cudnn을 삭제 후 재설치하였으나 여전히 정상적으로 구동하지 않아 python의 버전을 봤더니

 

base의 python버전과 달리 가상환경 내 python의 버전은 어찌된 이유인지 3.7 이었던게 문제였다..

 

이를 뒤늦게 발견하고 python 버전을 맞추어 다시 프로그램을 구동하니

 

cuda에 gpu가 정상적으로 붙는 모습이다..!

 

약 3시간의 삽질 동안 느낀 것은...

 

 

버전의 호환은 엄청나게 중요하다..!

'ComputerVision' 카테고리의 다른 글

Object Detection의 이해  (0) 2023.02.01
축구 match analyzer 구현하기  (0) 2022.11.17

축구 영상을 분석하는 알고리즘을 구현해보려 한다.

 

아래 링크를 참고하지만 필요한 코드들은 모두 직접 구상해서 구현해보려 한다.

 

https://candyz.tistory.com/4

 

Match Analyzer(based on OD & Opencv)

안녕하세요 Candy Lee입니다. 이번 게시글은 2020년 3월부터 2020년 10월달 까지 약 7달에 걸쳐 만들어본 축구 영상 분석 프로젝트 입니다. 깃허브 주소 : github.com/gang3039/Custom-TF-OD-Opencv-soccer-analysis 1.

candyz.tistory.com

 

큰 틀은 경기 영상을 Input값으로 넣었을 때, 선수들을 인식하고, 각 선수들의 팀을 구분하며, 해당 경기의 포메이션과 선수 간의 거리, 그리고 축구 공을 인식하는 것 까지 구현해보려 한다.

 

'ComputerVision' 카테고리의 다른 글

Object Detection의 이해  (0) 2023.02.01
jupyter notebook 가상환경 구축(엄청 애먹음..)  (0) 2022.11.17
  1. 말뭉치 내의 모든 구두점 삭제한 후 TF descriptor 구현하기

- TF descriptor : 문장 내 단어의 빈도를 설명해주는 값

import re, string

punc_regex = re.compile('[{}]'.format(re.escape(string.punctuation)))

def strip_punc(corpus):
	return punc_regex.sub('',corpus)

from collections import Counter
import numpy as np
doc = "Apples rule. Apples are the best. Truly, they are. Truly... Truly"

doc = strip_punc(doc) # 구두점 제거
counter = Counter(doc.lower().split()) # 소문자로 변환해주고 공백 단위로 나눠서 Counter에 넣어줌
descriptor = np.array([counter[word] for word in sorted(counter)], dtype=float) 
print(counter)
print(sorted(counter.keys())) # key 값을 알파벳 순으로 정렬해서 보여줌
print(descriptor)

- to_counter 함수 구현

def to_counter(doc):
	return Counter(strip_punc(doc).lower().split())

- to_vocab 함수 구현

def to_vocab(counters):
	vocab = set()
    for counter in counters:
    	vocab.update(counter.keys())
    return sorted(vocab)

- to_tf 함수 구현

import numpy as np
def to_tf(counter, vocab):
	lst=[]
    for word in vocab:
    	lst.append(counter[word])
    return np.array(lst, dtype= float)

- to_vocab 함수를 상위 n개의 단어만을 출력하고 불용어를 걸러 vocab을 형성해주도록 보완

def to_vocoab(counters, k=None, stop_words =tuple()):
	vocab = Counter()
    for counter in counters:
    	vocab.update(counter)
    for word in set(stop_words):
    	vocab.pop(word, None)
    return sorted(a for a, b in vocab.most_common()[:k]

- to_tf를 frequency로 변환하도록 업데이트

def to_tf(counter, vocab):
	lst=[]
    for word in voccab:
    	lst.append(counter[word])
    ret = np.array(lst, dtype=float)
    return ret/sum(ret)

- IDF 구현하기

def to_idf(vocab, counters):
	N = len(counters)
    lst=[]
    for t in vocab:
    	cnt = 0
        for counter in counters:
        	if (t in counter): cnt+=1
        lst.append(cnt)
     df = np.array(lst, dtype=float)
     return np.log10(N / df)

- TF-IDF 계산하기

doc_1 = "Apple cider is delicious."
doc_2 = "A recipe for apple cider, using apple."
doc_3 = "Donuts are delicious"
doc_4 = "Apple cider donuts, anyone? Donuts?"

# 여기에 코드 작성
word_counts = [to_counter(doc) for doc in [doc_1, doc_2, doc_3, doc_4]] # 각 문서에 대한 counter을 모은 list
vocab = to_vocab(word_counts, stop_words=stops) # 불용어를 제외한 모든 문서에서 단어들의 집합
tfs = np.vstack([to_tf(counter, vocab) for counter in word_counts]) # TF 행렬
idf = to_idf(vocab, word_counts) # IDF 행렬
tf_idfs = tfs * idf # 브로드캐스팅

print(tfs)
print(idf)
print(tf_idfs)
  • [글자-빈도] 형태로 변환하는 함수 만들기
def normalize(counter):
    total = sum(counter.values())
    return [(char, cnt/total) for char, cnt in counter.most_common()]
  • N-Gram 분석 모델 구현
from collections import defaultdict, Counter

def train_lm(text, n):
    raw_lm = defaultdict(Counter)
    history = '~'*(n-1)
    for char in text:
        raw_lm[history][char] += 1
        history = history[1:] + char
    lm = {history : normalize(counter) for history, counter in raw_lm.items()}
    return lm
  • N-Gram 모델을 통해 예측 텍스트 생성하기
import numpy as np

def generate_letter(lm, history):
    if not history in lm:
        return '~'
    letters, probs = unzip(lm[history])
    i = np.random.choice(letters, p = probs)
    return i
    
def generate_text(lm, n, nletters=100):
    history='~'*(n-1)
    text=[]
    for i in range(nletters):
        c = generate_letter(lm, history)
        text.append(c)
        history = history[1:]+c
    return ''.join(text)
  • 말뭉치(corpus) : 언어 연구를 위해 텍스트를 컴퓨터가 읽을 수 있는 형태로 모아 놓은 언어 자료
  • 토큰화(tokenization) : 말뭉치를 분석하기 위해 작은 단위, 즉 토큰(token)으로 쪼개는 과정
  • 불용어(stop words) : 문법적 기능만을 수행하며 실질적인 의미를 전달해주지 못하는 단어
  • 인코딩(encoding) : 텍스트 문서를 숫자로 표현하여 컴퓨터가 읽을 수 있도록 변환하는 과정
  • n-gram 언어 모델 : (n-1)개의 글자(or 단어)의 연속된 시퀀스를 통해 다음에 올 글자의 확률을 도출하고 예측하는 모델
  • 단어 가방 모형(Bag of Words, BoW) : 텍스트로 이루어진 문서에서 각 단어가 '몇 번씩' 등장하는지 수치화하여 벡터로 표현해주는 모델. TF(Term-Frequency) : 단어 빈도, IDF(Inverse term-frequency) : 역문서빈도
#라이브러리 import
import time
import numpy as np
%matplotlib notebook
import matplotlib.pyplot as plt

#여러 아이템 모음을 별개의 튜플로 풀어주는 함수
def unzip(pairs):
	return tuple(zip(*pairs))
    
#데이터 불러오기
path_to_wikipedia = 'wikipedia2text-extracted.txt'
with open(path_to_wikipedia, 'rb') as f:
	wikipedia = f.read().decode()
    wikipedia = wikipedia.lower()
print(str(len(wikipedia)) + 'character(s)')

#원소별 개수를 딕셔너리 형태로 저장해주는 Counter 클래스
from collections import Counter
counter = Counter(wikipedia)
print(counter)

import string
letters = set(string.ascii_lowercase)
counts=[]
for char, cnt in counter.most_common():
	if char in letters:
    	counts.append((char,cnt))
print(counts)

total = 0
for _, cnt in counts:
	total += cnt
freqs = []
for char, cnt in counts:
	freqs.append((char, cnt/total))
print(freqs)

#letter frequency 히스토그램 그리기
fig, ax = plt.subplots()
labels, values = unzip(freqs)
ax.bar(range(26), values, align = 'center', alpha=0.5)
ax.set_xticks(range(len(labels))
ax.set_xticklabels(labels)

ax.set_ylabel('Frequency')
ax.set_title('Frequency of Letters in English')

#간단한 토큰화
tokens = wikipedia.split()
print(len(tokens))
print(tokens[:10])

#텍스트의 단어 수 세기
word_counter = Counter(tokens)
print(len(word_counter))
word_counter.most_common()[:20]

데이터에 대한 답을 구할 때 최근접에 있는 데이터를 보고 다수를 차지하는 것을 정답으로 사용함

  • 데이터 준비하기
  • 도미의 길이와 무게 데이터(특성, feature)
bream_length = [25.4, 26.3, 26.5, 29.0, 29.0, 29.7, 29.7, 30.0, 30.0, 30.7, 31.0, 31.0, 
                31.5, 32.0, 32.0, 32.0, 33.0, 33.0, 33.5, 33.5, 34.0, 34.0, 34.5, 35.0, 
                35.0, 35.0, 35.0, 36.0, 36.0, 37.0, 38.5, 38.5, 39.5, 41.0, 41.0]
bream_weight = [242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 500.0, 390.0, 450.0, 500.0, 475.0, 500.0, 
                500.0, 340.0, 600.0, 600.0, 700.0, 700.0, 610.0, 650.0, 575.0, 685.0, 620.0, 680.0, 
                700.0, 725.0, 720.0, 714.0, 850.0, 1000.0, 920.0, 955.0, 925.0, 975.0, 950.0]
  • 빙어의 길이와 무게 데이터(특성, feature)
smelt_length = [9.8, 10.5, 10.6, 11.0, 11.2, 11.3, 11.8, 11.8, 12.0, 12.2, 12.4, 13.0, 14.3, 15.0]
smelt_weight = [6.7, 7.5, 7.0, 9.7, 9.8, 8.7, 10.0, 9.9, 9.8, 12.2, 13.4, 12.2, 19.7, 19.9]
  • 산점도 그리기
plt.scatter(bream_length, bream_weight)
plt.scatter(smelt_length, smelt_weight)
plt.xlabel('length')
plt.ylabel('weight')
plt.show()
  • 데이터 전처리
length = bream_length + smelt_length
weight = bream_weight + smelt_weight

fish_data = [[l,w] for l, w in zip(length, weight)
  • 타겟 데이터 생성
fish_target = [1]*35 + [0]*14
print(fish_target)
  • K-최근접 이웃 알고리즘 구현
from sklearn.neighbors import KNeighborsClassifier
kn = KNeighborsClassifier()
kn.fit(fish_data, fish_target)
kn.score(fish_data, fish_target)
kn.predict([[30,600]])
#fish_data와 fish_target 불러오기
print(kn._fit_X)
print(kn._y)
#n_neighbors 조정
kn49 = KNeighborsClassifier(n_neighbors=49)
kn49.fit(fish_data, fish_target)
kn49.score(fish_data, fish_target)

'ML' 카테고리의 다른 글

LG Aimers 진행중,,  (0) 2023.02.08
LG Aimers 강의 정리  (0) 2023.02.01
경사하강법  (2) 2022.09.23
선형 회귀(Linear Regression)  (0) 2022.09.22
주성분분석(PCA)  (0) 2022.09.21

경사하강법 : 함수의 극솟값을 찾는 하나의 알고리즘. 함수의 그래프 위 한 점에서 여러 변수 중 어떤 변수를 늘이고 줄여야 함숫값이 가장 많이 감소하는지 확인하고 그에 따라 변수들의 값을 늘이고 줄이는 과정.

하이퍼 파라미터 : 모델을 학습시키는 과정에 영향을 주는 파라미터. 직접 결정해야하는 값

경사하강법의 파라미터

  • Wold의 초기값 : 보통 정규분포 등으로 부터 무작위 추출(Random)
  • 학습률 : 학습률이 너무 크면 목표지점 지나칠 수 있음. 너무 작으면 변화량이 너무 작아 목표지점까지 도달하기 힘들 수 있음
  • 알고리즘의 종료조건

파이썬으로 구현해보기

# 경사하강법을 이용하여 선형 회귀모델 학습
1. 필요한 라이브러리 import, 데이터 가져오기
``` python
!pip install xarray
from pathlib import Path
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
%matplotlib notebook
import numpy as np
import xarray as xr
import mygrad as mg

# 데이터 불러오기
draft_data = xr.load_dataset(Path.cwd() / 'nba_draft_measurements.nc')

fig, ax = plt.subplots()
x = draft_data.height_no_shoes.data
y = draft_data.wingspan.data
ax.scatter(x,y)
ax.grid()
```
2. 선형회귀
``` python
#최소 제곱법을 통해 최적의 기울기와 y절편값 구함
def ordinary_least_squares(x,y):
    N = x.size
    m = (np.matmul(x,y)-x.sum()*y.sum()/N)/(np.matmul(x,x)-(1/N)*x.sum()**2)
    b = y.mean()-m*x.mean()
    return m,b
```
3. 여러 m,b 값에 대한 손실함수(MeanSquaredError) 그래프 시각화하기
``` python
def graph_linear_regression_mse(
    x,
    y,
    trajectory=None,
    m_scale = 10,
    b_scale = 10,
    sample_density=500,
):
    def(x,y,m,b):
        m = np.atleast_1d(m)
        b = np.atleast_1d(b)
        return ((x*m[None]+b[None]-y)**2).mean(axis=1)

    A = np.vstack([x, np.ones(len(x))]).T
    m_opt, b_opt = np.linalg.lstsq(A, y, rcond=None)[0] #최소 제곱 해 구해주는 함수
    I_opt = mse(x,y,m_opt, b_opt)

    center_m = m_opt
    center_b = b_opt

    #MSE 그래프의 figure 생셩
    fig = plt.figure()
    ax = fig.gca(projection='3d')

    #MSE 그래프의 최소점을 그래프 위에 검은 점으로 표시
    ax.plot(
        [m_opt],
        [b_opt],
        I_opt,
        c='black',
        marker='o',
        zorder=3,
        markersize=7,
    )

    #그래프를 그리는데 사용할 m,b 값들을 추출하여 numpy 배열의 형태로 생성, 이들 값에 대응되는 MSE 값들 계산
    m_series = np.linspace(center_m- m_scale, center_m + m_scale, sample_density)
    b_series = np.linspace(
        center_b-b_scale, center_b+b_scale, sample_density
    ).reshape(-1,1)

    Z = (b_series+x.reshape(-1,1,1) * m_series) - y.reshape(-1,1,1)
    Z = np.mean(z**2, axis=0)

    #그래프 그리기
    m_series, b_series = np.meshgrid(m_series, b_series)
    ax.set_xlabel('slobe:m')
    ax.set_ylabel('Intercept:b')
    ax.set_zlabel('MSE LOSS')
    ax.ticklabel_format(style='sci', scilimits=(-1,2))
    ax.dist = 11
    surf = ax.plot_surface(m_series, b_series, Z, cmap = plt.get_cmap('GnBu'))

    #지정한 trajectory를 그래프 위에 나타내기
    if trajectory is not None:
        trajectories = np.atleast_2d(trajectory)
        if trajectories.ndim == 2:
            trajectories = trajectories[np.newaxis]
        for trajectory in trajectories:
            m_values, b_values = trajectory.T
            I_values = ((x*m_values[:,None]+ b_values[:,None]-y)**2).mean(axis=1)
            ax.plot(m_values, b_values, I_values, marker='*', zorder=3, markersize=7,)
    return fig, ax
```
4. 선형 회귀 모델을 경사하강법으로 학습시키기 위한 기초 함수 만들기
``` python
def gradient_step(tensors, learning_rate): #경사하강법 구현 함수
    if isinstance(tensors, mg.Tensor):
        tensors = [tensors]
    for tensor in tensors:
        if tensor.grad is not None:
            tensor.data -= learning_rate*tensor.grad

import mygrad as mg
def mean_squared_error_mygrad(y_pred, y_true):
    #MSE 계산 함수
    return mg.mean((y_pred - y_true)**2)

true_params = np.array(ordinary_least_squares(height, wingspan))
def dist_from_true(model_params, true_params)-> float:#->은 주석
    params = np.array([i.item() for i in model_params])
    return np.sqrt(np.sum((true_params-params)**2))
```
5. 선형 모델 클래스 만들기
``` python
from mygrad.nnet.initializers import uniform 
#모델 파라미터의 초기화(균등분포로부터 랜덤 추출)를 위한 uniform 함수 import
class LinearModel:
    def initialize_params(self):
        self.m = uniform(1, lower_bound=-10, upper_bound = 10)
        self.b = uniform(1, lower_bound=-10, upper_bound = 10)
    def __init__(self, m=None, b=None):
        self.initialize_params()
        if m is not None:
            self.m = m
        if b is not None:
            self.b = b
    def __call__(self, x):
        y = self.m*x+self.b
        return y
    
    @property
    def parameters(self):
        t = (self.m, self.b)
        return t

#클래스 생성
model = LinearModel()
```
6. 경사하강법을 통해 모델 학습시키기

``` python
heights = draft_data.height_no_shoes.data
wingspans = draft_data.wingspan.data

model = LinearModel()

trajectory = [] #모델 파라미터를 저장할 배열
num_epochs = 10
learning_rate = 1E-4

from noggin import create_plot  # create_plot 함수를 import
plotter, fig, ax = create_plot(["loss", "m", "b", "dist_from_target"], ncols=2)

for n in range(num_epochs):
    y_pred = model(heights)
    loss = mean_squared_error_mygrad(y_pred, wingspans)
    loss.backward()
    plotter.set_train_batch(dict(loss=loss, m=model.m.item(), b=model.b.item(), dist_from_target = dist_from_true(model.parameters, true_params),), batch_size = len(y_pred),) #nogging 라이브러리를 활용하여 그래프를 실시간으로 채움

    trajectory.append((model.m.item(), model.b.item()))

    gradient_step(model.parameters, learning_rate)
plotter.plot()

graph_linear_regression_mse(height, wingspan, trajectory=trajectory)

# 데이터의 산점도, 이상적인 선형 회귀 모델, 직접 구한 선형 회귀 모델 시각화
fig, ax = plt.subplots()

ax.scatter(height, wingspan)
m, b =  ordinary_least_squares(height, wingspan)
x = np.linspace(height.min(), height.max(), 1000)

ax.plot(x, model.m * x + model.b, c="orange", label="Learned Fit")
ax.plot(x, m * x + b, c="red", ls= "--", label="Ideal Fit")
ax.legend()
ax.grid(True)
ax.set_xlabel("Height [inches]")
ax.set_ylabel("Wingspan [inches]")
```
- 선형회귀를 그래프로 그렸지만 b값이 맞지 않음
- 초기값에 따라 학습된 모델의 결과가 달라지기 때문
7. 데이터 전처리(표준화)
- 이전에 학습이 원활히 되지 않은 것은 b보다 m(기울기)이 더욱 민감하게 변화하기 때문
``` python
def norm(x):
    normed_x = (x-x.mean())/x.std()
    return normed_x
``` 
``` python
normed_height = norm(height)
normed_wingspan = norm(wingspan)
fig, ax = plt.subplots()
ax.scatter(normed_height, normed_wingspan)
ax.grid()
```

``` python
# 여기에 코드 작성
plotter, fig, ax = create_plot(['loss','m','b','dist_from_target'], ncols=2, last_n_batches=50)

# trajectory 리스트 초기화
trajectory=[]

# class instance 선언
model = LinearModel()


# epochs, learning rate 적절히 설정 
# epochs 최대 50회 설정 가능, 50회 넘어갈 시 Step 8 점수 0점
# learning rate 값을 변화시켜 가며, dist_from_taret 함수의 값을 감소시킬 것
num_epochs=40
learning_rate = 0.1



# ordinary_least_squares 함수 이용해  normalized height, normalized wingspan 에 대해 
# m*, b* 값 계산 후 true_params_normed 에 저장
true_params_normed = np.array(ordinary_least_squares(normed_height, normed_wingspan))


for n in range(num_epochs):
                              
    # normalized height 데이터를 이용해 모델의 예측값 계산
    y_pred = model(normed_height)
    
    # 오차함수 계산
    loss = mean_squared_error_mygrad(y_pred, normed_wingspan)
    
    # 오차함수 역전파
    loss.backward()

    # noggin 그래프 그리기 
    plotter.set_train_batch(
        dict(
            loss = loss,
            m = model.m.item(),
            b = model.b.item(),
            dist_from_target = dist_from_true(model.parameters, true_params_normed),
        ),
        batch_size=len(height),
    )
    
    # (m, b)의 값을 trajectory list 에 append
    trajectory.append((model.m.item(), model.b.item()))
        
    # 경사하강법 1 step 진행
    gradient_step(model.parameters, learning_rate)
    

plotter.plot()

'''
Displaying Errors (No blank). 
아래에는 빈칸 없습니다. 그대로 실행하시면 됩니다.
'''
train_metrics = plotter.to_xarray("train").batch
train_metrics.dist_from_target[-1]
graph_linear_regression_mse(normed_height, normed_wingspan, trajectory=trajectory)

fig, ax = plt.subplots()

ax.scatter(normed_height, normed_wingspan)
m, b =  ordinary_least_squares(normed_height, normed_wingspan)

x = np.linspace(normed_height.min(), normed_height.max(), 1000)

ax.plot(x, model.m * x + model.b, c="orange", label="Learned Fit", lw="4")
ax.plot(x, m * x + b, c="red", ls= "--", label="Ideal Fit")
ax.legend()
ax.grid(True)
ax.set_xlabel("Normed Height")
ax.set_ylabel("Normed Wingspan");
num_models = 10
trajectories = [[] for i in range(num_models)]
models = [LinearModel() for i in range(num_models)]

num_epochs = 100
step_size = 1E-1

for n in range(num_epochs):
    for model_id, model in enumerate(models):
        y_pred = model(normed_height)
        loss = mean_squared_error_mygrad(y_pred, normed_wingspan)
        loss.backward()

        trajectories[model_id].append((model.m.item(), model.b.item()))
        gradient_step(model.parameters, learning_rate=learning_rate)

trajectories = np.array(trajectories)

fig, ax = graph_linear_regression_mse(normed_height, normed_wingspan, trajectory=trajectories)
```
9. 표준화한 데이터를 통해 얻은 모델을 원래 모델에 맞게 조정하기
``` python
def processed_predictions(model, x, height_mean = height.mean(), height_std = height.std(), wingspan_mean = wingspan.mean(), wingspan_std = wingspan.std(),):
    new_x = (x-height_mean)/height_std
    return mg.asarray(model(new_x))*wingspan_std + wingspan_mean
fig, ax = plt.subplots()
ax.scatter(height, wingspan)

x = np.linspace(height.min(), height.max(), 1000)
# 모델을 통해 최종적으로 얻는 y 계산
# 여기에 코드 작성
y = processed_predictions(model,x)


ax.plot(x, y, color="orange", lw=4, label="Learned Model")
m, b = ordinary_least_squares(height, wingspan,)
ax.plot(x, m * x + b, c="red", label="Ideal Fit")
ax.grid(True)
ax.legend()
ax.set_xlabel("Height [inches]")
ax.set_ylabel("Wingspan [inches]")
```

'ML' 카테고리의 다른 글

LG Aimers 진행중,,  (0) 2023.02.08
LG Aimers 강의 정리  (0) 2023.02.01
K-최근접 이웃 알고리즘  (0) 2022.09.26
선형 회귀(Linear Regression)  (0) 2022.09.22
주성분분석(PCA)  (0) 2022.09.21

+ Recent posts