모두를 위한 딥러닝 Lec02

2021. 5. 12. 23:06IT 공부/ML

※ 본 카테고리의 글은 홍콩과기대 김성훈 교수님의 "Basic Machine/Deep Learning with TensorFlow(Python) 강의를 바탕으로 공부하되, TensorFlow2 환경에서 정리한 바를 기록하고 있습니다.

강의 웹사이트: http://hunkim.github.io/ml/

유튜브 : youtu.be/BS6O0zOGX4E


 

- 텐서플로우(TensorFlow)란?

  : data flow graphs를 사용하여 numerical computation을 하는 오픈소스 라이브러리다. 

 

- Data Flow Graph 란?

  : 노드와 노드가 엣지로 연결되어 있는 것, ○─○의 형태를 갖는다. 

    노드는 하나의 (수학적) operation

    엣지는 데이터(multidimensional data arrays)이며 tensor라고도 부름

 

- 텐서플로우1에서 텐서플로우2로의 주요 변경사항 참고

http://solarisailab.com/archives/2640

 


- 텐서플로우 설치하기

   : 그램 노트북에 NVIDIA가 아닌 Intel 그래픽 카드가 내장되어 있어서 cpu 버전으로 설치했다. 

(참고) - 전체 과정 확인

https://kyoko0825.tistory.com/entry/윈10-아나콘다를-이용한-텐서플로우-CPU-버전-설치

(참고) - cpu 버전 설치를 위한 명령어 확인

https://copycoding.tistory.com/341

 

1) Anaconda prompt 실행 후 최신 버전으로 업데이트

conda update -n base conda
// done
conda update --all
// done

 

2) 아나콘다 가상환경 생성

conda create -n tensorflow_cpu python=3.8
// done
// #
// # To activate this environment, use
// #
// #     $ conda activate tensorflow_cpu
// #
// # To deactivate an active environment, use
// #
// #     $ conda deactivate

 

3) 가상환경을 활성화

activate tensorflow_cpu
// (tensorflow_cpu) C:\Users\기본경로>

 

4) pip를 최신버전으로 업데이트

python -m pip install --upgrade pip
// Successfully installed pip-21.1.1

 

5) tensorflow(CPU버전) 설치

pip install --ignore-installed --upgrade tensorflow-cpu

 

6) 파이썬 기타 라이브러리 설치

pip install numpy matplotlib pandas pillow graphviz

 

7) 텐서플로우 설치 확인

(tensorflow_cpu) C:\WINDOWS\system32>python
// Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
// Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> tf.__version__
// '2.4.1'

 


 

- 주피터 노트북 환경설정

 

1) 주피터노트북에서 기본경로가 될 폴더 생성

(참고) - 주피터노트북에서 기본 경로 변경하는 과정

https://ooyoung.tistory.com/7

 

2) 아나콘다 파워셸 프롬프트(Anaconda Powershell Prompt) 실행 

 

3) 환경설정 파일이 위치한 경로를 확인

jupyter notebook --generate-config
// Writing default config to: C:\Users\내컴퓨터이름\.jupyter\jupyter_notebook_config.py

 

4) 관리자권한으로 메모장 실행 후 환경설정 파일 열기

 

5) # c:NotebookApp.notebook_dir = '' 라고 쓰여진 부분을 찾아 #는 지우고 '' 안에 원하는 경로를 입력

c.NotebookApp.notebook_dir = 'C:\Tensorflow'

 

6) 바로가기의 속성창에서 "%USERPROFILE%/" 과 %HOMEPATH% 을 삭제 후 확인

 

7) 주피터노트북(새로설치됨) 실행

 

8) 새로 설정한 기본 경로에 알맞은 폴더 구조가 나오는지 확인

 


 

- 주피터 노트북에서 텐서플로우 문자열 출력하기

 

1) "Hello, TensorFlow!" 문자열을 가지는 Tensor(다차원배열)가 생성됨

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

print(hello)
// tf.Tensor(b'Hello, TensorFlow!', shape=(), dtype=string)

 

2) Tensor값에 접근하기 위해 numpy 형태로 변환하여 출력

print(hello.numpy())
// b'Hello, TensorFlow!'

 

3) Tensor 클래스 변환 (bytes → str)

print(hello.numpy().decode("utf-8"))
// Hello, TensorFlow!

 


 

- 주피터 노트북에서 텐서플로우 Computational graph

 

1) TensorFlow operation을 사용하여 graph(tensor)를 build

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

node3 = tf.add(node1, node2)  # 또는 
node3 = node1 + node2

 

2) graph를 실행하고 변수를 업데이트하여 결과를 return

print("node1:", node1, "node2:", node2)
print("node3:", node3)
// node1: tf.Tensor(3.0, shape=(), dtype=float32) node2: tf.Tensor(4.0, shape=(), dtype=float32)
// node3: tf.Tensor(7.0, shape=(), dtype=float32)

print("node1:", node1.numpy(), "node2:", node2.numpy())
print("node3:", node3.numpy())
// node1: 3.0 node2: 4.0
// node3: 7.0

 


- 텐서플로우에서의 placeholder, function (함수)

(참고) - session과 placeholder가 어떻게 변경되었는지 

https://eclipse360.tistory.com/40

 

placeholder는 값이 지정되지 않은 tensor를 생성하고 나중에 값을 입력받는다.
→ 텐서플로우2에서는 placeholder가 삭제되었다.

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

adder_node = a + b

print(sess.run(adder_node, feed_dict={a: 3, b:5}))
// 실행해도 에러가 발생한다. 

 

1) @tf.function을 사용하여 함수를 정의하고 값을 나중에 입력받는다.

@tf.function
def adder_node(a,b):
    return a + b
    
A = tf.constant(3)
B = tf.constant(5)
print(adder_node(A, B).numpy())
// 8

C = tf.constant([[1,2,3], [4,5,6]])
D = tf.constant([[2,3,4], [5,6,7]])
print(adder_node(C, D).numpy())
// [[ 3  5  7]
//  [ 9 11 13]]

 


- Tensor, Rank, Shape, Type

  Datas   Ranks   Shapes   Types
  3   rank 0 tensor   [ ]   scalar
  [1., 2., 3.]   rank 1 tensor   [3]   vector
  [[1., 2., 3.], [4., 5., 6.]]   rank 2 tensor   [2, 3]   matrix
  [[[1., 2., 3.]], [[7., 8., 9.]]]   rank 3 tensor   [2, 1, 3]   3-Tensor

 

 

반응형

'IT 공부 > ML' 카테고리의 다른 글

모두를 위한 딥러닝 Lec00~Lec01  (0) 2021.05.11