ML lab 01 - TensorFlow의 설치및 기본적인 operations (new) 

강의를 보고, 실습을 한번 해보겠다. 

https://www.youtube.com/watch?v=-57Ne86Ia8w&feature=youtu.be

그래프 빌드

>>> import tensorflow as tf
>>> node1 = tf.constant(3.0, tf.float32)
>>> node2 = tf.constant(4.0)
>>> node3 = tf.add(node1, node2)

먼저 import tensorflow as tf 란 tensorflow란 이름이 길어서 tf라는 이름으로 쓴다는 말.

 

이게 tensorflow 1.0버전에서는 가능한데

tensorflow 2.2 버전에서 사용하려면 

 

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

을 사용하면 Session사용이 가능하다. 

 

 

>>> print("node1:", node1, "node2: ", node2)
node1: Tensor("Const_1:0", shape=(), dtype=float32) node2:  Tensor("Const_2:0", shape=(), dtype=float32)



>>> print("node3: ",node3)
node3:  Tensor("Add:0", shape=(), dtype=float32)

그 다음 노드를 출력해주는데 이게 신기하게도 tensro의 값이 나오지 않고

그래프의 (Tensor)라고 만 말해줌

 

그래프의 값을 출력하기 위해서는

Session을 사용해야 한다. 

 

sess = tf.Session()

해줘야 하는데 오류가 난다. 

 

>>> sess = tf.Session()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute 'Session'

 

 

구글링 결과

sess = tf.compat.v1.Session()

이걸 사용해줘야 한다. 

위에서 사용은 했지만 왜인지 몰라도 또 해줘야 한다. 

 

버전이 달라서 문제였었다. 

 

>>> sess = tf.compat.v1.Session()

>>> print("sess.run(node1, node2): ", sess.run([node1, node2]))
sess.run(node1, node2):  [3.0, 4.0]

>>> print("sess.run(node3): ", sess.run(node3))
sess.run(node3):  7.0

바꿔 주니깐

답이 나왔다

 

sess.run()이 그래프를 실행 시켜주고

괄호 안에 실행시켜주고싶은 노들를 넣는다. 

 

 

 

 

텐서플로우 구조

1. 그래프를 빌드

     node1 = ...

     node2 = ...

     node3 = ....

 

2. sess.run( ) 그래프 실행

    sess.run([node1, node2])

 

3. 값 리턴

   

 

 

 

실행 시켜주는 단계에서 값 던져주고 싶을 때, 

 

1. 노드를 placeholder로 만들어 준다

2. 노드 두개를 이용해서 adder_node를 만들어줌

3. session 만들고 실행

 

 

>>> a = tf.placeholder(tf.float32)
>>> b = tf.olaceholder(tf.float32)

해주는데 또 

 

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute 'placeholder'

 

오류가 났다. 

 

다시

>>> import tensorflow.compat.v1 as tf

해주니깐 됐다. 

 

 

텐서플로우 입장에서는 값을 출력하고 싶은데 몰라서

feed_dict를 이용해서 값을 넘겨준다. 

 

값을 주면서 실행 시켜라 ,

>>> adder_node = a+b
>>> print(sess.run(adder_node, feed_dict = {a: 3, b: 4.5}))
7.5
>>> print(sess.run(adder_node, feed_dict = {a: [1,3], b: [2,4]}))
[3. 7.]

n개의 값을 넘겨 줄 수도 있다. 

 

 

이런 식이 된다. 

 [ ( 1+2 ), ( 3 + 4 ) ]

 

 

1. 그래프 정의

 placeholder 만들기 가능

2. 실행 시킬 때, feed_dict로 값을 넣어줌 

  feed_dict = {a: ...}

3. 출력값 리턴해주거나, 값 update를 한다. 

 

 

 

Tensor

- array같이 보면 된다. 

-> Ranks (몇 차원 array이냐)

->Shapes (몇 개씩 들어 있느냐)

    t = [[1,2,3] , [4,5,6], [7,8,9]]

    [3,3]

 

-> Types

 

 

 

 

+ Recent posts