>  기사  >  백엔드 개발  >  소프트웨어 엔지니어를 위한 머신러닝

소프트웨어 엔지니어를 위한 머신러닝

WBOY
WBOY원래의
2024-08-06 20:14:151189검색

Machine Learning for Software Engineers

귀중하다고 생각하시면 알려주시면 계속 진행하겠습니다!

1장 - 선형 모델

가장 단순하면서도 강력한 개념 중 하나는 선형 모델입니다.

ML의 주요 목표 중 하나는 데이터를 기반으로 예측하는 것입니다. 선형 모델은 기계 학습의 'Hello World'와 같습니다. 간단하지만 더 복잡한 모델을 이해하기 위한 기반을 형성합니다.

집값을 예측하는 모델을 만들어 보겠습니다. 이 예에서 출력은 예상되는 "주택 가격"이고 입력은 "sqft", "num_bedrooms" 등이 됩니다...

def prediction(sqft, num_bedrooms, num_baths):
    weight_1, weight_2, weight_3 = .0, .0, .0  
    home_price = weight_1*sqft, weight_2*num_bedrooms, weight_3*num_baths
    return home_price

각 입력에 대한 '가중치'가 표시됩니다. 이러한 가중치는 예측 뒤에 마법을 만들어내는 것입니다. 이 예제는 가중치가 0이므로 항상 0을 출력하므로 지루합니다.

이러한 가중치를 어떻게 찾을 수 있는지 알아봅시다.

가중치 찾기

가중치를 찾는 과정을 모델 '훈련'이라고 합니다.

  • 먼저 알려진 특징(입력)과 가격(출력)이 있는 주택 데이터세트가 필요합니다. 예를 들어:
data = [
    {"sqft": 1000, "bedrooms": 2, "baths": 1, "price": 200000},
    {"sqft": 1500, "bedrooms": 3, "baths": 2, "price": 300000},
    # ... more data points ...
]
  • 가중치를 업데이트하는 방법을 만들기 전에 예측이 얼마나 벗어난지 알아야 합니다. 예측과 실제 값의 차이를 계산할 수 있습니다.
home_price = prediction(1000, 2, 1) # our weights are currently zero, so this is zero
actual_value = 200000

error = home_price - actual_value # 0 - 200000 we are way off. 
# let's square this value so we aren't dealing with negatives
error = home_price**2

이제 하나의 데이터 포인트에 대한 오차(오류)를 알 수 있는 방법이 있으므로 모든 데이터 포인트에 대한 평균 오류를 계산할 수 있습니다. 이를 일반적으로 평균 제곱 오차라고 합니다.

  • 마지막으로 평균 제곱 오차를 줄이는 방식으로 가중치를 업데이트합니다.

물론 임의의 숫자를 선택하고 진행하면서 최상의 값을 계속 저장할 수 있지만 이는 비효율적입니다. 그럼 다른 방법인 경사하강법을 살펴보겠습니다.

경사하강법

경사하강법은 모델에 가장 적합한 가중치를 찾는 데 사용되는 최적화 알고리즘입니다.

그라디언트는 각 가중치에 작은 변화를 가할 때 오류가 어떻게 변하는지 알려주는 벡터입니다.

사이드바 직관
언덕이 많은 풍경 위에 서 있다고 상상해 보세요. 목표는 가장 낮은 지점(최소 오류)에 도달하는 것입니다. 그라데이션은 항상 가장 가파른 오르막을 가리키는 나침반과 같습니다. 그라데이션 방향을 반대로 하여 가장 낮은 지점을 향해 나아가고 있습니다.

작동 방식은 다음과 같습니다.

  1. 임의의 가중치(또는 0)로 시작하세요.
  2. 현재 가중치에 대한 오차를 계산합니다.
  3. 가중치별 오차의 기울기(기울기)를 계산합니다.
  4. 오류를 줄이는 방향으로 조금씩 이동하여 가중치를 업데이트하세요.
  5. 오류가 크게 감소하지 않을 때까지 2~4단계를 반복합니다.

각 오류에 대한 기울기는 어떻게 계산하나요?

경도를 계산하는 한 가지 방법은 가중치를 조금씩 이동하여 이것이 오류에 어떤 영향을 미치는지 확인하고 거기서부터 어디로 이동해야 하는지 확인하는 것입니다.

def calculate_gradient(weight, data, feature_index, step_size=1e-5):
    original_error = calculate_mean_squared_error(weight, data)

    # Slightly increase the weight
    weight[feature_index] += step_size
    new_error = calculate_mean_squared_error(weight, data)

    # Calculate the slope
    gradient = (new_error - original_error) / step_size

    # Reset the weight
    weight[feature_index] -= step_size

    return gradient

단계별 분석

  • 입력 매개변수:

    • 가중치: 모델의 현재 가중치 세트입니다.
    • 데이터: 주택 특징 및 가격에 대한 데이터세트입니다.
    • feature_index: 기울기를 계산하는 가중치(0은 평방피트, 1은 침실, 2는 욕실).
    • step_size: 가중치를 약간 변경하는 데 사용하는 작은 값(기본값은 1e-5 또는 0.00001).
  • 원래 오류 계산:

   original_error = calculate_mean_squared_error(weight, data)

먼저 현재 가중치를 사용하여 평균 제곱 오차를 계산합니다. 이것이 우리의 출발점입니다.

  • 무게를 약간 늘리세요:
   weight[feature_index] += step_size

무게를 조금씩(step_size) 늘립니다. 이를 통해 가중치의 작은 변화가 오류에 어떤 영향을 미치는지 확인할 수 있습니다.

  • 새 오류 계산:
   new_error = calculate_mean_squared_error(weight, data)

가중치를 약간 증가시켜 평균 제곱 오차를 다시 계산합니다.

  • 기울기(기울기) 계산:
   gradient = (new_error - original_error) / step_size

이것이 핵심 단계입니다. 우리는 "무게를 약간 늘렸을 때 오류가 얼마나 변했습니까?"라고 묻고 있습니다.

  • new_error > original_error, 기울기는 양수입니다. 즉, 이 가중치를 늘리면 오류도 증가합니다.
  • new_error < Original_error, 기울기는 음수입니다. 즉, 이 가중치를 늘리면 오류가 줄어듭니다.
  • 크기는 이 가중치의 변화에 ​​대해 오류가 얼마나 민감한지 알려줍니다.

    • 무게 재설정:
   weight[feature_index] -= step_size

무게를 바꾸면 어떻게 되는지 테스트 중이었기 때문에 무게를 원래 값으로 되돌렸습니다.

  • 그라디언트 반환:
   return gradient

이 가중치에 대해 계산된 기울기를 반환합니다.

This is called "numerical gradient calculation" or "finite difference method". We're approximating the gradient instead of calculating it analytically.

Let's update the weights

Now that we have our gradients, we can push our weights in the opposite direction of the gradient by subtracting the gradient.

weights[i] -= gradients[i]

If our gradient is too large, we could easily overshoot our minimum by updating our weight too much. To fix this, we can multiply the gradient by some small number:

learning_rate = 0.00001
weights[i] -= learning_rate*gradients[i]

And so here is how we do it for all of the weights:

def gradient_descent(data, learning_rate=0.00001, num_iterations=1000):
    weights = [0, 0, 0]  # Start with zero weights

    for _ in range(num_iterations):
        gradients = [
            calculate_gradient(weights, data, 0), # sqft
            calculate_gradient(weights, data, 1), # bedrooms
            calculate_gradient(weights, data, 2)  # bathrooms
        ]

        # Update each weight
        for i in range(3):
            weights[i] -= learning_rate * gradients[i]

        if _ % 100 == 0:
            error = calculate_mean_squared_error(weights, data)
            print(f"Iteration {_}, Error: {error}, Weights: {weights}")

    return weights

Finally, we have our weights!

Interpreting the Model

Once we have our trained weights, we can use them to interpret our model:

  • The weight for 'sqft' represents the price increase per square foot.
  • The weight for 'bedrooms' represents the price increase per additional bedroom.
  • The weight for 'baths' represents the price increase per additional bathroom.

For example, if our trained weights are [100, 10000, 15000], it means:

  • Each square foot adds $100 to the home price.
  • Each bedroom adds $10,000 to the home price.
  • Each bathroom adds $15,000 to the home price.

Linear models, despite their simplicity, are powerful tools in machine learning. They provide a foundation for understanding more complex algorithms and offer interpretable insights into real-world problems.

위 내용은 소프트웨어 엔지니어를 위한 머신러닝의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.