Programming/Tensorflow2017. 8. 2. 20:00

Learning rate

Overshooting : Learning rate의 값이 너무 커 튕겨나감

Takes too long : Learning rate의 값이 너무 작아 바닥까지 못내려감

 

Solution!

- Data(x) preprocessing

Original data -> Zero-centered-data -> Normalized data

- Standardiztion

X_std[i,0] = (X[i,0] - X[i,0].mean()) / X[i,0].std()

 

Overfitting

- Our model is very good with training data set

+ BUT not good at test dataset or in real use

 

Solution!

- More training data!

- Reduce the number of features

- Regularization

 

Regularization?

- Let's not have too big numbers in the weight

12reg = 0.001 * tf.reduce_sum(tf.square(w))

 

=================================================================

 

 

 

=================================================================

Posted by BadSchool
Programming/Tensorflow2017. 7. 30. 18:30

ex)

Spam Detection : Spam or Ham

Facebook feed : Show or Hide

Credit Card Fraudulent Trasaction detection : legitimate / fraud

 

Linear Regression 문제점

합격임에도 불구하고 불합격 판정을 줄 수 있다.

 

- We know Y is 0 or 1

- H(x) = Wx + b

but Hypothesis can give vaules large than 1 or less than 0 (너무 큰 값을 받아들이지 못함)

 

Solution!

Used sigmoid Func.

 

Cost Func. 문제점

기존의 func는 변경된 H(x) 함수에 적용할 수 없음

 

Solution!

연립방정식으로 두가지 경우를 생각 (y=0, y=1)

 

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
import tensorflow as tf
 
x_data = [[1,2], [2,3], [3,1], [4,3], [5,3], [6,2]]
y_data = [[0], [0], [0], [1], [1], [1]]
 
= tf.placeholder(tf.float32, shape = [None, 2])
= tf.placeholder(tf.float32, shape = [None, 1])
 
= tf.Variable(tf.random_normal([2,1]), name = 'weight')
= tf.Variable(tf.random_normal([1]), name = 'bias')
 
# Hypothesis Func.
hypothesis = tf.sigmoid(tf.matmul(X, W) + b)
 
# Cost Func.
cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) * tf.log(1 - hypothesis))
 
# Minimize Func.
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)
 
predicted = tf.cast(hypothesis > 0.5, dtype = tf.float32)
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype = tf.float32))
 
 
# Launch Graph
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
 
    for step in range(10001):
        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("\nHypthesis: ", h, "\nCorrect (Y) ", c, "\Accuracy: ", a)
cs

 https://github.com/BadSchool/Study/blob/master/tensorflow/tf_5-2.py

====================================================================

 

 

====================================================================

Posted by BadSchool
Programming/Tensorflow2017. 7. 30. 18:12

Recap

- Hypothesis(가설. 어떻게 예측할 것 인지)

- Cost function(cost 계산 방법)

- Gradient descent algorithm(cost 값 최적화)

 

변수들이 많아지면 복잡해 지므로 Matrix를 사용하여 일괄 계산

 

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
#Matrix 사용 함
import tensorflow as tf
 
x_data = [[73.80.75.], [93.,88.,93], [89.,91.,90], [96.,98.,100.], [73.,66.,70]]
y_data = [[152.], [185.], [180.], [196.], [142.]]
 
= tf.placeholder(tf.float32, shape=[None, 3])
= tf.placeholder(tf.float32, shape=[None, 1])
 
= tf.Variable(tf.random_normal([3,1]), name='weight')
= tf.Variable(tf.random_normal([1]),name='bias')
 
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={x1: x1_data, x2: x2_data, x3: x3_data, Y: y_data})
    if step % 10 == 0:
        print(step, "Cost: ", cost_val, "\nPrediction:\n",hy_val)
        
cs
https://github.com/BadSchool/Study/blob/master/tensorflow/tf_4-1.py

 

==================================================================

 

 

 

==================================================================

'Programming > Tensorflow' 카테고리의 다른 글

[Tensorflow] Application & Tips  (0) 2017.08.02
[Tensorflow] Binary Classfication  (0) 2017.07.30
[Tensorflow] Linear Regression  (0) 2017.07.30
[Tensorflow] 준비사항 2  (0) 2017.07.30
[Tensorflow] 준비사항 1  (0) 2017.07.30
Posted by BadSchool
Programming/Tensorflow2017. 7. 30. 18:00

Cost Function.

- How fit the line to our (Training) Data?

 

Cost = ( H ( x1 ) - y1 )^2 + ( H ( x2 ) - y2 )^2 + ( H ( x3 ) - y3 )^2

-> 제곱하는 이유 : 음수, 양수를 모두 양수로 통일시키기 위하여

 

Linear Regression?

예측값과 실제값의 오차를 구하여 가장 적은 오차를 찾음

즉 가장 작은 값 (가장 오차가 적은 값) 을 나오게 하는 W와 b를 구하는 과정

 

in Tenserflow

1. Build graph using Tensorflow operations

2. sess.run(op, feed_dict={x:x_data})

3. update variables in the graph (and return values)

 

How to minimize cost?

 

최솟값을 구하는 알고리즘

Gradient descent algorithem : 경사를 따라 내려가는 알고리즘

- Minimize cost function

- used many minimization problems

- For given cost func. , cost(W, b), it will find W, b to minimize cost

- It can be applied to more general func. : cost(w1, w2, ...)

 

How it works? / How would you find the lowest point?

 

start any value ex(0, 0)

Keeping changing W and b a liittle bit to try and reduce cost(W, b)

경사도는 어떻게? -> 미분을 이용함

 

Convex Fucntion : 어느점에서 시작하던 결과값이 같음

H(x) = Wx

 

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
import tensorflow as tf
= tf.Variable(tf.random_normal([1]), name='weight')
= tf.Variable(tf.random_normal([1]), name='bias')
= tf.placeholder(tf.float32, shape=[None])
= tf.placeholder(tf.float32, shape=[None])
 
# hypothesis = XW + b
hypothesis = X * W + b
 
# 추측값과 실제값의 차이를 모두 더하여 평균을 구함
cost = tf.reduce_mean(tf.square(hypothesis - Y))
 
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
 
# 그 오차값을 최대한 낮추는 작업
train = optimizer.minimize(cost)
 
sess = tf.Session()
 
sess.run(tf.global_variables_initializer())
 
for step in range(2001):
    cost_val, W_val, b_val, _ = sess.run([cost, W, b, train], feed_dict={X : [12345], Y : [2.13.14.15.16.1]})
    # 20번에 한번씩 출력
    if step % 20 == 0:
        print(step, cost_val, W_val, b_val)
cs

https://github.com/BadSchool/Study/blob/master/tensorflow/tf_1.py 

=====================================================================

 

 

 

=====================================================================

'Programming > Tensorflow' 카테고리의 다른 글

[Tensorflow] Binary Classfication  (0) 2017.07.30
[Tensorflow] Multi-Variable linear regression (use matrix)  (0) 2017.07.30
[Tensorflow] 준비사항 2  (0) 2017.07.30
[Tensorflow] 준비사항 1  (0) 2017.07.30
[Tensorflow] Intro  (0) 2017.07.30
Posted by BadSchool
Programming/Tensorflow2017. 7. 30. 17:30

기초지식

 

확률

어떤 사건이 일어날 수 있는 경우를 신뢰할 수 있는 정도를 규정하는 방법, 2가지로 나뉨

 

(1) 빈도론자(Frequentist)

얼마만큼 빈번하게 특정한 사건이 반복되어 발생하는가를 관찰, 이를 기반으로 가설을 검증

즉, 사전 확률이 없다.

-> 사건이 독립적이고 반복적이며, 그 확률분포가 정규분포를 보이는 문제에 적합 ex.) 도박승률, 농작물 수확량, 보험금 계산, Etc.

 

(2) 베이지안(Bayesian)

어떤 가설의 확률을 평가하기 위해 주관적으로 또는 임의적으로 사전 확률을 먼저 정하고, 관찰된 데이터를 기반으로 가능도를 계산하여 처음의 설정된 확률을 보정

-> 사전 관찰 지식이 없는 불확실한 상황 예측에 적합, 관찰된 데이터를 가지고 조건부로 가설을 검증

 

선형대수학

벡터와 행렬은 인공신경망을 이해하기 위한 기초 수학이다.

 

(1) 벡터

방향과 크기의 의미를 모두 포함하는 수학으로 스칼라 값들을 순서대로 가진다.

선형수학에서의 n-차원 벡터 -> n개의 원소를 갖는 벡터로 열 벡터(ColumnVector)로 표현 = 행 벡터(Row vector)

 

(2) 행렬

행렬은 원소들이 놓여지는 행과 열을 가진다.

행 또는 열의 크기가 1이고, 다른 열 또는 행의 크기가 1이 아닐때 그 행렬은 벡터로 볼 수 있다.

 

행렬과 벡터의 곱셈은 일정한 규칙에 따라 계산한다.

([i][j] = sum(A[i][k] * B[k][j]) for k = 0....n

 

해석학 - 미분

연속적이로 매끄러운 함수(미분 가능한 함수)에서 특정 지점의 접선의 기울기는 그 점에서의 미분 값과 같다.

미분이 불가능한 경우 = (뾰족 점, 불연속적인 점, 접선이 수직인 점)

 

합성함수의 미분

 

합성함수?

함수 g(x)의 결과값이 다시 다른 함수 f(x)의 값으로 들어가는 f(g(x))의 구조

여러번 합성 된 경우로 동일한 규칙을 적용할 수 있으며, 인공 신경망의 역전파 알고리즘에서 사용

 

편미분

다변수 함수를 미분할 때 미분대상 변수 외에 나머지 변수를 고정시켜 상수처럼 생각하여 미분하는 방식

다변수 f가 동립변수 x, y 를 가지고 있을 때 , 함수 f를 x에 대하여 편미분 한 것은 밑에 사진을 참조.

 

=================================================================

 

 

 

=================================================================

'Programming > Tensorflow' 카테고리의 다른 글

[Tensorflow] Binary Classfication  (0) 2017.07.30
[Tensorflow] Multi-Variable linear regression (use matrix)  (0) 2017.07.30
[Tensorflow] Linear Regression  (0) 2017.07.30
[Tensorflow] 준비사항 1  (0) 2017.07.30
[Tensorflow] Intro  (0) 2017.07.30
Posted by BadSchool
Programming/Tensorflow2017. 7. 30. 17:02

머신러닝을 하기전 기초 지식


기초수학

대수학 - 선형 대수학(Linear Algebra)

해석학 - 미적분학, 벡터 미적분학, 미분 방정식

확 . 통 - 통계학, 확률론


통계학?

자료를 수집, 분류, 분석, 표현 하여 어떤 현상의 인과관계를 설명학, 나아가서는 미래에 벌어질 상황을 예측함

기술통계학(Descriptive), 추측통계학(Inferential Statistics)


기술통계학??

관찰된 자료를 수집 및 정리

자료 형태를 표현(중심의 측정, 산포의 측정)

자료의 특성 값 도출(대표값, 변동의 크기 등)

-> 데이터를 수집하고 분류하고 분석해 컴퓨터에 학습시킴


추측통계학??

모집단에서 추출된 표본 자료를 분석하여 특성 값 도출

확률 이론을 바탕으로 모집단의 특성을 파악

-> 새로운 결과값에 대해 결과를 예측하는 과정에 주로 사용


※상관분석은 독립변수와 종속변수간의 관계를 확인하고, 회귀분석은 변수들 간 인과관계를 설명한다.

- 종속변수(Dependent Variable) : 우리가 알고 싶어 하는 결과 값

- 독립변수(Independent Variable) : 결과 값에 영향을 주는 입력 값


상관분석

상관계수(r) : 변수간의 관계 정도 (-1 <= r <= 1)


회귀분석

측정된 변수들의 데이터로부터 관계를 함수식으로 설명

독립변수의 값에의해 종속변수의 값 예측

결정계수(r^2) : 독립변수로 얼마나 의미있게 예측할 수 있는지 ( 0 <= r^2 <= 1)

일반적으로 r^2 >= 0.65 이면 의미있는 회귀식이다.


================================================================




================================================================



 

'Programming > Tensorflow' 카테고리의 다른 글

[Tensorflow] Binary Classfication  (0) 2017.07.30
[Tensorflow] Multi-Variable linear regression (use matrix)  (0) 2017.07.30
[Tensorflow] Linear Regression  (0) 2017.07.30
[Tensorflow] 준비사항 2  (0) 2017.07.30
[Tensorflow] Intro  (0) 2017.07.30
Posted by BadSchool
Programming/Tensorflow2017. 7. 30. 15:50

안녕하세요, 오랜만에 글을 올리는 듯 하네요. 요즘 김성훈교수님의 텐서플로우 강의를 보느라 업로드를 잊고 있었습니다 ㅎㅎ;


이 곳에서는 제가 Tensorflow를 공부하면서 메모해 둔 것들을 올리도록 하겠습니다.

Posted by BadSchool