ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [TensorFlow] 01. 1차 방정식 학습하기
    Machine Learning 2024. 4. 10. 15:16

    코드부터 작성하기

    import tensorflow as tf
    import numpy as np
    from tensorflow.keras import Sequential
    from tensorflow.keras.layers import Dense
    
    model = Sequential([Dense(units=1, input_shape=[1])])
    model.compile(optimizer='sgd', loss='mean_squared_error')
    
    X, Y = [], []
    for i in range(-5, 6):
      X.append(i)
      Y.append(4*i-5)
    
    xs = np.array(X, dtype=float)
    ys = np.array(Y, dtype=float)
    print(xs, ys)
    
    model.fit(xs, ys, epochs=500)
    
    print(model.predict([10.0])) # 35

    위 코드는
    $$ y=4\cdot x-5 $$
    위 수식을 예측하는 모델을 학습한 후, x=10을 대입하여 결과를 확인하는 코드이다.

    코드 분석하기

    모듈 불러오기

    Sequential: 여러 레이어가 순차적인 구조를 가지는 모델

    Dense: Fully Connected Layer(완전 연결 계층), 각 layer끼리 모든 뉴런이 서로 연결되어있는 계층

    import tensorflow as tf
    import numpy as np
    from tensorflow.keras import Sequential
    from tensorflow.keras.layers import Dense

    모델 구성하기

    출력(units) 개수가 1개, 입력 개수(input_shape)가 1개인 완전연결계층을 하나 배열한 Sequential 모델.

    • 옵티마이저(optimizer): SGD(Stochastic Gradient Descent)
    • 손실함수(loss, Loss Function): 평균제곱오차(MSE, Mean Squared Error)
    model = Sequential([Dense(units=1, input_shape=[1])])
    model.compile(optimizer='sgd', loss='mean_squared_error')

    데이터 준비하기

    • X = [-5, -4, -3, -2, ... , 5]
    • y = 4 * x - 5
    • Y = [-25, -21, -17, -13, ... , 15]
    X, Y = [], []
    for i in range(-5, 6):
      X.append(i)
      Y.append(4*i-5)
    
    xs = np.array(X, dtype=float)
    ys = np.array(Y, dtype=float)

    모델 학습하기

    tf.keras.Model.fit(x, y)

    • x = Input 데이터
    • y = Target 데이터(정답)
    • epochs = 학습의 반복 수
    model.fit(xs, ys, epochs=500)

    예측하기

    $$ y=4\cdot x-5 $$
    x = 10일 때
    $$ y=4\cdot 10-5=35 $$

    모델의 예측은 35.000202가 나왔다. 거의 비슷한 수치.

    print(model.predict([10.0])) # 35
    1/1 [==============================] - 0s 160ms/step
    [[35.000202]]

    참고도서

Designed by Tistory.