import tensorflow as tf
import numpy as np

tf.random.set_seed(400)

x_data = np.array([[50, 47], [40, 43], [30, 15], [85, 83], [97, 85], [100, 100]], dtype=np.float32)
y_data = np.array([[0], [0], [0], [1], [1], [1]], dtype=np.float32)

w = tf.Variable(tf.random.normal([2, 1]))
b = tf.Variable(tf.random.normal([1]))
print(w, b)
learning_rate = 0.0001
for i in range(5001):
    with tf.GradientTape() as tape:
        hypothesis = 1 / (1 + tf.exp(-(tf.matmul(x_data, w) + b)))
        cost = tf.reduce_mean(-tf.reduce_sum(y_data*tf.math.log(hypothesis) + (1-y_data)*tf.math.log(1-hypothesis)))        
        w_grad, b_grad = tape.gradient(cost, [w, b])
        w.assign_sub(learning_rate * w_grad)
        b.assign_sub(learning_rate * b_grad)
    if i % 500 == 0:
        print(f'Step : {i}, Cost : {cost.numpy()}, Weight : {w.numpy()[0]}, Bias : {b.numpy()[0]}')

temp_x = np.array([[30, 25]], dtype=np.float32)
logistic = 1 / (1 + tf.exp(-(tf.matmul(temp_x, w) + b)))
print(f"점수가 {temp_x[0]} 일 때", tf.cast(logistic > 0.5, dtype=tf.float32).numpy()[0])
반응형

+ Recent posts