SK Networks Family AI bootcamp 강의노트

25일차 [ 선형회귀모델 ]

HyunJung_Jo 2025. 2. 19. 16:18

https://colab.research.google.com/drive/12ZX-VvwvKfQgNgAnXYCiuUwGLcLxGdDT#scrollTo=OVtiQNld0-nX

 

Google Colab Notebook

Run, share, and edit Python notebooks

colab.research.google.com

더보기

Okay, let's discuss what "proba" means in the context of machine learning, especially when dealing with classification models.

Understanding "Proba" (Probability) in Machine Learning

"Proba" is short for probability. In classification tasks, machine learning models often predict the probability of an input belonging to each of the possible classes.

Here's a breakdown:

  1. Classification Models: These models are designed to assign input data to specific categories or classes (e.g., classifying images as cats or dogs, emails as spam or not spam).
  2. Probability Scores: Instead of just giving a hard prediction (e.g., "this image is a cat"), classification models can output probability scores for each class. For example, the model might predict:
    • 80% probability that the image is a cat
    • 20% probability that the image is a dog
  3. "Proba" in Output: The term "proba" is often used to refer to these probability scores. You might see it in variable names (like pred_proba) or function names (like predict_proba) in machine learning libraries.
  4. Interpreting Proba: The probability scores represent the model's confidence in its prediction. Higher probability means the model is more certain about the classification.

In your code context:

While you haven't calculated or used "proba" explicitly in the provided code, it's important to understand that the output of your model (predictv1) contains values that can be interpreted as scores or activations for each class. To obtain actual probabilities, you would typically apply a function like softmax to these scores.

Example:

Let's say your model's output (predictv1) for a single input looks like this:

 

content_copy 
[0.2, 0.1, 0.8, 0.3, 0.6]
Use code with caution

These values are not probabilities yet. Applying softmax would transform them into probabilities that sum to 1, something like:

content_copy 
[0.12, 0.09, 0.37, 0.15, 0.27]
Use code with caution

Now, you could interpret these values as:

  • 12% probability of belonging to class 1
  • 9% probability of belonging to class 2
  • 37% probability of belonging to class 3 (highest probability, so the predicted class)
  • 15% probability of belonging to class 4
  • 27% probability of belonging to class 5

I hope this clarifies the meaning of "proba" and how it relates to your code! Let me know if you have any other questions.

 

이 코드는 PyTorch를 사용하여 구현된 신경망 클래스 NeuralNetworkV2입니다. 이 클래스는 주로 이미지 분류와 같은 작업에서 사용될 수 있으며, 아래는 각 부분에 대한 설명입니다:

클래스 초기화 (__init__ 메서드):

feature_size: 입력 특성의 크기입니다. 예를 들어, 이미지라면 이미지의 픽셀 수가 되며, 28x28 크기의 흑백 이미지라면 784가 됩니다.
target_size: 출력 클래스를 나타내며, 모델이 분류할 수 있는 클래스의 수입니다.
hidden_size: 은닉층의 뉴런 수를 결정합니다. 기본값은 512입니다.
self.flatten은 입력 텐서를 flatten, 즉 2D 행렬의 형태를 1D 벡터로 변경하는 역할을 합니다.
self.linear_relu_stack는 nn.Sequential를 사용하여 여러 레이어를 순서대로 연결한 신경망입니다.
신경망 구조:

첫 번째 nn.Linear: 입력의 크기(feature_size)에서 은닉층(hidden_size)으로 변환하는 연산을 수행합니다.
nn.ReLU: 활성화 함수로, 해당 레이어를 통과한 결과를 비선형 변환하여 다음 레이어로 보냅니다.
두 번째 nn.Linear: 첫 번째 은닉층에서 두 번째 은닉층으로 변환합니다.
nn.ReLU: 두 번째 활성화 함수.
세 번째 nn.Linear: 은닉층에서 최종 출력층(target_size)으로 변환합니다.
최종 출력은 logits, 즉 모델의 예측 결과입니다.
forward 메서드:

입력 데이터 features는 먼저 flattened되며, 이를 통해 모델의 예측 단계가 시작됩니다.
순차적으로 설정된 레이어들을 통과하면서 최종 예측값 logits을 출력합니다.
이 클래스는 다양한 입력 및 출력 크기에 유연하게 적용될 수 있도록 설계되었으며, 쉽게 재사용할 수 있는 구조를 가지고 있습니다. 이미지 분류 외에도 입력 크기와 출력 크기를 적절히 조정하면 다양한 응용에 적용할 수 있습니다.

Copy
Regenerate
더보기

좋은 질문입니다! modelv2.linear_relu_stack[0].weight.shape가 (784, 512)가 아니라 (512, 784)인 이유는 PyTorch에서 선형 레이어 (nn.Linear)의 가중치 행렬이 출력 특성 수 x 입력 특성 수로 정의되기 때문입니다.

다시 말해, 가중치 행렬의:

  • : 다음 레이어의 뉴런 (노드) 수, 즉 출력 특성 수를 나타냅니다.
  • : 이전 레이어의 뉴런 (노드) 수, 즉 입력 특성 수를 나타냅니다.

modelv2의 첫 번째 레이어는 nn.Linear(feature_size, hidden_size)로 정의되었으며, 여기서 feature_size는 784 (28x28 이미지를 평평하게 만든 것)이고 hidden_size는 512입니다.

따라서 이 레이어의 가중치 행렬은 다음과 같이 구성됩니다.

  • 출력 특성 수: 512 (hidden_size)
  • 입력 특성 수: 784 (feature_size)

결과적으로 modelv2.linear_relu_stack[0].weight.shape는 (512, 784)가 됩니다.

간단히 요약하면:

PyTorch에서 선형 레이어의 가중치 행렬은 (출력 특성 수, 입력 특성 수) 형태를 가지므로 modelv2의 첫 번째 레이어에서는 (512, 784)가 됩니다. 이는 다음 레이어로 전달될 512개의 특성을 생성하기 위해 784개의 입력 특성에 가중치를 적용하는 방식을 나타냅니다.

 

 

https://colab.research.google.com/drive/1s_z06s89sRQcbgp-zc_cN1uccM_vWgV1#scrollTo=01AeuBqB2_OB

 

Google Colab Notebook

Run, share, and edit Python notebooks

colab.research.google.com

 

Remind

  • cpu에서 gpu로 모델 학습시 tensor를 gpu에 올려야 한다. 다시 numpy로 변환시 cpu로 내려야 한다.
model = LinearRegressionModelV1().to(device)
torch.manual_seed(42)
optimizer = torch.optim.SGD(params=model.parameters(),lr=0.01)

torch.manual_seed(42)
epochs = 100 # 전체 데이터를 학습하는 횟수

train_loss_list = []
test_loss_list = []
epoch_list = []

for epoch in range(epochs):
  ################################################
  # Traing(학습)
  ################################################
  model.train() # 학습모드
  # 순전파
  y_pred = model(X_train.to(device)) # 학습을 통한 예측값 # [cpu -> gpu: 모든 데이터를 gpu에 올리기  ]
  loss = loss_fn(y_pred, y_train.to(device)) # 오차값 # [cpu -> gpu]
  # 역전파
  optimizer.zero_grad()
  loss.backward()
  optimizer.step()

  ################################################
  # Testing(평가)
  ################################################
  model.eval() # 평가모드

  with torch.inference_mode():
    test_pred = model(X_test.to(device))
    test_loss = loss_fn(test_pred, y_test.to(device).type(torch.float))

  if epoch % 10 == 0:
    print(f"Epoch: {epoch} | MAE Train loss: {loss} | MAE Test loss: {test_loss}")
    epoch_list.append(epoch)
    train_loss_list.append(loss.detach().cpu().numpy()) # [gpu -> cpu: GPU Tensor to CPU numpy ]
    test_loss_list.append(test_loss.detach().cpu().numpy())
    """
    detach()는 텐서를 계산 그래프에서 분리하여, 
    해당 텐서의 연산이 모델 학습에 영향을 주지 않도록 합니다.
    즉, 그래프 추적 없이 텐서 데이터를 안전하게 사용하고, 
    NumPy 배열로 변환할 수 있게 해줍니다.
    """
model.eval() # 평가 모드
with torch.inference_mode():
  y_pred = model(X_test.to(device)) # to gpu
plot_predictions(predictions=y_pred.cpu().numpy()) # to cpu