Lab08_Tensor_Manipulation.md

Tensor Manipulation

0. 공통 라이브러리 import

  • InteractiveSession()

    • 쉘과 같은 인터랙티브 컨텍스트에서 사용하기 위한 Tensorflow Session
    • 자기 자신을 기본 Session으로 설치, 아래 코드 중 Tensor.eval()에서 사용되는 Session
    • 인터랙티브 쉘과 Jupyter Notebook에서 편리하며 Session 객체를 명시적으로 전달하지 않아도 됨
import numpy as np
import pprint
import tensorflow as tf
pp = pprint.PrettyPrinter(indent=4)
sess = tf.InteractiveSession()

 

1. Simple Array

t = np.array([0., 1., 2., 3., 4., 5., 6.])
pp.pprint(t)
print(t.ndim) # rank
print(t.shape) # shape
# slicing
print(t[0], t[1], t[-1])
print(t[2:5], t[4:-1])
print(t[:2], t[3:])
array([0., 1., 2., 3., 4., 5., 6.])
1
(7,)
0.0 1.0 6.0
[2. 3. 4.] [4. 5.]
[0. 1.] [3. 4. 5. 6.]

 

2. 2D Array

t = np.array([[1.,2.,3.], [4.,5.,6.], [7.,8.,9.], [10.,11.,12.]])
pp.pprint(t)
print(t.ndim)
print(t.shape)
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.],
       [ 7.,  8.,  9.],
       [10., 11., 12.]])
2
(4, 3)

 

3. Shape, Rank, Axis

t = tf.constant([1,2,3,4])
tf.shape(t).eval()
array([4], dtype=int32)

 

t = tf.constant([[1,2],
                [3,4]])
tf.shape(t).eval()
array([2, 2], dtype=int32)

 

t = tf.constant([[[[1,2,3,4], [5,6,7,8], [9,10,11,12]],
                  [[13,14,15,16], [17,18,19,20], [21,22,23,24]]]])
tf.shape(t).eval()
array([1, 2, 3, 4], dtype=int32)

 

4. Matmul VS multiply

matrix1 = tf.constant([[1.,2.], [3.,4.]])
matrix2 = tf.constant([[1.], [2.]])
print("matrix 1 shape", matrix1.shape)
print("matrix 2 shape", matrix2.shape)
tf.matmul(matrix1, matrix2).eval()
matrix 1 shape (2, 2)
matrix 2 shape (2, 1)
array([[ 5.],
       [11.]], dtype=float32)

 

  • 주의

    • 행렬의 곱은 matmul을 사용
    • *를 이용하는 경우 broadcasting으로 인해 이상한 결과가 나올 수 있으므로 주의
(matrix1*matrix2).eval()
array([[1., 2.],
       [6., 8.]], dtype=float32)

 

5. Broadcasting

matrix1 = tf.constant([[3.,3.]])
matrix2 = tf.constant([[2., 2.]])
(matrix1 + matrix2).eval()
array([[5., 5.]], dtype=float32)

 

matrix1 = tf.constant([[1., 2.]])
matrix2 = tf.constant(3.)
(matrix1+matrix2).eval()
array([[4., 5.]], dtype=float32)

 

matrix1 = tf.constant([[1., 2.]])
matrix2 = tf.constant([3., 4.])
(matrix1+matrix2).eval()
array([[4., 6.]], dtype=float32)

 

matrix1 = tf.constant([[1., 2.]])
matrix2 = tf.constant([[3.], [4.]])
(matrix1+matrix2).eval()
array([[4., 5.],
       [5., 6.]], dtype=float32)

 

6. Reduce mean

  • 주어진 값의 타입이 int이기 때문에 결과도 int로 나옴
tf.reduce_mean([1, 2], axis=0).eval()
1

 

x = [[1., 2.],
    [3., 4.]]
tf.reduce_mean(x).eval()
2.5

 

tf.reduce_mean(x, axis=0).eval()
array([2., 3.], dtype=float32)

 

tf.reduce_mean(x, axis=1).eval()
array([1.5, 3.5], dtype=float32)

 

tf.reduce_mean(x, axis=-1).eval()
array([1.5, 3.5], dtype=float32)

 

7. Reduce sum

tf.reduce_sum(x).eval()
10.0

 

tf.reduce_sum(x, axis=0).eval()
array([4., 6.], dtype=float32)

 

tf.reduce_sum(x, axis=1).eval()
array([3., 7.], dtype=float32)

 

tf.reduce_mean(tf.reduce_sum(x, axis=-1)).eval()
5.0

 

8. Argmax

x = [[0, 1, 2],
    [2, 1, 0]]
tf.argmax(x, axis=0).eval()
array([1, 0, 0])

 

tf.argmax(x, axis=1).eval()
array([2, 0])

 

tf.argmax(x, axis=-1).eval()
array([2, 0])

 

9. Reshape

t = np.array([[[0, 1, 2],
              [3, 4, 5]],
            [[6, 7, 8],
             [9, 10, 11]]])
t.shape
(2, 2, 3)

 

tf.reshape(t, shape=[-1, 3]).eval()
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

 

tf.reshape(t, shape=[-1, 1, 3]).eval()
array([[[ 0,  1,  2]],

       [[ 3,  4,  5]],

       [[ 6,  7,  8]],

       [[ 9, 10, 11]]])

 

tf.squeeze([[0], [1], [2]]).eval()
array([0, 1, 2], dtype=int32)

 

tf.expand_dims([0, 1, 2], 1).eval()
array([[0],
       [1],
       [2]], dtype=int32)

 

10. One_hot

tf.one_hot([[0], [1], [2], [0]], depth=3).eval()
array([[[1., 0., 0.]],

       [[0., 1., 0.]],

       [[0., 0., 1.]],

       [[1., 0., 0.]]], dtype=float32)

 

  • one_hot을 수행한 후 rank가 expand되므로 reshape 필요
t = tf.one_hot([[0], [1], [2], [0]], depth=3)
tf.reshape(t, shape=([-1, 3])).eval()
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.],
       [1., 0., 0.]], dtype=float32)

 

11. Casting

tf.cast([1.8, 2.2, 3.3, 4.9], tf.int32).eval()
array([1, 2, 3, 4], dtype=int32)

 

tf.cast([True, False, 1 == 1, 0 == 1], tf.int32).eval()
array([1, 0, 1, 0], dtype=int32)

 

12. Stack

x = [1, 4]
y = [2, 5]
z = [3, 6]

tf.stack([x, y, z]).eval()
array([[1, 4],
       [2, 5],
       [3, 6]], dtype=int32)

 

tf.stack([x, y, z], axis=0).eval()
array([[1, 4],
       [2, 5],
       [3, 6]], dtype=int32)

 

tf.stack([x, y, z], axis=1).eval()
array([[1, 2, 3],
       [4, 5, 6]], dtype=int32)

 

13. One and Zeros like

x = [[0, 1, 2],
    [2, 1, 0]]
tf.ones_like(x).eval()
array([[1, 1, 1],
       [1, 1, 1]], dtype=int32)

 

tf.zeros_like(x).eval()
array([[0, 0, 0],
       [0, 0, 0]], dtype=int32)

 

14. Zip

for x, y in zip([1, 2, 3], [4, 5, 6]):
    print(x, y)
1 4
2 5
3 6

 

for x, y, z in zip([1, 2, 3], [4, 5, 6], [7, 8, 9]):
    print(x, y, z)
1 4 7
2 5 8
3 6 9

'AI&BigData > Deep Learning' 카테고리의 다른 글

Lab10-1. ReLU: Better non-linearity  (0) 2018.05.18
Lab09-3. Sigmoid Backpropagation  (0) 2018.05.18
Lab09-2. TensorBoard  (0) 2018.05.05
Lab09-1. NN for XOR  (0) 2018.04.27
Lab08-2. Deep Learning의 기본 개념  (0) 2018.04.26
Lab07-2. MNIST data  (0) 2018.04.18
Lab07-1. Application&Tip  (0) 2018.04.18
Lab06. Softmax Classification  (0) 2018.04.18
Lab05. Logistic classification  (0) 2018.04.18