1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
import numpy as np
# 회귀 (regression)
# 학습 데이터를 이용하여 특성과 상관관계 등을 파악하고,
# 그 결과를 바탕으로 학습 데이터가 아닌 새로운 데이터가 주어졌을 때,
# 그 결과값을 연속적인 값으로 예측
# 입력(x), 출력(y) -> y = Wx +b
# W : 가중치, 기울기, b : 바이어스
# 데이터의 특성을 잘 나타낼 수 있는 가중치(W)와 바이어스(b)를 찾는 것이 목표
# 손실함수(Loss function) : 정답(t)와 예측값(p)의 차이를 모두 더해 수식으로 나타낸 것 => E(W, b)
# 손실함수의 값이 최소가 되는 가중치(W)와 바이이스(b)를 찾는 방법 => 경사하강법
## 회귀 기초 예제 ##
# 학습 데이터 => 2x-1
x_train = np.array([2, 1, 4, 3, 5, 9, 7, 10]).reshape(8, 1)
y_train = np.array([3, 1, 7, 5, 9, 17, 13, 19]).reshape(8, 1)
# 가중치와 바이어스 초기화
W = np.random.rand(1, 1)
b = np.random.rand(1)
print("W = ", W, ", b = ", b)
# 손실함수
def loss_func(input, t):
pred = np.dot(input, W) + b
return (np.sum((t-pred)**2))/len(input)
# 수치미분 정의
def numerical_derivative(func, x):
delta = 1e-4
grad = np.zeros_like(x)
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
idx = it.multi_index
temp = x[idx]
x[idx] = float(temp) + delta
f1 = func(x)
x[idx] = float(temp) - delta
f2 = func(x)
grad[idx] = (f1 - f2) / (2 * delta)
x[idx] = temp
it.iternext()
return grad
# Utility 함수
def error_eval(input, t):
pred = np.dot(input, W) + b
return (np.sum((t-pred)**2))/len(input)
def predict(input):
return np.dot(input, W) + b
# 학습하기
learning_rate = 1e-2
f = lambda x : loss_func(x_train, y_train)
for step in range(4001):
W -= learning_rate * numerical_derivative(f, W)
b -= learning_rate * numerical_derivative(f, b)
if (step%500)==0:
print("step = ", step, ", error = ", error_eval(x_train, y_train), ", W = ", W, ", b =", b)
print(predict(6)) # 11
|
cs |
위 소스코드를 실행시키면 아래와 같은 결과값이 출력된다.

반응형
'머신러닝_딥러닝 > Tensorflow + Keras' 카테고리의 다른 글
XOR 문제 (딥러닝으로 해결) (0) | 2021.10.23 |
---|---|
XOR 문제 (0) | 2021.10.23 |
로지스틱 회귀 (Logistic Regression) (0) | 2021.10.23 |
필수품 for Machine learning (0) | 2021.10.22 |
Tensorflow & Keras (0) | 2021.09.14 |