반응형

텐서플로우에서 행렬 계산하는 방법을 설명합니다.



다음 사이트에 있는 텐서플로우 예제들을 공부한 결과를 비정기적으로 올릴 예정입니다.

https://github.com/aymericdamien/TensorFlow-Examples






텐서플로우 2.0에서 텐서플로우 1.x 코드를 실행하는 방법을 설명합니다. 


Tensorflow 2.0에서 Tensorflow 1.x 코드 실행하기

https://webnautes.tistory.com/1393



같은 크기의 행렬간의 덧셈과 뺄셈은 tf.add와 tf.subtract 함수로 계산할 수 있습니다.


from __future__ import print_function

import tensorflow as tf

# 2 x 2 행렬
#  | 1  2 |
#  | 3  4 |
matrix1 = tf.constant([[1., 2.], [3., 4.]])


# 2 x 2 행렬

#  | 1  1 |

#  | 1  1 |

matrix2 = tf.constant([[1., 1.],[1., 1.]])


add = tf.add(matrix1, matrix2)
sub = tf.subtract(matrix1, matrix2)


# 세션에서 계산 결과 출력
with tf.Session() as sess:
   result = sess.run(add)
   print(result)
   result = sess.run(sub)
   print(result)




[[2. 3.]

[4. 5.]]

[[0. 1.]

[2. 3.]]





from __future__ import print_function

import tensorflow as tf

# 1 x 2 행렬 -> 행벡터
matrix1 = tf.constant([[1., 2.]])

# 2 x 1 행렬 -> 열벡터
matrix2 = tf.constant([[3.],[4.]])


# 1 x 1 행렬이 됩니다.
product1 = tf.matmul(matrix1, matrix2)
# [[11.]]


# 곱할때 순서를 바꾸면 2 x 2 행렬이 됩니다.
product2 = tf.matmul(matrix2, matrix1)
# [[3. 6.]
#  [4. 8.]]


# 세션에서 계산 결과 출력
with tf.Session() as sess:
   result = sess.run(product1)
   print(result)
   result = sess.run(product2)
   print(result)



[[11.]]

[[3. 6.]

 [4. 8.]]






원본 코드

https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/1_Introduction/basic_operations.py


마지막 업데이트 - 2018. 8. 24



문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts