출처 : http://hunkim.github.io/ml/


ML lec 02 - Linear Regression의 Hypothesis 와 cost 설명 


Regression ?


- 0 ~ 100 같은 일정 범위 내의 정확한 수치를 예측할 때 사용되는 개념.

- 위 그림과 같은 데이터를 학습하고 입력 값으로 7시간이 들어오면 대략 65점 정도가 나오겠다고 예측 하는것 



Linear Regression ? 


- Linear한 모델이 우리가 가지고 있는 Data에 맞을 거라고 가설을 세우고 시작 하는게 Linear Regression 

Ex > 공부 양이 올라가면 성적도 올라간다.

> 선형으로 설명할 수 있는 현상들이 많다. 


- 데이터들을 모두 포함하는 Linear한 선(모델)을 찾는 것이다.


Hypothesis 


- H(x) : 모델 or hypothesis or 가설 

  W, b : 이 두 값에 의해서 '선'이 결정된다.

- 어떤 선이 가장 좋은지 찾고 그 선의 W와 b 값을 저장함 



Which hypothesis is better ? 




- 실제 Data와 hypothesis 사이의 거리가 좁을 수록 좋다.

-> 이 거리를 계산하기 위한 function 

: Cost function(Loss function)   # 우리가 세운 가설이 실제 데이터와 얼마나 다르늬? 


: 제곱을 하므로써 거리가 멀 수록 더 큰 패널티를 가진다. 


위 식을 모든 데이터에 적용을 하면?~ 



다시 한번 써보면?~



- 위 Cost 함수가 작게 나오는것이 관건인데 

Cost가 가장 작은 값이 나오도록 하는 W와 b를 구하는게 Linear Regression의 학습 


마무리! 




출처

http://hunkim.github.io/ml/

https://github.com/hunkim/DeepLearningZeroToAll/

http://daeson.tistory.com/252

https://www.tensorflow.org/


ML lec 01_TensorFlow 의 설치 및 기본적인 operation



TensorFlow ?


- 구글에서 만든 오픈소스 라이브러리 (machine intelligence)

- 텐서플로우 외에도 상당히 많다. 

- 머신러닝을 위한 프레임워크들에 점수를 매겨 순위를 정한것 


- Tensorflow is an open source software library for numerical computation using data flow graphs

- Python을 이용해 TensorFlow 사용 가능 


What is a Data Flow Graph ?



- 위 그림에서 동그라미 그림을 노드라 하고 선을 엣지라 한다. 

> 노드 : 일종의 mathematical operations 

> 엣지 : 일종의 data array (tensors)


- 이런 형태를 거치며 데이터에 대한 연산을 처리하고 원하는 결과를 얻거나 작업을 할 수 있다.


설치 방법은 패쓰~ 


- OS마다 다르고 버전마다 다르다 인터넷 검색하면 다 나와있다.

- 만약 우분투 활경에서 GPU를 이용한 환경을 구현 할거면 아래 주소 참고 

http://kimtaeh.tistory.com/19

http://kimtaeh.tistory.com/20?category=682301 

 

Check install and version 


C:\Users\th_k9>python
Python 3.6.2 |Anaconda custom (64-bit) | (default, Sep 19 2017, 08:03:39( [MSC v. 1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> tf.__version__
'1.2.1'
>>>

- import tensorflow as tf 

> as tf 안하면 : tensorflow.__version__

> as tf 하면 : tf.__version__



TensorFlow Hello World! 


# Create a constant op
# This op is added as a node to the default graph 
hello = tf.constant("Hello, TensorFlow!")

# seart a TF session
sess = tf.Session()

# run the op and get result 
print(sess.run(hello))


! tf.constant() 


- constant(

value,

dtype=None,

shape=None,

name='Const'

verify_shape=False

  )


- For example: 


# Constant 1-D Tensor populated with value list.  (populated with : 채워지는)
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7])     => [1 2 3 4 5 6 7]

# Constant 2-D Tensor populated with scalar value -1.
tensor = tf.constant(-1.0, shape=[2, 3])     => [[-1. -1. -1.]
                                                 [-1. -1. -1.]]


- Args:

> value : A constant value (or list) of output type

> dtype : The type of the elements of the resulting tensor

> shape : Optional dimensions of resulting tensor

> name : Optional name for the tensor

> verify_shape : Boolean that enables verification of a shape of values


- Return:

A Constant Tensor 


! tf.Session()


- A class for running TensorFlow operations

- Session 여는 3 가지 방법 1.기본 2.with구문 3.장치선ㅌ액

1. 기본 

- 위에 있는 Hello TensorFlow 예시

- 마지막 sess.close() 추가해서 Session 객체를 닫아주어야 함 


2. with 구문 

import tensorflow as tf

hello = tf.constant("Hello, TensorFlow!")

with tf.Session() as sess:
    print(sess.run(hello))

- with 구문을 사용하면 자동으로 Close 됨 


3. 장치선택 

import tensorflow as tf

hello = tf.constant("Hello, TensorFlow!")

with tf.Session() as sess:
    with tf.device("/cpu:0"):
    #with tf.device("/gpu:0"):
        print(sess.run(hello))


4. tf.InteractiveSession() 이라는 것도 있는데 음.. 모르게쒀요 필요할때 알아봐야지


! tf.Session().run()


- run(

 fetches,

 feed_dict = None,

 options = None,

 run_metadata = None

 )


- Args:

>fetches : A single graph element, a list of graph elements, or a dictionary whose values are graph elements or lists of graph elements

> feed_dict : A dictionary that maps graph elements to values

> options : A [RunOptions] protocol buffer

> run_metadata : A [Runmetadata] protocol buffer 



Computational Graph 


node1 = tf.constant(3.0, tf.float32)
node2 = tf.constant(4.0)  #also tf.float32 implicitly 
node3 = tf.add(node1, node2) 

# Build graph (tensors) using TensorFlow operations 

print("node1:", node1, "node2", node2) 
print("node3:", node3) 

#----------result------------
node1 : Tensor("Const:0", shape=(), dtype=float32)  node2: Tensor("Const_1:0", shape=(), dtype=float32)
node3 : Tensor("Add:0", shape(), dtype(float32)

- Tensor인걸 알려주며 어떤 정보를 담고 있는지 알려줌 

- 그래프의 노드 확인 용으로 사용 가능 


- Session 열어주고 sess.run()하면 들어있는 값이 나옴 



TensorFlow의 작동 과정 



Placeholder 


- 걍 변수임 

- placeholder(

 dtype,

 shape = None,

 name = None

 )

a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a + b

with tf.Session() as sess:
    print(sess.run(adder_node, feed_dict={a : 3, b : 4.5}))
    print(sess.run(adder_node, feed_dict={a : [1, 3], b : [2, 4]}))

#-------------result-------------
7.5
[ 3. 7. ]



Tensor ? 


- 기본적으로 Array를 의미함 


- Tensor Ranks, Shapes, and Types 


> Ranks : 차원을 의미 


> Shapes : 각 차원에 몇 개의 element가 들어가 있는지 


> Type 



다음 실습은 Linear Regression 구현~ 

홍콩 과기대 김성훈 교수님

출처 : http://hunkim.github.io/ml/


- 이세돌과 알파고의 대국

 


  - 바둑은 경우의 수가 너무 많아서 컴퓨터가 계산할 수 없는 영역이었다.

  - 4 : 1로 짐

  - 이 때부터 컴퓨터 과학 분야를 모르는 사람도 인공지능에 관심을 가지기 시작 (나도 포함)


- Dr.Andrew Ng

  


  - 머신 러닝을 잘 이해하고 잘 활용하는 것이 슈퍼 파워를 가지는 힘

  - 이 슈퍼파워를 가지자고 강의를 만들어 주심


- 이 강의의 대상

  - 이세돌과 알파고의 대국을 보고 머신러닝이 뭘까? 라는 궁금증을 가지게된 기본 지식이 없던 사람도 들을 수 있는 강의

  - 수학을 잘 못하는 사람, 컴퓨터를 전공하지 않은 사람들도 충분힣 이해할 수 있는 수준

    - y = Wx + b 정도의 수학만 나옴

  - Tensorflow와 Python을 활용해 머신러닝을 구현해보고 싶은사람


- 이 강의의 목표

  - 머신러닝에 대한 기본적인 이해

    - Linear regression, Lopgistic regression (classification)

    - Neural networks, Convolutional Neural Network, Recurrent neural Network

  - 위 개념들을 사용해서 자신이 갖고있는 문제를 머신러닝을 이용해 해결

    - Tensorflow와 Python


- 강의 형식

  - 10분 내외의 개념 설명

  - Tensorflow를 활용한 프로그래밍 튜토리얼


- 대략적인 스케쥴

  - 머신러닝이 무엇인가?(컨셉)

  - Linear regression  # 기본적이지만 아주 중요

  - Logistic regression (classification)   # 기본적이지만 아주 종요

  - Multivariable (Vector) linear/logistic regression

  - Neural networks

  - Deep Learning

    - CNN

    - RNN

    - Bidirectional Neural Network


- 다음 강의

  - ML basic concepts

+ Recent posts