파이썬 머신러닝ML

Linear regression

양기호니 2023. 7. 26. 22:00
728x90
반응형

W,b를 조정해서 참에 가까운값으로 예측한다.

 

import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras.optimizers import SGD

# X, Y 데이터
x_train = [1,2,3]
y_train = [1,2,3]

W = tf.Variable(tf.random.normal([1]), name='weight')
b = tf.Variable(tf.random.normal([1]), name='bias')
#cost/loss function
def compute_cost():
    # XW+b
    h = x_train * W + b
    cost=tf.reduce_mean((h-y_train)**2)
    return cost
optimizer=SGD(learning_rate=0.01) #미분 + 알파 기능
for i in range( 2000):
    optimizer.minimize(compute_cost, var_list=[W,b])
print(i, '코스트', compute_cost().numpy)

1999 코스트 <bound method _EagerTensorBase.numpy of <tf.Tensor: shape=(), dtype=float32, numpy=9.3275736e-07>>

W.numpy(),b.numpy()

(array([0.99887836], dtype=float32), array([0.00254972], dtype=float32))

반응형