*Softmax Classification의 multinominal 개념 :



x1 , x2 , y 값이 주어졌을 때

좌표에 [x1, x2] = y로 표시한다. 


[wa1, wa2, wa3] [x1, x2, x3] (세로)  = [w1x1 + w2x2 + w3x3]  => a인지 아닌지 여부  [2.0]   => 0.7 (2.0/전체값 = softmax)

[wb1, wb2, wb3] [x1, x2, x3] (세로)  = [w1x1 + w2x2 + w3x3] => b인지 아닌지 여부 [1.0] => 0.2 (1.0/전체값 = softmax)

[wc1, wc2, wc3] [x1, x2, x3] (세로)  = [w1x1 + w2x2 + w3x3] => c인지 아닌지 여부 [0.1] =0.1 (0.1/전체값 = softmax)


H(x) = softmax(WX + b)

=> softmax 값이 가장 큰 것을 취한다(위에서는 'A')


argmax라는 함수를 쓴다

argmax에 확률을 집어넣어준다 (위 예시에서는 argmax(0.7) =1 , argmax(0.2) = 0, argmax(0.1) = 0 )




*A, B, C학점 예측 소스코드 :


05train.txt

1
2
3
4
5
6
7
8
9
#x0 x1 x2 y[A   B   C]
1   2   1   0   0   1
1   3   2   0   0   1
1   3   4   0   0   1
1   5   5   0   1   0
1   7   5   0   1   0
1   2   5   0   1   0
1   6   6   1   0   0
1   7   7   1   0   0
cs


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
import tensorflow as tf
import numpy as np
 
xy = np.loadtxt('./data/05train.txt', dtype='float32')
 
x_data = xy[:, 0:3]
y_data = xy[:, 3:]
print(x_data.shape, y_data.shape)
 
= tf.placeholder(tf.float32)
= tf.placeholder(tf.float32)
 
= tf.Variable(tf.zeros([3,3]))
hypothesis = tf.nn.softmax(tf.matmul(X,W))
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1))
train = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
 
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
 
    for step in range(5001):
        sess.run(train, feed_dict={X:x_data, Y:y_data})
        if step % 200 == 0:
            print(step, sess.run(cost, feed_dict={X:x_data, Y:y_data}), sess.run(W))
    a = sess.run(hypothesis, feed_dict={X:[[1,11,7]]})
    print(a, sess.run(tf.argmax(a, 1)))
#[[0.7576524  0.2345292  0.00781842]] [0]   0번째 있는 값이 제일 크다!! A일 확율이 76%
    c = sess.run(hypothesis, feed_dict={X:[[1,1,0]]})
    print(c, sess.run(tf.argmax(c, 1)))
#[[0.00227058 0.0237952  0.9739342 ]] [2]   3번째 있는 값이 제일 크다!! C일 확율이 97%
 
cs


*A, B, C학점 예측 소스코드(accuracy 포함) :

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
import tensorflow as tf
import numpy as np
 
xy = np.loadtxt('./data/05train.txt', dtype='float32')
 
x_data = xy[:, 0:3]
y_data = xy[:, 3:]
print(x_data.shape, y_data.shape)
 
= tf.placeholder(tf.float32)
= tf.placeholder(tf.float32)
 
= tf.Variable(tf.zeros([3,3]))
hypothesis = tf.nn.softmax(tf.matmul(X,W))
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1))
train = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
 
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
 
    for step in range(5001):
        sess.run(train, feed_dict={X:x_data, Y:y_data})
        if step % 200 == 0:
            print(step, sess.run(cost, feed_dict={X:x_data, Y:y_data}), sess.run(W))
    a = sess.run(hypothesis, feed_dict={X:[[1,11,7]]})
    print(a, sess.run(tf.argmax(a, 1)))
#[[0.7576524  0.2345292  0.00781842]] [0]   0번째 있는 값이 제일 크다!! A일 확율이 76%
    c = sess.run(hypothesis, feed_dict={X:[[1,1,0]]})
    print(c, sess.run(tf.argmax(c, 1)))
#[[0.00227058 0.0237952  0.9739342 ]] [2]   3번째 있는 값이 제일 크다!! C일 확율이 97%
 
 
    correct_prediction = tf.equal(tf.argmax(hypothesis, 1),
                                  tf.argmax(Y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction
                                      , tf.float32))
    print(sess.run(accuracy, feed_dict={X:x_data, Y: y_data})) #0.875 87%의 정확도
cs





*Binary Classification :


- 활용분야 :
=> spam email Detection : Spam or Ham

=> Facebook feed : Show or hide

=> Credit Card Fraud Detection : fraud or not


그래프 그리기 online : 

https://www.desmos.com/calculator



=> w값이 클 수록 기울기가 y 축에 가까워진다 :









I = log 1/p 


I = 정보량

1/p = 전체 사건 수


2^ = 6  => 3비트

- 3비트 불확실성이 크다


2^ = 2 => 1비트

- 2비트 불확실성이 낮다


=> 불확실성이 작은 것이 더 좋다!(entropy가 낮은것)


*Cost Function  :


C:(H(x), y) = -ylog(H(x)) - (1-y)log( 1-H(x) )


=> cost(W) = - 1/m SUM (ylog(H(x)) + 1-y) log (1- H(x)) )


*Logistic Regression (Hypothesis & Cost 함수 & Cost 최소화):





*Logistic Regression 소스 에제:


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
import tensorflow as tf
import numpy as np
tf.set_random_seed(888)
 
xy = np.loadtxt('./data/04train.txt', dtype='float32')
x_data = xy[:, 0:-1] # 행은 전체 행, 열은 0열 부터 끝에서 1번째 열까지 x_data로 지정
y_data = xy[:, [-1]] # 행은 전체 행, 열은 끝에서 1번째 열만 y_data로 지정
 
print(x_data.shape, y_data.shape) #(6, 3) (6, 1)  따라서 W는 [3, 1]로 만들어준다
 
= tf.placeholder(tf.float32)
= tf.placeholder(tf.float32)
 
= tf.Variable(tf.random_uniform([3,1], -1.1. )) #(6, 3) (6, 1)  따라서 W는 [3, 1]로 만들어준다
= tf.matmul(X,W)  # matrix multiplication
hypothesis = tf.div(1.1. + tf.exp(-h))
 
cost = -tf.reduce_mean(Y * tf.log(hypothesis) +
                       (1+Y) * tf.log(1-hypothesis))
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(cost)
 
sess = tf.Session()
sess.run(tf.global_variables_initializer())
 
for step in range(2001):
    sess.run(train, feed_dict={X:x_data, Y:y_data})
    if step % 20 == 0:
        print(step, sess.run(cost, feed_dict={X:x_data, Y:y_data})
              , sess.run(W))
cs






* Logistic Regression (with Accuracy) :


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
import tensorflow as tf
import numpy as np
tf.set_random_seed(888)
 
xy = np.loadtxt('./data/04train.txt', dtype='float32')
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
 
print(x_data.shape, y_data.shape) #(6, 3) (6, 1)  따라서 W는 [3, 1]로 만들어준다
 
= tf.placeholder(tf.float32)
= tf.placeholder(tf.float32)
 
= tf.Variable(tf.random_uniform([3,1], -1.1. )) #(6, 3) (6, 1)  따라서 W는 [3, 1]로 만들어준다
= tf.matmul(X,W)  # matrix multiplication
hypothesis = tf.div(1.1. + tf.exp(-h))
 
cost = -tf.reduce_mean(Y * tf.log(hypothesis) +
                       (1+Y) * tf.log(1-hypothesis))
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(cost)
 
sess = tf.Session()
sess.run(tf.global_variables_initializer())
 
for step in range(2001):
    sess.run(train, feed_dict={X:x_data, Y:y_data})
    if step % 20 == 0:
        print(step, sess.run(cost, feed_dict={X:x_data, Y:y_data})
              , sess.run(W))
 
= sess.run(hypothesis, feed_dict={X:[[1,2,2]]})
print(a > 0.5)
 
#예측과 정답 비율
# 0     0
# 0     1
# 1     1
# 정답 비율은 2/3.
# 이걸 수식으로 옮겨보면 :
 
predicted = tf.cast(hypothesis > 0.5, dtype = tf.float32)
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y)
                                  , dtype=tf.float32))
acc = sess.run(accuracy, feed_dict={X:x_data, Y:y_data})
print(acc)
 
cs




*Diabetes 유관 Dataset을 분석 :



★문제풀이 :

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
import tensorflow as tf
import numpy as np
 
xy = np.loadtxt('./data/diabetes.csv', delimiter=',', dtype='float32')
print(xy)
 
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
 
# print(x_data, y_data)
print(x_data.shape, y_data.shape)  # [8:1]
 
= tf.placeholder(tf.float32)
= tf.placeholder(tf.float32)
 
= tf.Variable(tf.random_uniform([8,1], 1.1.))
 
= tf.matmul(X,W)  # matrix multiplication
hypothesis = tf.div(1.1. + tf.exp(-h))
 
cost = -tf.reduce_mean(Y * tf.log(hypothesis) +
                       (1+Y) * tf.log(1-hypothesis))
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(cost)
 
sess = tf.Session()
sess.run(tf.global_variables_initializer())
 
for step in range(200001):
    sess.run(train, feed_dict={X:x_data, Y:y_data})
    if step % 20 == 0:
        print(step, sess.run(cost, feed_dict={X:x_data, Y:y_data})
              , sess.run(W))
 
predicted = tf.cast(hypothesis > 0.5, dtype = tf.float32)
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y)
                                  , dtype=tf.float32))
acc = sess.run(accuracy, feed_dict={X:x_data, Y:y_data})
print(acc)
 
cs


★정답 :

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
import tensorflow as tf
import numpy as np
tf.set_random_seed(777)  
 
xy = np.loadtxt('./data/diabetes.csv', delimiter=',', dtype=np.float32)
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
 
print(x_data.shape, y_data.shape)
 
= tf.placeholder(tf.float32, shape=[None, 8])
= tf.placeholder(tf.float32, shape=[None, 1])
 
= tf.Variable(tf.random_uniform([81], -1.,1.))
= tf.Variable(tf.random_uniform([1], -1.1.))
 
hypothesis = tf.sigmoid(tf.matmul(X, W) + b)
 
cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) *
                       tf.log(1 - hypothesis))
 
train = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
 
predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))
 
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
 
    for step in range(30001):
        cost_val, _ = sess.run([cost, train], feed_dict={X: x_data, Y: y_data})
        if step % 200 == 0:
            print(step, cost_val)
 
    h, c, a = sess.run([hypothesis, predicted, accuracy],
                       feed_dict={X: x_data, Y: y_data})
    print("\nHypothesis: ", h, "\nCorrect (Y): ", c, "\nAccuracy: ", a)
 
 
cs

*multi-variable linear regression은 이전 linear regression과 다르게 x값이 여러개이다


1) one-variable regression Hypothesis

H(x) = Wx + b


2) two-variable regression Hypothesis

H(x1, x2) = w1x1 + w2x2 + b


3) multi-variable regression Hypothesis

H(x1,x2...xn) = w1x1 + w2x2 + w3x3 ... + wnxn + b



위 수식은 비효율적 따라서 아래 Matrix Multiplication 수식으로 변경해준다


H(x1, x2...xn) = [w1, w2, w3] [x1 x2 x3] (세로) + b

H(x1, x2...xn) = [x1, x2, x3] [w1 w2 w3] (세로) + b

H(X) = WX + b

H(X) = XW + b


b term을 없앤 simplified된 형태 =>  w 괄호 안으로 넣어준다.


H(x1, x2...xn) = [b w1, w2, w3] [x1 x2 x3] (세로) + b

H(x1, x2...xn) = [x1, x2, x3] [b w1 w2 w3] (세로) + b

H(X) = WX
H(X) = XW

아래와 같은 Transpose 형태로 쓸 수도 있다 :

w = [w1 w2 w3] (세로)   x= [x1 x2 x3] (세로)
H(X) = WtX + b




*Multi-variable linear regression에서의 Cost function :


Cost Function은 이전 linear regression과 똑같다 :

Gradient Descent 알고리즘을 사용한다.


cost(W,b) = 1/m 평균(H(x)- y ) 제곱



* Multi-variable linear regression 구현 실습 : 



1) 2개의 x variable( 비효율적인 방법 = matrix 형태아님 ) :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import tensorflow as tf
 
x1_data = [1.,0.,3.,0.,5.]
x2_data = [0.,2.,0.,4.,0.]
y_data = [1,2,3,4,5]
 
W1 = tf.Variable(tf.random_uniform([1], -11))
W2 = tf.Variable(tf.random_uniform([1], -11))
= tf.Variable(tf.random_uniform([1], -11))
 
hypothesis = W1*x1_data + W2*x2_data + b
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(cost)
 
sess = tf.Session()
sess.run(tf.global_variables_initializer())
 
for step in range(2001) :
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(cost), sess.run(W1), sess.run(W2), sess.run(b))
 
cs


2) 2개의 x variable( 효율적인 방법 = matrix 형태 ) :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import tensorflow as tf
 
x_data = [[1.,0.,3.,0.,5.],[0.,2.,0.,4.,0.]]
y_data = [1,2,3,4,5]
 
= tf.Variable(tf.random_uniform([1,2], -11))
= tf.Variable(tf.random_uniform([1], -11))
 
hypothesis = tf.matmul(W, x_data) + b  # H(X) = WX + b
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(cost)
 
sess = tf.Session()
sess.run(tf.global_variables_initializer())
 
for step in range(2001) :
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(cost), sess.run(W), sess.run(b))
 
cs


1)2) 의 비교 


b term을 없애고 matrix를 [1,3]으로 변경 시 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import tensorflow as tf
 
x_data = [[1,1,1,1,1],
         [1.,0.,3.,0.,5.],
          [0.,2.,0.,4.,0.]]
y_data = [1,2,3,4,5]
 
= tf.Variable(tf.random_uniform([1,3], -11))
 
 
hypothesis = tf.matmul(W, x_data)  # H(X) = WX
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(cost)
 
sess = tf.Session()
sess.run(tf.global_variables_initializer())
 
for step in range(2001) :
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(cost), sess.run(W))
 
cs






*Data를 load 하여 학습 시키기 : 


=> Pycharm에 data를 추가한다.


data.zip

프로젝트 폴더에 놓는다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import tensorflow as tf
import numpy as np
 
xy = np.loadtxt('./data/03train.txt', dtype='float32')
print(xy)
 
x_data = xy[:, 0 : -1]
y_data = xy[:, [-1]]
print(x_data.shape, y_data.shape)
 
= tf.Variable(tf.random_uniform([3,1], -1.1.)) # 3 = X 열의 개수 
hypothesis = tf.matmul(x_data, W)
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(cost)
 
sess =tf.Session()
sess.run(tf.global_variables_initializer())
 
for step in range(2001) :
    sess.run(train)
    if step % 20 == 0: # 20 번에 1번씩
        print(step, sess.run(cost), sess.run(W))
cs



*CSV 파일을 읽어서 출력하기(delimiter는 , 콤마로 ) :


1
2
3
4
5
6
7
8
9
10
import tensorflow as tf
import numpy as np
 
xy = np.loadtxt('./data/test-score.csv', delimiter=',', dtype='float32')
print(xy)
 
x_data = xy[:, 0 : -1]
y_data = xy[:, [-1]]
print(x_data.shape, y_data.shape)
 
cs


*File input linear regression :


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
import tensorflow as tf
import numpy as np
 
tf.set_random_seed(777)  
 
xy = np.loadtxt('./data/test-score.csv', delimiter=',', dtype=np.float32)
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
 
print(x_data.shape, x_data, len(x_data))
print(y_data.shape, y_data)
 
= tf.placeholder(tf.float32, shape=[None, 3])
= tf.placeholder(tf.float32, shape=[None, 1])
 
= tf.Variable(tf.random_normal([31]))
= tf.Variable(tf.random_normal([1]))
 
hypothesis = tf.matmul(X, W) + b
 
cost = tf.reduce_mean(tf.square(hypothesis - Y))
 
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)
train = optimizer.minimize(cost)
 
sess = tf.Session()
sess.run(tf.global_variables_initializer())
 
for step in range(2001):
    cost_val, hy_val, _ = sess.run(
        [cost, hypothesis, train], feed_dict={X: x_data, Y: y_data})
    if step % 10 == 0: # 10번에 1번씩
        print(step, "Cost: ", cost_val, sess.run(W), sess.run(b))
 
print("=====prediction=====")
print(sess.run(hypothesis, feed_dict={X: [[10070101]]}))
print(sess.run(hypothesis, feed_dict={X: [[6070110], [9010080]]}))
 
 
 
cs








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import tensorflow as tf
x_data = [1.2.3.]
y_data = [1.2.3.]
= tf.Variable(tf.random_uniform([1], -1.1.)) #초기 값을 랜덤하게 준다 -1에서 1 사이에서 1개
= tf.Variable(tf.random_uniform([1], -1.1.)) #초기 값을 랜덤하게 준다 -1에서 1 사이에서 1개
hypothesis = w * x_data + b
cost = tf.reduce_mean(tf.square(hypothesis - y_data)) # Cost를 구한다
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(cost)  #가장 작은 cost륵 가져온다
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for step in range(2001):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(cost), sess.run(w), sess.run(b))
 
cs


위 코드는 하드코딩으로 값을 주고 있음으로 placeholder를 사용해서 재사용할 수 있도록 만들어 준다 :


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
import tensorflow as tf
 
x_data = [1.2.3.]
y_data = [1.2.3.]
 
= tf.Variable(tf.random_uniform([1], -1.1.)) #초기 값을 랜덤하게 준다 -1에서 1 사이에서 1개
= tf.Variable(tf.random_uniform([1], -1.1.)) #초기 값을 랜덤하게 준다 -1에서 1 사이에서 1개
 
= tf.placeholder(tf.float32)
= tf.placeholder(tf.float32)
 
hypothesis = w * X + b
cost = tf.reduce_mean(tf.square(hypothesis - Y)) # Cost를 구한다
 
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(cost)  #가장 작은 cost륵 가져온다
 
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
 
for step in range(2001):
    sess.run(train, feed_dict={X:x_data, Y:y_data})
    if step % 20 == 0:
        print(step, sess.run(cost, feed_dict={X:x_data, Y:y_data}), sess.run(w), sess.run(b))
cs



위 내용을 비교를 하면 :




위 코드에서 Hypothesis를 구하려면 X(x_data) 만 있으면 된다(Y는 필요없음) 

코드 맨 아래줄에 아래와 같이 추가해준다 :


1
print(sess.run(hypothesis, feed_dict={X:5}))
cs


전체 코드 :


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
import tensorflow as tf
 
x_data = [1.2.3.]
y_data = [1.2.3.]
 
= tf.Variable(tf.random_uniform([1], -1.1.)) #초기 값을 랜덤하게 준다 -1에서 1 사이에서 1개
= tf.Variable(tf.random_uniform([1], -1.1.)) #초기 값을 랜덤하게 준다 -1에서 1 사이에서 1개
 
= tf.placeholder(tf.float32)
= tf.placeholder(tf.float32)
 
hypothesis = w * X + b
cost = tf.reduce_mean(tf.square(hypothesis - Y)) # Cost를 구한다
 
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(cost)  #가장 작은 cost륵 가져온다
 
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
 
for step in range(2001):
    sess.run(train, feed_dict={X:x_data, Y:y_data})
    if step % 20 == 0:
        print(step, sess.run(cost, feed_dict={X:x_data, Y:y_data}), sess.run(w), sess.run(b))
 
print(sess.run(hypothesis, feed_dict={X:5}))
cs





*Cost의 최소화 방법 :


H(x) = Wx + b


Wx 와 H(x) 값이 거의 비슷( = 예측값)


cost(W,b)  = W와 b에 대한 함수 

cost(W) = b가 값이 minor함으로 W에 대한 함수로 변경


cost(W) = 1/m 평균 (Wx - y)제곱


cost가 가장 작을 때 W와 b의 값을 구하기 위해서

Gradient descent algorithm을 사용한다.

Local Minimum에 도달할 때까지 줄여나간다...


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
import tensorflow as tf
import matplotlib.pyplot as plt
tf.set_random_seed(777)  # for reproducibility - seed를 주는 것은 random variable을 일정하게 주기위함

= [123]
= [123]
 
= tf.placeholder(tf.float32)
 
# Our hypothesis for linear model X * W
hypothesis = X * W
 
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
 
# Launch the graph in a session.
sess = tf.Session()
# Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
 
# Variables for plotting cost function
W_vals = []
cost_vals = []
 
for i in range(-3050):
    curr_W = i * 0.1 # 촘촘하게 그려주기 위해 0.1을 준다.
    curr_cost = sess.run(cost, feed_dict={W: curr_W})
    W_vals.append(curr_W)
    cost_vals.append(curr_cost)
 
# Show the cost function
plt.plot(W_vals, cost_vals) # X= W_vals, Y=cost_vals
plt.show() # 화면에 보여주기
 
cs


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
import tensorflow as tf
tf.set_random_seed(777)  # for reproducibility
 
x_data = [123]
y_data = [123]
 
# Try to find values for W and b to compute y_data = W * x_data + b
# We know that W should be 1 and b should be 0
# But let's use TensorFlow to figure it out
= tf.Variable(tf.random_normal([1]), name='weight')
 
= tf.placeholder(tf.float32)
= tf.placeholder(tf.float32)
 
# Our hypothesis for linear model X * W
hypothesis = X * W # Simplified Hypothesis
 
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
 
# Minimize: Gradient Descent using derivative: W -= learning_rate * derivative
# Gradient Descent Optimizer 대신에 아래와 같은 공식을 사용한다 :
learning_rate = 0.1
gradient = tf.reduce_mean((W * X - Y) * X)
descent = W - learning_rate * gradient
update = W.assign(descent)
 
# Launch the graph in a session.
sess = tf.Session()
# Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
 
for step in range(21):
    sess.run(update, feed_dict={X: x_data, Y: y_data})
    print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}), sess.run(W))
 
'''
0 5.81756 [ 1.64462376]
1 1.65477 [ 1.34379935]
2 0.470691 [ 1.18335962]
3 0.133885 [ 1.09779179]
4 0.0380829 [ 1.05215561]
5 0.0108324 [ 1.0278163]
6 0.00308123 [ 1.01483536]
7 0.000876432 [ 1.00791216]
8 0.00024929 [ 1.00421977]
9 7.09082e-05 [ 1.00225055]
10 2.01716e-05 [ 1.00120032]
11 5.73716e-06 [ 1.00064015]
12 1.6319e-06 [ 1.00034142]
13 4.63772e-07 [ 1.00018203]
14 1.31825e-07 [ 1.00009704]
15 3.74738e-08 [ 1.00005174]
16 1.05966e-08 [ 1.00002754]
17 2.99947e-09 [ 1.00001466]
18 8.66635e-10 [ 1.00000787]
19 2.40746e-10 [ 1.00000417]
20 7.02158e-11 [ 1.00000226]
'''
 
cs






*일반적인 직선을 나타내는 공식(선형을 나타내는 가설 Hypothesis) : 

y = wx + b

H(x) = wx + b


위 공식에서 W와 B가 미지수이다. 

결국 W와 b를 찾는것이 목적!!


w= weight 기울기

b= bias


(x, y) , (x1, y1), (x2, y2) 의 값이 있을 때

(x, H(x)), (x1, H(x1)), (x2, H(x2))


Cost = 1/N <<(H(x) - y)2


Cost는 w의 제곱식 

Cost는 작으면 작을 수록 좋다!(Loss가 적다는 의미)


*Linear Regression을 하기 위한 기본 적인 3가지 요소

- Hypothesis

- Cost 정의(에측값에서 제곱을 해서 평균을 구한 값)

- Cost를 최소화 하기 위한 알고리즘(Gradient Decent...)


* 최적의 Hypothesis의 선택 :
=> H(x) - y를 최소화하는 직선을 찾으면 됨!

- Cost = Hypothesis에서 예측값 목표를 뺀값의 제곱의 평균

(tf.reduce_mean(tf.square(hypothesis - y_data)))




*Linear Regression Example (with Pycharm) : 


1) Pycharm 가상환경에서 tensorflow 설치 :



(Terminal에서 'pip install tensorflow' 입력)



2) Pycharm에서 Python 파일 생성하기 :

실행하기 (shift + F10) or 마우스 우클릭 후 Run linear_Regression



3) tensorflow로 학습시키기 :



소스코드 :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import tensorflow as tf
 
x_data = [1.2.3.]
y_data = [1.2.3.]
 
 
= tf.Variable(tf.random_uniform([1], -1.1.)) #초기 값을 랜덤하게 준다 -1에서 1 사이에서 1개
= tf.Variable(tf.random_uniform([1], -1.1.)) #초기 값을 랜덤하게 준다 -1에서 1 사이에서 1개
 
hypothesis = w * x_data + b
cost = tf.reduce_mean(tf.square(hypothesis - y_data)) # Cost를 구한다
 
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(cost)  #가장 작은 cost륵 가져온다
 
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
 
for step in range(2001):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(cost), sess.run(w), sess.run(b))
cs






*모두를 위한 머신러닝 링크:

=> https://hunkim.github.io/ml



*머신러닝과 Traditional Programming의 차이는?

(ML) Data + Output => Computer => Programming

(Traditional) Data + Programming => Computer => Output


*기계학습의 핵심 :
"일반화된 규칙을 통해 미래를 예측할 수 있다!!"


*머신러닝의 알고리즘 유형 :


1. 지도학습(Supervised Learning) : 답이 달려있는 상태에서 학습을 하는 것

2. 자율학습 - 비지도학습(Unsupervised Learning) : 답이 없는 상태에서 학습을 하는데...Data들을 잘 설명해주는 변수 (군집 분산 - Clustering OR 축소해봤더니 Insight를 주더라...)

3. 준지도학습(Semi-Supervised Learning) : 데이터 100만건 중에 10만건에 답이 있다. 이 상태에서 학습을 시킴. 목표값이 표시된 데이터와 표시되지 않은 데이터를 모두 훈련에 사용하는 것을 말함

4. 강화학습(Reinforcement Learning) : 

어떤 환경을 탐색하는 에이젼트가 현재의 상태를 인식하여 어떤 행동을 취한다면 그 에이젼트는 환경으로부터 포상을 얻게 됨.

포상은 음수와 양수 둘 다 가능하며, 강화 학습 알고리즘은 그 에이전트가 앞으로 누적될 포상을 최대화하는 일련의 행동으로 정의되는 정책을 찾는 방법


=> 요즘 학자들은 비지도 학습강화 학습에 집중하고 있음...




*접근 방법별 알고리즘 :

1) 결정트리 학습법(Decision Tree)

2) 연관규칙 학습법(Association Rule)

3) 인공신경망(Artificial Neural Network)

4) 유전계획법

5) 귀납 논리 계획법

6) 서포트 벡터 머신

7) 클러스터링

8) 베이즈 네트워크

9) 강화학습법

10) 표현학습법

11) 동일성 계측 학습법 등...



*(Supervised Learning) 지도학습의 예 : 


- 공부한 시간 대비 시험 점수를 예측 (공부를 많이하면 점수가 올라간다, 날씨가 추워지면 따뜻한 커피가 많이 팔린다) 

=> regression


- 공부한 시간 대비 시험의 합격/불합격 여부 

=> binary classification


- 공부한 시간 대비 (A,B,C,D,F) 학점 

=> multi-label classification, multi-nominal classification, softmax classification


- 라벨링 된 데이터에 대한 예측 (이미지를 학습시키는...확률값이 output으로 나온다)


*X와 Y를 잘 Define 해야 한다 : 

Y(숫자) : Linear Regression으로 풀 수 있다

Y(숫자X) : 2중 하나 : Pass/Fail, Female/Male -> Logistic Regression으로 풀 수 있다

              2개 이상 : A/B/C, 고양이/강아지/모자 와 같은 데이터(숫자가 아닌 nominal data) -> Softmax Classification으로 풀 수 있다




*기계학습의 절차 : 

- Dataset을 확보한다(DB Table 또는 CSV 파일) 

- Y를 구분한다(결과변수, 응답변수, 종속변수, 표적변수 등...)


*기계학습 세부절차

1) Business 이해(Biz Objective 정의, 환경/상황분석, 분석의 목표 설정)

2) Data 이해(원시데이터 확보, Describe Data, Explore Data)

3) Data Preparation(데이터 정제)

4) Modeling(모델링 기법 선택, Test 설계, 모델 구축)

5) Evaluation(결과 평가)

6) Deployment(Deploy, Report & Review)


=> 2번->4번 을 결과자 잘 나올 때 까지 무한반복한다




*Deep Learning : 

- 여러 비선형 변환 기법의 조합을 통해 높은 수준의 추상화를 시도하는 기계학습 알고리즘의 집합

- 사람의 사고 방식을 컴퓨터에게 가르치는 기계학습의 한 분야

- 1940년대의 인공신경망의 변형 분야


+ Recent posts