[인공지능 #5 ] Logistics classification 가설함수
python 문법에 관한 글 입니다.
인공지능 tensor flow 코딩을 위해 python 문법에 대해 정리를 하고자 합니다.
글의 순서는 아래와 같습니다
==========================================
1.Logistics classification 가설함수
==> 합격, 불합격을 구분할때 적용함
2. 당뇨병 예측
3. Next step
==> Multinomial : 여러개의 classification의 확율을 구함.
4. 참고자료
============================================
[ Logistics classification 가설함수]
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# Lab 5 Logistic Regression Classifier
import tensorflow as tf
tf.set_random_seed(777) # for reproducibility
x_data = [[1, 2],
[2, 3],
[3, 1],
[4, 3],
[5, 3],
[6, 2]]
# x data에 따라 합부(0,1)로 나타는 Y data를 예측함
# 공부한 시간에 따른 합격여부 data
y_data = [[0],
[0],
[0],
[1],
[1],
[1]]
# placeholders for a tensor that will be always fed.
X = tf.placeholder(tf.float32, shape=[None, 2])
Y = tf.placeholder(tf.float32, shape=[None, 1])
W = tf.Variable(tf.random_normal([2, 1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
# sigmoid 함수 사용함
==> h(x) 가 0~1 사이에 값을 갖게됨.
==> cost(w)은 y값과 h(x)차이가 크면 1에 가깝고, 작으면 0에 가까워지도록 구현함 , 이를 하나의 공식으로 통일시킴.
-기존의 cost함수형식으로 하게되면 울퉁불퉁한 2차 곡선 형태되고, 경사를 내려오면서 수많은 기울기 0 지점을 지나게 되어, 목표지점에 다다르지 못하게됨
-따라서 다른 코스트 함수가 필요함, 아래 함수가 그 대안임
# Hypothesis using sigmoid: tf.div(1., 1. + tf.exp(tf.matmul(X, W)))
hypothesis = tf.sigmoid(tf.matmul(X, W) + b)
# cost/loss function
cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) *
tf.log(1 - hypothesis))
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)
# Accuracy computation
# True if hypothesis>0.5 else False
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:
# Initialize TensorFlow variables
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)
# Accuracy report
h, c, a = sess.run([hypothesis, predicted, accuracy],
feed_dict={X: x_data, Y: y_data})
print("\nHypothesis: ", h, "\nCorrect (Y): ", c, "\nAccuracy: ", a)
'''
0 1.73078
200 0.571512
400 0.507414
600 0.471824
800 0.447585
...
9200 0.159066
9400 0.15656
9600 0.154132
9800 0.151778
10000 0.149496
Hypothesis: [[ 0.03074029]
[ 0.15884677]
[ 0.30486736]
[ 0.78138196]
[ 0.93957496]
[ 0.98016882]]
y 예측치
Correct (Y): [[ 0.]
[ 0.]
[ 0.]
[ 1.]
[ 1.]
[ 1.]]
y 예측치와 실제 y값의 차가 0.5 이상이면 0. 이하면 1
Accuracy: 1.0
예측정확도 100%
'''
'''
[당뇨병 예측]
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# Lab 5 Logistic Regression Classifier
import tensorflow as tf
import numpy as np
tf.set_random_seed(777) # for reproducibility
xy = np.loadtxt('data-03-diabetes.csv', delimiter=',', dtype=np.float32)
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
print(x_data.shape, y_data.shape)
# placeholders for a tensor that will be always fed.
X = tf.placeholder(tf.float32, shape=[None, 8])
Y = tf.placeholder(tf.float32, shape=[None, 1])
W = tf.Variable(tf.random_normal([8, 1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
# Hypothesis using sigmoid: tf.div(1., 1. + tf.exp(tf.matmul(X, W)))
hypothesis = tf.sigmoid(tf.matmul(X, W) + b)
# cost/loss function
cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) *
tf.log(1 - hypothesis))
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)
# Accuracy computation
# True if hypothesis>0.5 else False
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:
# Initialize TensorFlow variables
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)
# Accuracy report
h, c, a = sess.run([hypothesis, predicted, accuracy],
feed_dict={X: x_data, Y: y_data})
print("\nHypothesis: ", h, "\nCorrect (Y): ", c, "\nAccuracy: ", a)
'''
0 0.82794
200 0.755181
400 0.726355
600 0.705179
800 0.686631
...
9600 0.492056
9800 0.491396
10000 0.490767
...
[ 1.]
[ 1.]
[ 1.]]
Accuracy: 0.762846
[ 참고자료 ]
https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌/
http://agiantmind.tistory.com/176
https://www.tensorflow.org/install/
https://github.com/hunkim/deeplearningzerotoall
http://www.derivative-calculator.net/
http://terms.naver.com/entry.nhn?docId=3350391&cid=58247&categoryId=58247 ==> 미분계산/공식
http://matplotlib.org/users/installing.html ==>matplotlib 설치
https://www.kaggle.com/==> DATA SAMPLE 을 구할수 있는 사이트
'''
'프로젝트 > 인공지능' 카테고리의 다른 글
[python] python 문법정리 (0) | 2017.08.05 |
---|---|
[인공지능 #6 ] multinomial 적용 (0) | 2017.07.30 |
[인공지능 #4 ] 여러개의 DATA를 (X 변수) 구현 (0) | 2017.07.30 |
[인공지능 #3 ] Cost 최소화 알고리즘 구현 (0) | 2017.07.30 |
[인공지능 #2 ] Tensorflow Linear regression 구현 (0) | 2017.07.30 |
[인공지능 #4 ] 여러개의 DATA를 (X 변수) 구현
인공지능 구현에 대한 글입니다.
글의 순서는 아래와 같습니다.
================================================
1. X의 갯수가3개인 경우
==> 코딩이 매우 복잡해짐 , 대안으로 "매트릭스_행렬 "을 사용하면 간단해짐.
2. 매트릭스 적용
==> DATA 갯수(X 변수의갯수) 이 많아져도 간단하게 코딩이 가능해짐
3. TENSOR FLOW로 파일에서 DATA 읽어오기
==> DATA를 프로그램상에 올리면 메모리한계가 있으므로, DATA를 별도의 화일에 저장하고 불러오는것이 유리함
4. DATA QUE로 읽어들임 시간차로 처리해서 시스템 부하를 줄어줌
==> 화일이 많거나, 용량이 커지면 TENSORFLOW에서 자동으로 시간차를 두고 처리해주는 시스템 구현이 가능함
5. Next step
==> LOGISTICS 알고리즘 : CLASSSIFICATION 중 주요한 알고리즘.
6.참고자료
=================================================
[ Cost 최소화 알고리즘 구현 소스코드 분석 ]
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# Lab 4 Multi-variable linear regression
import tensorflow as tf
tf.set_random_seed(777) # for reproducibility
==> x값이 3개
x1_data = [73., 93., 89., 96., 73.]
x2_data = [80., 88., 91., 98., 66.]
x3_data = [75., 93., 90., 100., 70.]
y_data = [152., 185., 180., 196., 142.]
# placeholders for a tensor that will be always fed.
x1 = tf.placeholder(tf.float32)
x2 = tf.placeholder(tf.float32)
x3 = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
w1 = tf.Variable(tf.random_normal([1]), name='weight1')
w2 = tf.Variable(tf.random_normal([1]), name='weight2')
w3 = tf.Variable(tf.random_normal([1]), name='weight3')
b = tf.Variable(tf.random_normal([1]), name='bias')
hypothesis = x1 * w1 + x2 * w2 + x3 * w3 + b
print(hypothesis)
==> x,w값이 3개(x1,x2,x3 ,w1,w2,w3) 인 가설임
==> 코딩이 매우 복잡해짐 , 대안으로 "매트릭스_행렬 "을 사용하면 간단해짐.
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Minimize. Need a very small learning rate for this data set
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)
train = optimizer.minimize(cost)
# 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(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)
'''
0 Cost: 19614.8
Prediction:
[ 21.69748688 39.10213089 31.82624626 35.14236832 32.55316544]
10 Cost: 14.0682
Prediction:
[ 145.56100464 187.94958496 178.50236511 194.86721802 146.08096313]
...
1990 Cost: 4.9197
Prediction:
[ 148.15084839 186.88632202 179.6293335 195.81796265 144.46044922]
2000 Cost: 4.89449
Prediction:
[ 148.15931702 186.8805542 179.63194275 195.81971741 144.45298767]
'''
[ 매트릭스 적용 ]
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# Lab 4 Multi-variable linear regression
import tensorflow as tf
tf.set_random_seed(777) # for reproducibility
매트릭로 DATA 적용
x_data = [[73., 80., 75.],
[93., 88., 93.],
[89., 91., 90.],
[96., 98., 100.],
[73., 66., 70.]]
y_data = [[152.],
[185.],
[180.],
[196.],
[142.]]
# placeholders for a tensor that will be always fed.
X = tf.placeholder(tf.float32, shape=[None, 3])
Y = tf.placeholder(tf.float32, shape=[None, 1])
W = tf.Variable(tf.random_normal([3, 1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
매트릭스 곱샘 코딩
# Hypothesis
hypothesis = tf.matmul(X, W) + b
# Simplified cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Minimize
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)
train = optimizer.minimize(cost)
# 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(2001):
cost_val, hy_val, _ = sess.run(
[cost, hypothesis, train], feed_dict={X: x_data, Y: y_data})
if step % 10 == 0:
print(step, "Cost: ", cost_val, "\nPrediction:\n", hy_val)
'''
0 Cost: 7105.46
Prediction:
[[ 80.82241058]
[ 92.26364136]
[ 93.70250702]
[ 98.09217834]
[ 72.51759338]]
10 Cost: 5.89726
Prediction:
[[ 155.35159302]
[ 181.85691833]
[ 181.97254944]
[ 194.21760559]
[ 140.85707092]]
...
1990 Cost: 3.18588
Prediction:
[[ 154.36352539]
[ 182.94833374]
[ 181.85189819]
[ 194.35585022]
[ 142.03240967]]
2000 Cost: 3.1781
Prediction:
[[ 154.35881042]
[ 182.95147705]
[ 181.85035706]
[ 194.35533142]
[ 142.036026 ]]
'''
[ TENSOR FLOW로 파일에서 DATA 읽어오기 ]
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# Lab 4 Multi-variable linear regression
import tensorflow as tf
import numpy as np
tf.set_random_seed(777) # for reproducibility
DATA는 CSV 화일에 저장됨, CSV 화일 위치는 PY 화일위치에 있음
xy = np.loadtxt('data-01-test-score.csv', delimiter=',', dtype=np.float32)
슬라이싱방법 숙지필요함
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
# Make sure the shape and data are OK
print(x_data.shape, x_data, len(x_data))
print(y_data.shape, y_data)
# placeholders for a tensor that will be always fed.
X = tf.placeholder(tf.float32, shape=[None, 3])
Y = tf.placeholder(tf.float32, shape=[None, 1])
W = tf.Variable(tf.random_normal([3, 1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
# Hypothesis
hypothesis = tf.matmul(X, W) + b
# Simplified cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Minimize
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)
train = optimizer.minimize(cost)
# 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(2001):
cost_val, hy_val, _ = sess.run(
[cost, hypothesis, train], feed_dict={X: x_data, Y: y_data})
if step % 10 == 0:
print(step, "Cost: ", cost_val, "\nPrediction:\n", hy_val)
나의 점수 예측
# Ask my score
print("Your score will be ", sess.run(
hypothesis, feed_dict={X: [[100, 70, 101]]}))
print("Other scores will be ", sess.run(hypothesis,
feed_dict={X: [[60, 70, 110], [90, 100, 80]]}))
'''
타인의 점수 예측
Your score will be [[ 181.73277283]]
Other scores will be [[ 145.86265564]
[ 187.23129272]]
'''
[ DATA QUE로 읽어들임 시간차로 처리해서 시스템 부하를 줄어줌 ]
import tensorflow as tf
tf.set_random_seed(777) # for reproducibility
화일 하나를 위한 QUE를 만듦
filename_queue = tf.train.string_input_producer(
['data-01-test-score.csv'], shuffle=False, name='filename_queue')
화일 리더 정의
reader = tf.TextLineReader()
key, value = reader.read(filename_queue)
# Default values, in case of empty columns. Also specifies the type of the
# decoded result.
CSV로 디코딩
record_defaults = [[0.], [0.], [0.], [0.]]
xy = tf.decode_csv(value, record_defaults=record_defaults)
불러올때마다 10 개씩 불러옴 (BATCH_SIZE =10 )
# collect batches of csv in
train_x_batch, train_y_batch = \
tf.train.batch([xy[0:-1], xy[-1:]], batch_size=10)
# placeholders for a tensor that will be always fed.
X 3개 , Y 1개 데이터 숫자를 맞추어줌
X = tf.placeholder(tf.float32, shape=[None, 3])
Y = tf.placeholder(tf.float32, shape=[None, 1])
W = tf.Variable(tf.random_normal([3, 1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
# Hypothesis
hypothesis = tf.matmul(X, W) + b
# Simplified cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Minimize
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)
train = optimizer.minimize(cost)
# Launch the graph in a session.
sess = tf.Session()
# Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for step in range(2001):
x_batch , y_batch 값을 train feed_dict로 넘겨줌
x_batch, y_batch = sess.run([train_x_batch, train_y_batch])
cost_val, hy_val, _ = sess.run(
[cost, hypothesis, train], feed_dict={X: x_batch, Y: y_batch})
if step % 10 == 0:
print(step, "Cost: ", cost_val, "\nPrediction:\n", hy_val)
coord.request_stop()
coord.join(threads)
# Ask my score
print("Your score will be ",
sess.run(hypothesis, feed_dict={X: [[100, 70, 101]]}))
print("Other scores will be ",
sess.run(hypothesis, feed_dict={X: [[60, 70, 110], [90, 100, 80]]}))
'''
Your score will be [[ 177.78144836]]
Other scores will be [[ 141.10997009]
[ 191.17378235]]
'''
[참고자료 ]
https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌/
http://agiantmind.tistory.com/176
https://www.tensorflow.org/install/
https://github.com/hunkim/deeplearningzerotoall
http://www.derivative-calculator.net/
http://terms.naver.com/entry.nhn?docId=3350391&cid=58247&categoryId=58247 ==> 미분계산/공식
http://matplotlib.org/users/installing.html ==>matplotlib 설치
'프로젝트 > 인공지능' 카테고리의 다른 글
[인공지능 #6 ] multinomial 적용 (0) | 2017.07.30 |
---|---|
[인공지능 #5 ] Logistics classification 가설함수 (0) | 2017.07.30 |
[인공지능 #3 ] Cost 최소화 알고리즘 구현 (0) | 2017.07.30 |
[인공지능 #2 ] Tensorflow Linear regression 구현 (0) | 2017.07.30 |
[인공지능 #1 ] Tensorflow를 실행하기 위한 사전준비 (0) | 2017.07.29 |
[인공지능 #3 ] Cost 최소화 알고리즘 구현
인공지능 구현에 대한 글입니다.
글의 순서는 아래와 같습니다.
================================================
1. Cost 최소화 알고리즘 구현 소스코드 분석
2. Cost Minimize 코딩 작성 ( cost 를 미분해서 W변화량 적용)
3. Optimizer 적용 테스트
- 간단한 미분은 상기과 같이 직접코딩이 가능하겠으나, 복잡해지면 통상적으로 optimizer로 코딩함
4. Optimizer 적용 과 수작업(미분계산) 수치 비교
- 경사도 수치를 중간에 변형할수 있도록 코딩함 (gvs) ==> 거의 같음
5. Next step
==> multivariable linear regresstion : 하나이상의 변수적용
6. 참고자료
=================================================
[ Cost 최소화 알고리즘 구현 소스코드 분석 ]
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# Lab 3 Minimizing Cost
import tensorflow as tf
import matplotlib.pyplot as plt
==> matplotlib를 사용키 위해서는 별도로 설치를 해야함
==> http://matplotlib.org/users/installing.html
==> 그래프를 그려주는 기능임.
tf.set_random_seed(777) # for reproducibility
X = [1, 2, 3]
Y = [1, 2, 3]
W = 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()
# Variables for plotting cost function
W_history = []
cost_history = []
==> 그래프를 그리기 위해 배열할당
for i in range(-30, 50):
curr_W = i * 0.1
curr_cost = sess.run(cost, feed_dict={W: curr_W})
W_history.append(curr_W)
cost_history.append(curr_cost)
# Show the cost function
plt.plot(W_history, cost_history)
plt.show()
[ Cost Minimize 코딩 작성 ( cost 를 미분해서 W변화량 적용) ]
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# Lab 3 Minimizing Cost
import tensorflow as tf
tf.set_random_seed(777) # for reproducibility
x_data = [1, 2, 3]
y_data = [1, 2, 3]
# 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
W = tf.Variable(tf.random_normal([1]), name='weight')
X = tf.placeholder(tf.float32)
Y = 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))
W값의 descent 간격을 구하는 과정을 미분방정식으로 직접(수작업) 코딩하는 내용입니다( 아래그림은 미분적용 과정입니다)
# Minimize: Gradient Descent using derivative: W -= learning_rate * derivative
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 1.93919 [ 1.64462376]
1 0.551591 [ 1.34379935]
2 0.156897 [ 1.18335962]
3 0.0446285 [ 1.09779179]
4 0.0126943 [ 1.05215561]
5 0.00361082 [ 1.0278163]
6 0.00102708 [ 1.01483536]
7 0.000292144 [ 1.00791216]
8 8.30968e-05 [ 1.00421977]
9 2.36361e-05 [ 1.00225055]
10 6.72385e-06 [ 1.00120032]
11 1.91239e-06 [ 1.00064015]
12 5.43968e-07 [ 1.00034142]
13 1.54591e-07 [ 1.00018203]
14 4.39416e-08 [ 1.00009704]
15 1.24913e-08 [ 1.00005174]
16 3.5322e-09 [ 1.00002754]
17 9.99824e-10 [ 1.00001466]
18 2.88878e-10 [ 1.00000787]
19 8.02487e-11 [ 1.00000417]
20 2.34053e-11 [ 1.00000226]
'''
[ Optimizer 적용 테스트 ]
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Lab 3 Minimizing Cost import tensorflow as tf tf.set_random_seed(777) # for reproducibility # tf Graph Input X = [1, 2, 3] Y = [1, 2, 3] # Set wrong model weights W = tf.Variable(5.0) ==> w 값을 터무니없는 값을 주고, 적정한 값을 찾아가는지 테스트함 # Linear model hypothesis = X * W # cost/loss function cost = tf.reduce_mean(tf.square(hypothesis - Y)) # Minimize: Gradient Descent Magic optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1) train = optimizer.minimize(cost) # 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(100): print(step, sess.run(W)) sess.run(train) ''' 0 5.0 1 1.26667 2 1.01778 3 1.00119 4 1.00008 ... 96 1.0 97 1.0 98 1.0 99 1.0 '''
[ Optimizer 적용 과 수작업(미분계산) 수치 비교]
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# Lab 3 Minimizing Cost
# This is optional
import tensorflow as tf
tf.set_random_seed(777) # for reproducibility
# tf Graph Input
X = [1, 2, 3]
Y = [1, 2, 3]
# Set wrong model weights
W = tf.Variable(5.)
# Linear model
hypothesis = X * W
# Manual gradient
gradient = tf.reduce_mean((W * X - Y) * X) * 2
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Minimize: Gradient Descent Magic
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimizer.minimize(cost)
# Get gradients
gvs = optimizer.compute_gradients(cost, [W])
# Optional: modify gradient if necessary
# gvs = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gvs]
==> gvc 수치를 필요에 따라서 변형적용이 가능함
# Apply gradients
apply_gradients = optimizer.apply_gradients(gvs)
# 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(100):
print(step, sess.run([gradient, W, gvs]))
sess.run(apply_gradients)
# Same as sess.run(train)
'''
# Apply gradients
0 [37.333332, 5.0, [(37.333336, 5.0)]]
1 [33.848888, 4.6266665, [(33.848888, 4.6266665)]]
2 [30.689657, 4.2881775, [(30.689657, 4.2881775)]]
3 [27.825287, 3.9812808, [(27.825287, 3.9812808)]]
4 [25.228262, 3.703028, [(25.228264, 3.703028)]]
...
96 [0.0030694802, 1.0003289, [(0.0030694804, 1.0003289)]]
97 [0.0027837753, 1.0002983, [(0.0027837753, 1.0002983)]]
98 [0.0025234222, 1.0002704, [(0.0025234222, 1.0002704)]]
99 [0.0022875469, 1.0002451, [(0.0022875469, 1.0002451)]]
'''
[ 참고자료 ]
https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌/
http://agiantmind.tistory.com/176
https://www.tensorflow.org/install/
https://github.com/hunkim/deeplearningzerotoall
http://www.derivative-calculator.net/
http://terms.naver.com/entry.nhn?docId=3350391&cid=58247&categoryId=58247 ==> 미분계산/공식
http://matplotlib.org/users/installing.html ==>matplotlib 설치
'프로젝트 > 인공지능' 카테고리의 다른 글
[인공지능 #6 ] multinomial 적용 (0) | 2017.07.30 |
---|---|
[인공지능 #5 ] Logistics classification 가설함수 (0) | 2017.07.30 |
[인공지능 #4 ] 여러개의 DATA를 (X 변수) 구현 (0) | 2017.07.30 |
[인공지능 #2 ] Tensorflow Linear regression 구현 (0) | 2017.07.30 |
[인공지능 #1 ] Tensorflow를 실행하기 위한 사전준비 (0) | 2017.07.29 |