인공지능/딥러닝

텐서플로 - 설치, 상수/변수 선언, 메소드

해피밀세트 2020. 5. 28. 20:00
반응형

 

 

TensorFlow

  • 구글이 오픈소스로 공개한 머신러닝 라이브러리
  • 다차원 행렬 계산(tensor), 대규모 숫자 계산 작업을 수행한다.
  • C++ 만들어진 라이브러리
  • CPU, GPU 버전이 있음
  • C++, JAVA, Python에서 사용가능

 

1. 텐서플로 설치 및 불러오기

 

1) 아나콘다 프롬프트 관리자 권한으로 실행

 

 

2) 텐서플로 1.15버전으로 설치

pip install --upgrade tensorflow==1.15

 

 

3) 텐서플로 불러오기

import tensorflow as tf

 

 

4) 텐서플로 버전 확인

tf.__version__

 


 

2. 상수 / 변수 선언

 

1) tf.constant() : 상수 선언

# 텐서 생성

tensor = tf.constant("tensorflow")
tensor
print(tensor)

### 텐서는 선언하고나서 세션을 시작해야한다.

# 세션 만들기

sess = tf.Session()

# 세션 실행

sess.run(tensor)

# 세션 닫기

sess.close()

a = tf.constant(1234)
b = tf.constant(5678)
add_op = a + b
add_op

sess = tf.Session()

sess.run(add_op)

sess.run([a,b,add_op])

sess.close()

a = tf.constant(1)
b = tf.constant(2)
c = tf.constant(3)
x1 = a+b*c
x2 = (a+b)*c

sess = tf.Session()

sess.run(x1)

sess.run(x2)

sess.close()

 

 

2) tf.Variable() : 변수 선언

# 오류남
# tf.matmul() : 행렬의 곱


x = tf.Variable([[1,2,3],[4,5,6]])  # 2x3
y = tf.Variable([[1,2],[3,4],[5,6]]) # 3x2
z = tf.Variable(0)
z = tf.matmul(x,y)

sess = tf.Session()

sess.run(x)

sess

# 상수로 하면 오류나지 않는다.

x = tf.constant([[1,2,3],[4,5,6]])  

y = tf.constant([[1,2],[3,4],[5,6]])
z = tf.Variable(0)

z = tf.matmul(x,y)

 

sess = tf.Session()

sess.run(x)

sess.run(y)

sess.run(z)

sess.close()

# 선언한 변수를 실행할땐 꼭 변수 초기화를 해주어야 한다.

x = tf.Variable([[1,2,3],[4,5,6]])

y = tf.Variable([[1,2],[3,4],[5,6]])

z = tf.Variable(0)

# tf.matmul() :

z = tf.matmul(x,y)

 

sess = tf.Session()

sess.run(tf.global_variables_initializer())

sess.run(x)

sess.run(y)

sess.run(z)

sess.close()

 

 

3) tf.placeholder() : 데이터 타입만 지정해두고 세션 실행 단계에서 데이터를 입력받음

p1 = tf.placeholder("int32")
p2 = tf.placeholder("int32")
y = tf.add(p1,p2)


# {변수이름 : 딕셔너리 모양으로 입력

sess = tf.Session()

sess.run(y,feed_dict={p1:10,p2:20})

sess.run(y,feed_dict={p1:300,p2:200})

sess.close()

 


 

3. 텐서플로 메소드

 

tf.add 덧셈
tf.subtract 뺄셈
tf.multiply 곱셈
tf.div 나눗셈의 몫
tf.truediv 나눗셈의 몫, 소숫점
tf.mod 나머지
tf.abs 절대값
tf.negative 음수
tf.sign 부호(음수 -1, 양수 1, 0)
tf.reciprocal 역수
tf.square 제곱
tf.round 반올림
tf.sqrt 제곱근
tf.pow 거듭제곱
tf.exp 지수값
tf.log 로그값
tf.maximum 최대값
tf.minimum 최소값
tf.cos 코사인
tf.sin 사인
반응형