#!/usr/bin/env python3


Activation  Function


activation function는 신경망의 필수 요소이기 때문에 신경망을 사용할 때는 활성화 함수를 자주 접하게 됩니다.

activation function의 목표는 가중치와 편향치를 조절하는 것이며 텐서플로에서 activation function는 텐서에 적용되는 비선형 연산입니다.


신경망에 비선형성을 도입하는 가장 일반적인 방법은 ReLU 함수가 있습니다.

import tensorflow as tf

import numpy as np

import matplotlib.pyplot as plt


def printf(tfclass):

    init = tf.global_variables_initializer()

    with tf.Session() as sess:

        init.run()

        print(tfclass.eval())


line = tf.linspace(-10., 10., num=100)

def plot_act_func(model):

    init = tf.global_variables_initializer()

    with tf.Session() as sess:

        init.run()

        x = line.eval()

        y = model.eval()

    plt.plot(x, y)

    plt.show()


relu_rlt = tf.nn.relu([-3., 3., 10.])

printf(relu_rlt)

# [ 0.  3. 10.]


relu = tf.nn.relu(line)

plot_act_func(relu)

ReLU Function



ReLU activation function의 선형 증가량에 상한을 설정하고 싶을 때가 있습니다.

max(0, x) 함수를 min()함수로 감싸서 구현할 수 있습니다. 텐서플로에는 ReLU6가 구현되어 있고

Relu6 = min(max(0, x), 6)으로 정의되어 있습니다.


ReLU6 이 함수는 매끄럽지 않은 각진 모양의 sigmoid 함수로 생각할 수 있습니다.

relu6_rlt = tf.nn.relu6([-3., 3., 10.])

printf(relu6_rlt)

# [0. 3. 6.]


relu6 = tf.nn.relu6(line)

plot_act_func(relu6)

relu6 function



sigmoid 함수는 연속이고 매끄러운 가장 일반적인 activation function입니다. 로지스틱 함수라고도 하며, 수식으로는

1 / (1+exp(-x))로 표현합니다. sigmoid 함수는 학습 과정에서 역전파 항을 0으로 만들어 버리는 경향이 있기 때문에 자주 사용하지는 않습니다.


sig_result = tf.nn.sigmoid([-1., 0., 1.])

printf(sig_result)

# [0.26894143 0.5        0.7310586 ]


sigmoid = tf.nn.sigmoid(line)

plot_act_func(sigmoid)

sigmoid function



또 다른 activation function하이퍼볼릭 탄젠트 함수가 있습니다. 하이퍼볼릭 탄젠트 함수는 sigmoid 함수와 아주 비슷하지만, 함수 값의 범위가 -1에서 1입니다.

tanh_rlt = tf.nn.tanh([-1.0, 0., 1.])

printf(tanh_rlt)

# [-0.7615942  0.         0.7615942]


tanh = tf.nn.tanh(line)

plot_act_func(tanh)

tanh function



softsign 함수도 activation function로 사용할 수 있습니다.

x / (abs(x) + 1)로 표현할 수 있으며 부호sign 함수를 연속 함수로 근사한 것입니다.

sosign = tf.nn.softsign([-1., 0., -1.])

printf(sosign)

# [-0.5  0.  -0.5]


softsign = tf.nn.softsign(line)

plot_act_func(softsign)

softsign function



softplus 함수는 매끄럽게 만든 ReLU 함수라고 할 수 있다. 이 함수의 식은 log(exp(x) + 1)

softplus_rlt = tf.nn.softplus([-1., 0., -1.])

printf(softplus_rlt)

# [0.31326166 0.6931472  0.31326166]


softplus = tf.nn.softplus(line)

plot_act_func(softplus)

softplus function

입력값이 커지면 softplus 함수값은 무한대로 가고, softsign 함수 값은 1에 수렴합니다.

반대로 입력 값이 작아지면 softplus 함수 값은 0에 수렴하고, softsign함수값은 -1에 수렴합니다.



지수 선형 유닛(ELU, Exponential Linear Unit) 함수는 softplus 함수와 비슷하지만 하부 점근선이 -1입니다.

x<0일 때는 exp(x)+1이고, 그외에는 x입니다.

elu_rlt = tf.nn.elu([-1.0, 0., -1.])

printf(elu_rlt)

# [-0.63212055  0.         -0.63212055]


elu = tf.nn.elu(line)

plot_act_func(elu)

elu function




참고 자료: 

[1]TensorFlow Machine Learning Cookbook, Nick McClure

'Tensorflow > Introduction' 카테고리의 다른 글

placeholder, marix, operation  (0) 2018.04.25
Getting Start Tensorflow  (0) 2018.04.25

#!/usr/bin/env python3


placeholder, marix, operation


변수는 텐서를 입력받아 변수를 출력하는 Variable()함수를 이용하여 주로 생성합니다.

이 함수는 변수 선언만 하기 때문에 변수 초기화를 별도로 해줘야 합니다.

import tensorflow as tf


my_var = tf.Variable(tf.zeros([2, 3]), dtype=tf.float32, name='my_var')


init = tf.global_variables_initializer()

with tf.Session() as sess:

    sess.run(init)


    result = my_var.eval()

    print(result)

    # [[0. 0. 0.]

    # [0. 0. 0.]]



placeholder는 계산 그래프에 데이터가 투입되는 위치를 나타냅니다. 세션의 feed_dict 인자를 통해 placeholder 데이터를 투입합니다.

계산에 placeholder를 넣기 위해서는 placeholder에 대해 하나 이상의 연산을 수행해야 합니다.

import numpy as np


with tf.Session() as sess:

    x = tf.placeholder(tf.float32, shape=[2, 2])

    y = tf.identity(x) # Return a tensor with the same shape and contents as input.

    x_vals = np.random.rand(2, 2)


    print(sess.run(y, feed_dict={x: x_vals}))

    # [[0.18282834 0.35173032]

    #  [0.3008346  0.14677659]]



다음은 matrix를 다루는 몇가지 방법에 대해 알아보겠습니다.

sess =  tf.Session()

identity_matrix = tf.diag([1., 1., 1.]) # identity matrix

A = tf.truncated_normal([2, 3], mean=1, stddev=1, dtype=tf.float32)

B = tf.fill([2, 3], 5.)

C = tf.random_uniform([3, 2], dtype=tf.float32)


np_arr = np.array([[1, 2, 3],

                       [-3, -7, -1],

                       [0, 5, -2]])

D = tf.convert_to_tensor(np_arr, dtype=tf.float32)



print(sess.run(identity_matrix))

# [[1. 0. 0.]

#  [0. 1. 0.]

#  [0. 0. 1.]]


print(sess.run(A))

# [[0.25446475 1.108418   2.5896869 ]

#  [0.3214993  0.6533705  0.8581022 ]]


print(sess.run(B))

# [[5. 5. 5.]

#  [5. 5. 5.]]


print(sess.run(C))

# [[0.9613472  0.97370124]

#  [0.4405172  0.7275435 ]

#  [0.9694842  0.23063374]]


print(sess.run(D))

# [[ 1.  2.  3.]

#  [-3. -7. -1.]

#  [ 0.  5. -2.]]


# 더하기 빼기는 다음과 같이 사용합니다.

print(sess.run(A+B))

# [[6.5324025 6.2761655 7.3138623]

#  [5.8994517 7.0984983 6.506235 ]]


print(sess.run(A-B))

# [[-4.5335164 -4.079894  -2.3542004]

#  [-4.500795  -5.3273354 -2.5056663]]


# 행렬곱은 다음 함수를 사용합니다.

print(sess.run(tf.matmul(B, identity_matrix)))

# [[5. 5. 5.]

#  [5. 5. 5.]]


print(sess.run(tf.transpose(C)))

# [[0.16169488 0.08706641 0.3332044 ]

#  [0.18076909 0.5893874  0.8159915 ]]


print(sess.run(tf.matrix_determinant(D)))

# -38.0


print(sess.run(tf.matrix_inverse(D)))

# [[-0.50000006 -0.5        -0.50000006]

#  [ 0.15789475  0.05263158  0.21052633]

#  [ 0.39473686  0.13157895  0.0263158 ]]


print(sess.run(tf.cholesky(identity_matrix)))

# [[1. 0. 0.]

#  [0. 1. 0.]

#  [0. 0. 1.]]


eig_value, eig_vector = sess.run(tf.self_adjoint_eig(D))

print(eig_value)

# [-10.659076    -0.22750695   2.886583  ]


print(eig_vector)

# [[-0.21749546 -0.6325011  -0.74339646]

#  [-0.84526515 -0.25879988  0.46749276]

#  [ 0.48808062 -0.7300446   0.4783433 ]]



나눗셈과 외은 다음과 같이 구합니다.

with tf.Session() as sess:

    f = tf.div(3, 4) # 몫만 표현

    print (f.eval()) # 0


    f1 = tf.truediv(3, 4) # 나눗셈 결과를 소수로 표현

    print(f1.eval()) # 0.75


    f2 = tf.floordiv(3.0, 4.0) # 몫을 소수로 표현

    print(f2.eval()) # 0.0


    f3 = tf.mod(22.0, 5.0) # 나머지

    print(f3.eval()) # 2.0


    f4 = tf.cross([1., 0., 0.], [0., 1., 0.]) # 외적

    print(f4.eval()) # [0. 0. 1.]



tan(pi/4)는 다음과 같이 구할 수 있습니다.

init = tf.global_variables_initializer()

with tf.Session() as sess:

init.run()

result = tf.div(tf.sin(np.pi/4.), tf.cos(np.pi/4.))

print(result)

# 1.0



다항함수 3*x^2 -x + 10의 결과는 다음 코드로 구현할 수 있습니다.

def custom_polynomial(val):

    return(3*tf.square(val) - val + 10)


init = tf.global_variables_initializer()

with tf.Session() as sess:

init.run()

result = custom_polynomial(11).eval()

print(result)

# 362




참고 자료: 

[1]TensorFlow Machine Learning Cookbook, Nick McClure

'Tensorflow > Introduction' 카테고리의 다른 글

Activation Function  (0) 2018.04.25
Getting Start Tensorflow  (0) 2018.04.25

#!/usr/bin/env python3


Getting Start Tensorflow


tensorflow는 객체로 만들어지기 때문에 출력을 위해 printf를 정의하고 이 것을 사용하겠습니다.

import tensorflow as tf


def printf(tfclass):

    init = tf.global_variables_initializer()

    with tf.Session() as sess:

        sess.run(init)

        rlt = tfclass.eval()

    print(rlt)

    

0 값으로 채워진 텐서는 다음과 같이 생성합니다.

zero_tsr = tf.zeros([3, 2])

printf(zero_tsr)

# [[0. 0.]

#  [0. 0.]

#  [0. 0.]]


1 값으로 채워진 텐서는 다음과 같이 생성합니다.

ones_tsr = tf.ones([3, 2])

printf(ones_tsr)

# [[1. 1.]

#  [1. 1.]

#  [1. 1.]]


동일한 상수값으로 채워진 텐서는 다음과 같이 생성합니다.

filled_tsr = tf.fill([3, 2], 9)

printf(filled_tsr)

# [[9 9]

#  [9 9]

#  [9 9]]


기존 상수를 이용해 텐서를 생성할 때는 다음 방식을 사용합니다.

constant_tsr = tf.constant([1, 2, 3])

printf(constant_tsr)

# [1 2 3]


기존 텐서의 형태를 바탕으로 텐서 변수를 초기화하는 것도 가능합니다.

zeros_similar = tf.zeros_like(constant_tsr)

printf(zeros_similar)

# [0 0 0]

ones_similar = tf.ones_like(constant_tsr)

printf(ones_similar)

# [1 1 1]


텐서플로는 구간을 지정하는 방식으로 텐서를 선언할 수 있습니다. 다음 함수는 range()나 numpy의 linspace()와 비슷하게 동작합니다.

linear_tsr = tf.linspace(0.0, 1.0, num=3)

printf(linear_tsr)

# [0.  0.5 1. ]


integer_seq_tsr = tf.range(6.0, 15, delta=3)

printf(integer_seq_tsr)

# [ 6.  9. 12.]


랜덤한 숫자도 뽑아낼 수 있습니다.

randunif_tsr = tf.random_uniform([3, 2], minval=0, maxval=1, dtype=tf.float32)

printf(randunif_tsr)

# [[0.218009   0.7311672 ]

#  [0.6954018  0.2027992 ]

#  [0.95226717 0.9950316 ]]


randnorm_tsr = tf.random_normal([3, 2], mean=0.0, stddev=1.0)

printf(randnorm_tsr)

# [[-0.45060402 -1.6076114 ]

#  [ 0.7157349  -0.28653365]

#  [ 1.2830635   0.6957943 ]]


특정 범위에 속하는 정규 분포 임의의 값을 생성하고 싶은 경우에 지정한 평균에서 항상 표준편차 2배 이내의 값을 뽑아줍니다.

truncnorm_tsr = tf.truncated_normal([3, 2], mean=3.0, stddev=1.0)

printf(truncnorm_tsr)

# [[2.6660793 2.3485358]

#  [3.378799  2.757817 ]

#  [2.8825157 1.9243042]]


배열의 항목을 임의로 섞을 때

shuffle_output = tf.random_shuffle(truncnorm_tsr)

printf(shuffle_output)

# [[2.174755  4.001117 ]

#  [2.6528723 2.8258555]

#  [3.5614102 2.8608997]]


cropped_output = tf.random_crop(shuffle_output, [3, 2])

printf(cropped_output)

# [[2.6678126 2.087521 ]

#  [1.5311174 4.574707 ]

#  [2.400455  3.175764 ]]




참고 자료: 

[1]TensorFlow Machine Learning Cookbook, Nick McClure

'Tensorflow > Introduction' 카테고리의 다른 글

Activation Function  (0) 2018.04.25
placeholder, marix, operation  (0) 2018.04.25

+ Recent posts