머신러닝

본문 바로가기
사이트 내 전체검색


머신러닝
머신러닝

6. TensorFlow

페이지 정보

작성자 관리자 댓글 2건 조회 4,810회 작성일 20-02-23 14:18

본문

6. TensorFlow

TensorFlow 

구글이 오픈소스로 공개한 머시러닝 라이브러리

- 딥러닝을 비롯한 여러 머신러닝에 사용되는 인기 있는 라이브러리

- 대규모 숫자 계산을 해주는 라이브러리

- 자체는 C++로 만들어진 라이브러리

- 일반적인 프로그래밍 방식과는 약간 다른 개념들을 포함한다.


[ 설치 과정 ]


python 3.6 버전을 철치한다.


tensorflow는 1.15버전 설치한다.
 

pip install tensorflow-cpu==1.15 # CPU
pip install tensorflow-gpu==1.15 # GPU
 




[ tensorflow 사용하기 ]
import tensorflow as tf
 


실습.


# -*- coding: utf-8 -*-
import tensorflow as tf


hello = tf.constant('Hello Tensorflow!!')  # 상수 정의
print(hello)
 


결과.


1.PNG

 

오류 : Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 

직역하면 당신의 CPU는 이 텐서플로우 바이너리가 사용하지 않은 명령어들을 지원한다. 정도가 될 것이다.

해결방법은 첫 번째는 무시하는 방법이고, 두번째는 다시 빌드(컴파일)하는 방법이다.

실제 응용에서는 빌드해야 겠지만, 처음 배울때는 무시하는 방법을 사용한다.


실습.


# -*- coding: utf-8 -*-
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # LOG_LEVEL를 2로 수정한다.


hello = tf.constant('Hello Tensorflow!!')
print(hello)


결과.


2.PNG

 

 


 

[tensorflow의 자료형]


- tensor : tensorflow에서 다양한 수학식을 계산하기 위한 가장 기본적이고
중요한 자료형
tensor의 형태는 배열과 비슷

Rank와 Shape라는 개념을 가지고 있다.


[ Rank 값 ]
0 : 스칼라
1 : 벡터
2 : 행렬
3 이상의 n : n-Tensor 또는 n차원 텐서 


[ Shape ]
각 차원의 요소 개수를 의미, 텐서의 구조를 의미


[dtype]
해당 텐서에 담긴 요소들의 자료형
string, float, int 등이 올 수 있다.


실습.


# -*- coding: utf-8 -*-
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


a = tf.constant(10)
b = tf.constant(40)
c = a + b #c = tf.add(a, b)

print(a)

print(b)
print(c)


결과.

5.PNG 

 


[tensorflow 프로그램 구조]

 

- 그래프 생성
- 그래프 실행

* 그래프 : tensor들의 연산 모음.

* 지연실행(lazy evaluation) : 함수형 프로그래밍에서 많이 사용

tensor와 tensor의 연산들을 미리 정의하여 그래프를 만들고,
필요할 때 연산을 실행하는 코드를 넣어 원하는 시점에 실제
연산을 수행하도록 하는 방식

* tensorflow 프로그래밍의 장점
모델 구성과 실행을 분리하여 프로그램을 깔끔하게 작성할 수 있다.



실습.


# -*- coding: utf-8 -*-
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

hello = tf.constant('Hello Tensorflow!!')
print(hello)


sess = tf.compat.v1.Session()
print(sess.run(hello))
sess.close()


결과.


3.PNG



실습.


# -*- coding: utf-8 -*-
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


# 그래프 생성

a = tf.constant(10)
b = tf.constant(40)
c = a + b #c = tf.add(a, b)
print(c)


# 그래프 실행
sess = tf.compat.v1.Session()
print(sess.run(c))
sess.close()



결과.


4.PNG




텐서플로 프로그래밍시 반드시 알아야 할 개념 두가지

 

# 플레이스홀더(placeholder) : 그래프에 사용할  입력값을 나중에 받기 위해 사용하는 매개변수(parameter)와 같은 개념

# 변수 : 그래프를 최적화하는 용도로 텐서플로가 학습한 결과를 갱신하기 위해  사용하는 것이 변수이다. (변수의 값들이 신경망의 성능을 좌우한다.)
 


실습.


# -*- coding: utf-8 -*-
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


# 플레이스홀더 정의하기
a = tf.compat.v1.placeholder(tf.int32, [3])
aa = tf.compat.v1.placeholder(tf.int32, [None])


# 배열을 2배로 하는 연산 정의하기
b = tf.constant(2)
x2 = a * b

bb = tf.constant(10)
x10 = aa * bb


sess = tf.compat.v1.Session()


#플레이스 홀더에 값을 넣고 실행하기
r1 = sess.run(x2, feed_dict={a:[1,2,3]})
r2 = sess.run(x2, feed_dict={a:[11,22,33]})

rr1 = sess.run(x10, feed_dict = {aa:[1,2,3,4]})
rr2 = sess.run(x10, feed_dict={aa:[1,2,3,4,5,6,7,8]})


print(r1)
print(r2)
print("========================")
print(rr1)
print(rr2)



결과.


6.PNG



실습.


# -*- coding: utf-8 -*-
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


# 상수를 정의하기(tf.Constant)
a = tf.constant(100)
b = tf.constant(120)
c = tf.constant(140)


# 변수를 정의하기(tf.Variable)

v = tf.Variable(0)


# 데이터 플로우 그래프 정의하기
calc_op = a + b + c

assign_op = tf.compat.v1.assign(v, calc_op)


sess = tf.compat.v1.Session()

sess.run(tf.global_variables_initializer()) # 세션 초기
sess.run(assign_op)

print(sess.run(v))




결과.



7.PNG



실습.


# -*- coding: utf-8 -*-
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


X = [[1.0,2.0,3.0], [4.0,5.0,6.0]]
W = tf.Variable([[0.1, 1.0], [0.2,2.0], [0.3,3.0]])

print(X)
print("---------------------------")
print(W)
print("---------------------------")
res = tf.matmul(X, W)
print(res)
print("---------------------------")


sess = tf.compat.v1.Session()
sess.run(tf.compat.v1.global_variables_initializer())
print(sess.run(res))

sess.close()


결과.


8.PNG



댓글목록

관리자님의 댓글

관리자 작성일

추가설치 1.
Visual Studio 2015, 2017 및 2019용 Microsoft Visual C++ 재배포 가능 패키지

https://support.microsoft.com/ko-kr/help/2977003/the-latest-supported-visual-c-downloads

추가설치 2.
오류메세지.
 tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found

CUDA Toolkit 설치(10.1)

https://developer.nvidia.com/cuda-10.1-download-archive-update2?target_os=Windows&target_arch=x86_64&target_version=10&target_type=exelocal

추가설치3.
cuDNN (cudnn-10.1)설치하기

https://developer.nvidia.com/rdp/cudnn-archive

관리자님의 댓글

관리자 작성일

tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2

https://blog.naver.com/PostView.nhn?blogId=complusblog&logNo=221237740617&redirect=Dlog&widgetTypeCall=true&directAccess=false


개인정보취급방침 서비스이용약관 모바일 버전으로 보기 상단으로

TEL. 063-469-4551 FAX. 063-469-4560 전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과

Copyright © www.leelab.co.kr. All rights reserved.