출처 : http://hunkim.github.io/ml/


ML lab 06-1: TensorFlow로 Softmax Classification의 구현하기 


 

이론 

- Softmax function은 여러개의 클래스를 예측할 때 유용하다.

- hypothesis를 통해 나온값을 softmax에 넣으면 확률로 나온다.

- cost 함수로 cross-entropy를 사용한다. 



hypothesis, softmax 구현 

hypothesis

softmax


hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)



Cost function 구현 



cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1))

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)



전체 구현 


- label은 one-hot encoding으로 표현 

> tf.arg_max()를 사용하면 제일 높은값을 가지는 인덱스 리턴해줌 


x_data = [[1, 2, 1, 1], [2, 1, 3, 2], [3, 1, 3, 4], [4, 1, 5, 5], [1, 7, 5, 5], [1, 2, 5, 6], [1, 6, 6, 6], [1, 7, 7, 7]]
y_data = [[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 1, 0], [0, 1, 0], [0, 1, 0], [1, 0, 0], [1, 0, 0]]

X = tf.placeholder(tf.float32, [None, 4])
Y = tf.placeholder(tf.float32, [None, 3])
nb_classes = 3

W = tf.Variable(tf.random_normal([4, nb_classes]), name='weight')
b = tf.Variable(tf.random_normal([np_classes]), name='bias')

# tf.nn.softmax computes softmax activations
# softmax = exp(Logits) / reduce_sum(exp(Logits), dim)
hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)

# Cross entropy cost
cost = tf.reduce_mean(-tf.reduce_sum(Y  * tf.log(hypothesis), axis=1))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for step in range(2001):
        sess.run(optimizer, feed_dict={X: x_data, Y: y_data})
        if step % 200 == 0:
            print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}))



Test & one-hot encoding 

all = sess.run(hypothesis, feed_dict={X: [[1, 11, 7, 9],
                                                          [1, 3, 4, 3],
                                                          [1, 1, 0, 1]]})
print(all, sess.run(tf.arg_max(all, 1)))



ML lab 06-2: TensorFlow로 Fancy Softmax Classification의 구현하기 


- cross-entropy, reshape, one-hot에 대한 구현


기존 

logits = tf.matmul(X, W) + b
hypothesis = tf.nn.softmax(logits)

# Cross entropy cost/Loss 
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1))


함수사용 

# Cross entropy cost/Loss
cost_i = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y_one_hot)
cost = tf.reduce_mean(cost_i)

: 주의! hypothesis가 아닌 Logits을 넣어준다. 



Animal classification 

with softmax_cross_entropy_with_logits 


- 0 ~ 6 숫자로 이루워진 Y를 one_hot으로 바꿔줘야함

- one_hot()에 N차원을 입력하면 N+1차원이 출력된다.

: [[0], [3]] => [[[1000000]]

                  [[0001000]]]

: 그래서 reshape 해줘야함 

- tf.reshape()

tf.reshape(Y_one_hot, [-1, nb_classes])

: [[1000000], [0001000]]

(-1 : 알아서 해줘라)

xy = np.loadtxt('data-04-zoo.csv', delimiter=',', dtype=np.float32)
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]

np_classes = 7

X = tf.placeholder(tf.float32, [None, 16])
Y = tf.placeholder(tf.float32, [None, 1])

Y_one_hot = tf.one_hot(Y, np_classes)
Y_one_hot = tf.reshape(Y_one_hot, [-1, np_classes])

W = tf.Variable(tf.random_normal([16, np_classes]), name='weight') 
b = tf.Variable(tf.random_normal([nb_classes]), name='bias')

# tf.nn.softmax computes softmax activations 
# softmax = exp(Logits) / reduce_sum(exp(Logits), dim)
logits = tf.matmul(X, W) + b
hypothesis = tf.nn.softmax(logits)

# Cross entropy cost/Loss 
cost_i = tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = Y_one_hot)

cost = tf.reduce_mean(cost_i)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)

# 예측한 값이 맞는지 틀렸는지 판단하는 부분 
prediction = tf.argmax(hypothesis, 1)
correct_prediction = tf.equal(prediction, tf.argmax(Y_one_hot, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for step in range(2000):
        sess.run(optimizer, feed_dict={X: x_data, Y: y_data})
        if step % 100 == 0:
            loss, acc = sess.run([cost, accuracy], feed_dict={X: x_data, Y: y_data})
            print("Step: {:5}\tLoss: {:.3f}\tAcc: {.2%}".format(step, loss, acc))

    pred = sess.run(prediction. feed_dict={X: x_data})

    for p, y in zip(pred, y_data.flatten())
        print("[{}] Prediction: {} True Y: {}".format(p == int(y), p, int(y)))
    # .platten() : [[1], [0]] -> [1, 0]
    # p와 y에 값 넘겨주기위해 zip으로 묶어줌 


출처 : http://hunkim.github.io/ml/


ML lec 6-1 : Softmax Regression - 기본 개념 소개


여러개의 클래스가 있을때 예측하는 모델 Multinomial classification

그 중 많이 사용되는 Softmax classification 


Logistic Classification(regression) 복습 



Y : real data, Y(hat), H(x) : prediction data



Multinomial classification 


training data 

: x1        x2        y

 10         5        A

  9         5         A

  3         2         B

  2         4         B

  11        1        C


필기1 - 위 데이터 그래프에 뿌린거


- 위 그림처럼 binary classification으로 각각의 데이터를 예측할 수 있다.


필기2 


- 위 데이터는 필기2의 그림처럼 세 개의 독립된 classifier를 가지고 구현할 수 있다. 

> 그런데 세 개를 독립적으로 구현하면 복잡하고 어렵다. 



그래서, 하나의 matrix로 합친다 

> 세 개의 독립된 classification 알고리즘을 구현해도 되지만 

하나의 벡터로 처리하게 되면 한번에 처리가 가능하게 되고 세 개의 독립된 classification처럼 동작하게된다.

 


ML lec 6-2: softmax classifier의 cost함수 


Multinomial classification


- Hypothesis(Sigmoid)의 결과 값 -> softmax 

> 그러면, 각각 0 ~ 1 사이의 값이 나온다. 

  각각의 값을 더하면 1이된다. (확률로 볼 수 있다.) 



- 마지막으로 one-hot encoding 기법을 사용해 제일 큰 값만 1.0으로 만들고 나머지는 0으로 만든다.


cost function 


- Softmax classification에선 cost function으로 cross-entropy를 사용한다. 

Cross-entropy


- 위 식을 아래처럼 바꾸고

-log(x)를 그래프로 뿌려보면

위와 같은 그래프가 그려진다.


일때

- element mul


: 맞는 값이면 cost값이 0

  틀린 값이면 무한대값이 나온다.



이제 cost를 최소화하는 값을 찾으면된다.

출처 : http://hunkim.github.io/ml/


ML lab 05 : TensorFlow로 Logistic Classification의 구현하기 


구현 할 식 


Training Data 

x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]]
y_data = [[0], [0], [0], [1], [1], [1]]

X = tf.placeholder(tf.float32, shape=[None, 2])
Y = tf.placeholder(tf.float32, shape=[None, 1])


구현부

W = tf.Variable(tf.random_normal([2, 1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
# tf.div(1., 1. + tf.exp(tf.matmul(X, W) + b))
hypothesis = tf.sigmoid(tf.matmul(X, W) + b)
# cost function
cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) * tf.log(1 - hypothesis))

train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)

# hypothesis가 0.5 이상이면 true 아니면 false
# tf.float32로 캐스팅하면서 true는 1.0이되고, false는 0.0이된다.
predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)

# predicted와 Y를 비교하고 true면 1.0 false면 0.0으로 캐스팅
# 결과들을 reduce_mean을 통해 평균내서 정확도가 몇 퍼센트인지 볼 수 있다.
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))


Train the model

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for step in range(10001):
        cost_val, _ = sess.run([cost, train], feed_dict={X : x_data, Y : y_data})
        if step % 200 == 0:
            print(step, cost_val)

    h, c, a = sess.run([hypothesis, predicted, accuracy], feed_dict={X : x_data, Y : y_data})
    print("\nHypothesis: ", h, "\nCorrect (Y): ", c, "\nAccuracy: ", a)




+ Recent posts