TechTogetWorld

 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid


인공지능 구현에 대한 글입니다.

글의 순서는 아래와 같습니다.


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

1. Tensorflow  Linear regression 소스코드 설명

2. placeholders 적용

  ==> data x,y를 미리 주지않고, 빈공간으로 그래프를 구성하고, 나중에 실행단계에서 숫자를 입력하는 방식임

  ==> 모델을 만들어 놓고, 나중에 data를 넘겨줄수 있음. 

3. Next step

  ==> cost 최소화 알고리즘 상세분석

4. 참고자료

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

[Tensorflow Linear regression 소스코드 설명 ]


1. 라이브러리 IMPORT import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Lab 2 Linear Regression import tensorflow as tf tf.set_random_seed(777) # for reproducibility

2. DATA 할당


# X and Y data x_train = [1, 2, 3] y_train = [1, 2, 3] # Try to find values for W and b to compute y_data = x_data * W + b # We know that W should be 1 and b should be 0 # But let TensorFlow figure it out


3. 변수선언
W = tf.Variable(tf.random_normal([1]), name='weight') b = tf.Variable(tf.random_normal([1]), name='bias')

# Our hypothesis XW+b


4. 가설 : X에 값에 따라 선형으로 변화하는 Y값의 관계를 직선의 공식으로 표현하고, 이를 파이선 문법으로 작성함



hypothesis = x_train * W + b



5. COST 함수 : 가설값과 실제 Y값의 차이를 최소화 하는 W를 찾는 함수



# cost/loss function cost = tf.reduce_mean(tf.square(hypothesis - y_train))



6. Gradient Descent : W 값을 기울기(미분값)*알파 값만큼 이동시키면서, COST 최소값을 찾아가는 함수

# Minimize optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01) train = optimizer.minimize(cost) # Launch the graph in a session.


7. SESSION 선언 : 텐서플로우 노드를 실행하기 위해서는 SESSION선언후 실행이 가능함

sess = tf.Session() # Initializes global variables in the graph.


8. 실행

sess.run(tf.global_variables_initializer())

- 변수를 실행하기 위해서는 글로벌 로 초기화를 해주어야 함. # Fit the line for step in range(2001): sess.run(train) ==> Train을 실행하면, 하위단의 cost , hypathsis , w ,b 등이 따라서 실행이 되는 구조임 if step % 20 == 0: print(step, sess.run(cost), sess.run(W), sess.run(b)) # Learns best fit W:[ 1.], b:[ 0.]


9. 실행결과

- STEP이 진행될수록 Cost값 ( 실제값과 가설값의 차이 ) 가 작아지는 방향으로 W 값과 , B 값을 을 찾아가고 있음을 알수있음

- 여기서는 w값이 1에 수렴하고 , b는 0에 수렴하는것으로 보여집니다.

- 즉

X 1,2,3 / Y 1,2,3 을 가장 잘 나타내는 식은

H(X)=1*X+0 임을 알수있습니다. 0를 지나는 기울기 1인이 직선이 DATA를 나타내는 최적의 선 임을 알수있음


''' 0 2.82329 [ 2.12867713] [-0.85235667] 20 0.190351 [ 1.53392804] [-1.05059612] 40 0.151357 [ 1.45725465] [-1.02391243] ... 1920 1.77484e-05 [ 1.00489295] [-0.01112291] 1940 1.61197e-05 [ 1.00466311] [-0.01060018] 1960 1.46397e-05 [ 1.004444] [-0.01010205] 1980 1.32962e-05 [ 1.00423515] [-0.00962736] 2000 1.20761e-05 [ 1.00403607] [-0.00917497]


'''



[ placeholders 적용 ]

import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Lab 2 Linear Regression import tensorflow as tf tf.set_random_seed(777) # for reproducibility # 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') b = tf.Variable(tf.random_normal([1]), name='bias') # Now we can use X and Y in place of x_data and y_data # # placeholders for a tensor that will be always fed using feed_dict # See http://stackoverflow.com/questions/36693740/
X = tf.placeholder(tf.float32, shape=[None]) Y = tf.placeholder(tf.float32, shape=[None]) ==> data x,y를 미리 주지않고, 빈공간으로 그래프를 구성하고, 나중에 실행단계에서 숫자를 입력하는 방식임
# Our hypothesis XW+b hypothesis = X * W + b # cost/loss function cost = tf.reduce_mean(tf.square(hypothesis - Y)) # Minimize optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01) 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()) # Fit the line for step in range(2001): cost_val, W_val, b_val, _ = \ sess.run([cost, W, b, train], feed_dict={X: [1, 2, 3], Y: [1, 2, 3]})
==> cost , w, b 실행을 한번에 명령을 줄수있음
==> cost data x,y를 여기서 주어줌 if step % 20 == 0: print(step, cost_val, W_val, b_val) # Learns best fit W:[ 1.], b:[ 0] ''' ... 1980 1.32962e-05 [ 1.00423515] [-0.00962736] 2000 1.20761e-05 [ 1.00403607] [-0.00917497] ''' # Testing our model print(sess.run(hypothesis, feed_dict={X: [5]})) print(sess.run(hypothesis, feed_dict={X: [2.5]})) print(sess.run(hypothesis, feed_dict={X: [1.5, 3.5]})) ''' [ 5.0110054] [ 2.50091505] [ 1.49687922 3.50495124] ''' # Fit the line with new training data for step in range(2001): cost_val, W_val, b_val, _ = \ sess.run([cost, W, b, train], feed_dict={X: [1, 2, 3, 4, 5], Y: [2.1, 3.1, 4.1, 5.1, 6.1]})
==> shape를 none으로 했기때문에,data 갯수는 필요한 만큼 줄수있음 if step % 20 == 0: print(step, cost_val, W_val, b_val) # Testing our model print(sess.run(hypothesis, feed_dict={X: [5]})) print(sess.run(hypothesis, feed_dict={X: [2.5]})) print(sess.run(hypothesis, feed_dict={X: [1.5, 3.5]}))

==> 학습이 완료된 hypothis 함수에 X값을 주고, Y값을 예측하는 과정임
''' 1960 3.32396e-07 [ 1.00037301] [ 1.09865296] 1980 2.90429e-07 [ 1.00034881] [ 1.09874094] 2000 2.5373e-07 [ 1.00032604] [ 1.09882331] [ 6.10045338] [ 3.59963846] [ 2.59931231 4.59996414]
"""

[참고자료 ]


https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌/ 

http://agiantmind.tistory.com/176 

https://www.tensorflow.org/install/

https://github.com/hunkim/deeplearningzerotoall

 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid


인공지능 구현에 대한 글입니다.

글의 순서는 아래와 같습니다.


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

1. 프로그램 설치하기

2. 강의 소스코드 저장위치

3. 예제코드 실행 ( hellow tensorflow ! )

4. Nextstep

  - 코딩 실습

5. 참고자료

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

[프로그램 설치하기]


1. 참고자료 ==>설치매뉴얼  http://agiantmind.tistory.com/176   ==> window10 매뉴얼이지만, WIN7에 설치해도 잘 잘동함.

2. Anaconda  TensorFlow   /  PyCharm 설치

     (참조) https://www.tensorflow.org/install/

  (1). Anaconda 설치

         Anaconda Download    ==>  Python 3.6  64-bit를 설치 

  (2) TensorFlow 설치

     [1] 시작프로그램 -> Anaconda Prompt 실행 ==> 관리자권한으로 실행

     [2]TensorFlow를 위한 환경 생성 (Python 3.5 버전으로 설치)

          C:>conda create -n TensorFlow python=3.5

     [3]TensorFlow 활성화

          C:>activate TensorFlow

          (TensorFlow) C:>  ==> 프롬프트 변경됨

     [4]PIP를 통해 TensorFlow 설치

         . CPU only version : (TensorFlow) C:>pip install tensorflow

         . GPU version : (TensorFlow) C:>pip install tensorflow-gpu   ==> NVIDIA 그래픽 카드 이용실 설치/별도 추가 TOOL 설치/가입 필요함

   (3)PyCharm 설치 및 환경 구성

      [1] PyCharm 다운/설치 (Community 버전 다운)

           PyCharm Download 

      [2] Create New Project 눌러 새로운 프로젝트 생성

      [3] 프로젝트 저장 위치 선택 후 Interpreter 항목에서 TensorFlow 설치된 환경의 Python 선택 필요

         interpreter 우측 톱니를 클릭하고 , ADD LOCAL 를 클릭해서 아래 화일을 선택함

          c:\users\dhp\anaconda3\envs\Tensorflow\python.exe

      [4] Project에 New --> Python File ==>코딩시행 ( hellow tensorflow! 출력하는 코딩입니다 )

       import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
sess = tf.Session()
hello = tf.constant('Hello, TensorFlow')
print(sess.run(hello))
print(str(sess.run(hello), encoding='utf-8')) # unicode --> utf-8


[ 강좌의 강의코드 저장위치]

    https://github.com/hunkim/deeplearningzerotoall



[Nextstep]

  - 코딩실습


[참고자료]

https://www.inflearn.com/course/기본적인-머신러닝-딥러닝-강좌/ 

http://agiantmind.tistory.com/176 

https://www.tensorflow.org/install/

https://github.com/hunkim/deeplearningzerotoall