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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
 
import numpy as np
 
 
# 머신러닝 XOR 문제
# 단순히 로지스틱 회귀 만으로는 해결할 수 없음
# AND, OR, NAND gate 등을 조합한 다층 구조로 해결할 수 있음
# 딥러닝의 핵심 아이디어
 
 
## XOR 문제 ##
 
def sigmoid(x):
    return 1/(1+np.exp(-x))
 
 
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
 
 
class LogicGate:
 
    def __init__(self, x_data, t_data):
        self.__x_data = x_data.reshape(42)
        self.__t_data = t_data.reshape(41)
 
        self.__W = np.random.rand(21)
        self.__b = np.random.rand(1)
 
        self.__learning_rate = 1e-2
 
    def __loss_func(self):
        delta = 1e-6  # log가 무한대로 발산하는 것을 막아준다
 
        z = np.dot(self.__x_data, self.__W) + self.__b
        y = sigmoid(z)
 
        return -np.sum(self.__t_data * np.log(y + delta) + (1 - self.__t_data) * np.log((1 - y) + delta))
 
    def __error_eval(self):
        delta = 1e-6  # log가 무한대로 발산하는 것을 막아준다
 
        z = np.dot(self.__x_data, self.__W) + self.__b
        y = sigmoid(z)
 
        return -np.sum(self.__t_data * np.log(y + delta) + (1 - self.__t_data) * np.log((1 - y) + delta))
 
    def train(self):
 
        f = lambda x: self.__loss_func()
 
        for step in range(10001):
            self.__W -= self.__learning_rate * numerical_derivative(f, self.__W)
            self.__b -= self.__learning_rate * numerical_derivative(f, self.__b)
 
            if (step % 500== 0:
                print("step = ", step, ", error = "self.__error_eval(), ", W = "self.__W, ", b ="self.__b)
 
    def predict(self, input):
 
        z = np.dot(input, self.__W) + self.__b
        y = sigmoid(z)
 
        if y >= 0.5:
            result = 1
        else:
            result = 0
 
        return result
 
 
# 테스트 데이터
data_x = np.array([[00], [01], [10], [11]])
data_t = np.array([0110])
test_data = np.array([[00], [01], [10], [11]])
 
XOR_object = LogicGate(data_x, data_t)
XOR_object.train()
 
 
for input_data in test_data:
 
    pred = XOR_object.predict(input_data)
    print(input_data, " = ", pred)
cs

 

위의 소스코드를 실행시키면 아래와 같은 출력값을 얻을 수 있다.

 

반응형

'머신러닝_딥러닝 > Tensorflow + Keras' 카테고리의 다른 글

MNIST 1탄  (0) 2021.10.23
XOR 문제 (딥러닝으로 해결)  (0) 2021.10.23
로지스틱 회귀 (Logistic Regression)  (0) 2021.10.23
선형회귀 (Linear Regression)  (0) 2021.10.23
필수품 for Machine learning  (0) 2021.10.22

+ Recent posts