Is there any problem with the calculation in the following code?
0 - Introduction
Welcome to the Foundations of Machine Learning (ECE5984_41) course!
This is the 3rd lab practice. From now on, you will going to implement Softmax regression, MLP
1. Packages
You have to install and use below packages for HW#2.
numpy: Fundamental package for matrix computation with python.
matplotlib: Package for visualization of the graph with python.
scikit-learn: Python module for machine learning built on top of SciPy
Do not use other machine learning packages in this homework, e.g., tensorflow, pytorch, jax, etc.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mplcolors
import sklearn.datasets as skdatasets
from sklearn.model_selection import train_test_split
def load_iris(normalize):
# import data
X, y = skdatasets.load_iris(return_X_y=True)
# only use 1st & 3rd features
X = X[:, [0, 2]]
if normalize:
X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)
return train_test_split(X, y, test_size=0.2, random_state=444)
def affine(x, w, b):
out = None
#########################################################################
# out variable. #
#########################################################################
# ******** START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ******** #
out = np.dot(x, w) + b
# ********* END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ********* #
cache = (x, w, b)
return out, cache
Assistant
User
한글로 번역해주세요.
Assistant
제공된 코드는 numpy를 사용하여 소프트맥스 회귀 모델과 다층 퍼셉트론(MLP)을 구축하고 훈련하는 다양한 측면을 다루고 있으며 상당히 포괄적입니다. 여기에 자세한 개요와 잠재적인 문제에 대한 논의가 있습니다.
발견된 잠재적 문제
소프트맥스의 수치 안정성:
소프트맥스 함수 구현은 수치 안정성을 위해 특성(axis=1)에 대해 입력 x의 최대값을 빼는 방식을 사용하고 있습니다. 이는 좋은 방법입니다.
그러나 이러한 변환은 일반적으로 충분하지만, 매우 큰 숫자는 지수화할 때 여전히 오버플로를 일으킬 수 있습니다. 지수화 전에 추가적인 검사나 클리핑을 하는 것이 더 안전할 수 있습니다.
그래디언트 검사:
affine_backward, Linear 클래스의 backward, 클래스의 와 같은 함수에서 계산된 그래디언트는 수치적 그래디언트 검사를 통해 올바르게 계산되었는지 확인해야 합니다. 특히 이러한 수동 구현에서는 그래디언트 검사가 제공되지 않았습니다.
def affine_backward(dout, cache):
x, w, b = cache
dx, dw, db = None, None, None
#########################################################################
# Compute the gradient w.r.t inputs, weights, and biases. Store each of #
# them in the dx, dw, db variable. #
#########################################################################
# ******** START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ******** #
dw = np.dot(x.T, dout)
db = np.sum(dout, axis=0)
dx = np.dot(dout, w.T)
# ********* END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ********* #
return dx, dw, db
def softmax(x):
yhat = None
#########################################################################
# Store the softmax scores in the yhat variable. #
#########################################################################
# ******** START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ******** #
x = x - np.max(x, axis=1)[:, None]
yhat = np.exp(x) / np.sum(np.exp(x), axis=1)[:, None]
# ********* END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ********* #
return yhat
def cross_entropy_loss(yhat, y, n_class):
# clip values to prevent divide by zero
yhat = np.clip(yhat, a_min=1e-7, a_max=1-1e-7)
loss = None
#########################################################################
# loss in the loss variable. Note that the yhat is the output of the #
# softmax function implemented above. #
#########################################################################
# ******** START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ******** #
loss = -np.mean(np.sum(np.log(yhat) * one_hot(y, n_class), axis=1))
# ********* END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ********* #
return loss
def cross_entropy_loss_and_grad(x, y, n_class):
yhat = softmax(x)
loss = cross_entropy_loss(yhat, y, n_class)
grad = yhat - one_hot(y, n_class)
return loss, grad
2.3. Train model
def train_softmax_regression(x_train, x_test, y_train, y_test, lr, epochs, log_every):
# set seed
np.random.seed(444)
# shape
_, in_features = x_train.shape
out_features = len(np.unique(y_train))
# initialize weights
w = np.random.rand(in_features, out_features)
b = np.zeros(out_features)
# begin training
for e in range(1, epochs+1):
# forward affine (out = wx + b)
out, cache = affine(x_train, w, b)
# compute cross-entropy loss and grad (dL/dout)
loss, dout = cross_entropy_loss_and_grad(out, y_train, out_features)
# backward affine
, dw, db = affine_backward(dout, cache)
# gradient descent
w -= lr * dw
b -= lr * db
# print log
if e % log_every == 0:
yhat = softmax(affine(x_test, w, b)[0])
accr = np.mean(np.argmax(yhat, axis=1) == y_test)
loss = cross_entropy_loss(yhat, y_test, out_features)
print(f'Epochs: {e}/{epochs}, loss (test): {loss:.4f}, accuracy (test): {accr:.4f}')
return w, b
w, b = train_softmax_regression(x_train, x_test, y_train, y_test, lr=1e-2, epochs=200, log_every=20)
def compute_decision_boundary(x, w, b, resolution):
x1, x2 = x[:, 0], x[:, 1]
x1_mesh = np.linspace(np.min(x1) - 0.1, np.max(x1) + 0.1, resolution)
x2_mesh = np.linspace(np.min(x2) - 0.1, np.max(x2) + 0.1, resolution)
x1_mesh, x2_mesh = np.meshgrid(x1_mesh, x2_mesh, indexing='xy')
x = np.c[x1_mesh.ravel(), x2_mesh.ravel()]
y_mesh = np.argmax(softmax(affine(x, w, b)[0]), axis=1)
y_mesh = y_mesh.reshape(resolution, resolution)
return x1_mesh, x2_mesh, y_mesh
x1_mesh, x2_mesh, y_mesh = compute_decision_boundary(x_test, w, b, resolution=500)
plot_iris(x_test, y_test, x1_mesh, x2_mesh, y_mesh)
Q1 (Linear layer): 4 points; 1 point each
class Linear:
def init(self, in_features, out_features, is_first=False):
#########################################################################
# TODO: Initialize the weights and biases of the linear layer. Store #
# the weights in the self.w variable and biases in the self.b variable. #
# Weights should be a 2d np.ndarray of shape (in_features, out_features)#
# and initialized from a Uniform ranged [0, 1]. Biases should be a 1d #
# np.ndarray of shape (out_features,) and initialized to zero. #
#########################################################################
# ******** START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ******** #
self.w = np.random.uniform(low=0, high=1, size=(in_features, out_features))
self.b = np.zeros(out_features)
# ********* END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ********* #
self.dw = None
self.db = None
self.is_first = is_first
def call(self, x):
out = None
self.input = x # cache for backward
#########################################################################
# TODO: Implement the forward pass for the linear layer. Compute the #
# affine transform of X and store the result in the out variable. #
#########################################################################
# ******** START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ******** #
# out = x @ self.w + self.b
out = np.dot(x, self.w) + self.b
# ********* END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ********* #
return out
def backward(self, dout):
#########################################################################
# TODO: Implement the backward pass for the linear layer. Store the #
# gradient of loss w.r.t weights (dL/dw) in the self.dw variable, and #
# the gradient of loss w.r.t biases (dL/db) in the self.db variable. #
#########################################################################
# ******** START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ******** #
self.dw = np.dot(self.input.T, dout)
self.db = np.sum(dout, axis=0)
# ********* END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ********* #
dx = None
#########################################################################
# TODO: Implement the backward pass for the linear layer. Store the #
# gradient of loss w.r.t inputs (dL/dx) in the dx variable. Note that #
# we compute dx, if this is not the first layer (i.e., if self.is_first #
# is False) #
#########################################################################
# ******** START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ******** #
if not self.is_first:
dx = np.dot(dout, self.w.T)
# ********* END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ********* #
return dx
Q2 (ReLU layer): 2 points; 1 point each
class ReLU:
def call(self, x):
self.input = x # cache for backward
out = None
#########################################################################
# TODO: Implement the forward pass of ReLU layer. Store the computed #
# values in the out variable #
#########################################################################
# ******** START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ******** #
out = np.maximum(0, x)
# ********* END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ********* #
return out
def backward(self, dout):
dx = None
#########################################################################
# TODO: Implement the backward pass of ReLU layer. Store the computed #
# values in the dx variable. Note that you can use self.input to #
# compute the gradients. #
#########################################################################
# ******** START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ******** #
dx = dout * (self.input > 0)
# ********* END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ********* #
return dx
MLP (no need to implement)
class MLP:
def init(self, features):
def setup_layers(features):
layers = [] # n: in_features, m: out_features
for i, (n, m) in enumerate(zip(features[:-1], features[1:])):
layers += [Linear(n, m, i==0), ReLU()]
del layers[-1]
return layers
self.layers = setup_layers(features)
def call(self, X):
for layer in self.layers:
X = layer(X)
return X
def backward(self, dout):
for layer in reversed(self.layers):
dout = layer.backward(dout)
Q3 (Cross-entropy layer): 2 points
class CrossEntropyLoss:
def init(self, n_class):
self.n_class = n_class
def call(self, x, y):
loss, grad = None, None
#########################################################################
# TODO: Compute the cross-entropy loss and its gradient without using #
# explicit loops. Store the loss in loss variable and the gradient in #
# grad variable. Please use the softmax and cross_entropy_loss function #
# implemented above. Hint: this function is equivalent to the #
# cross_entropy_loss_and_grad() implemented above. #
#########################################################################
# ******** START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ******** #
yhat = softmax(x)
loss = cross_entropy_loss(yhat, y, self.n_class)
grad = yhat - one_hot(y, self.n_class)
# ********* END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ********* #
return loss, grad
Q4 (Gradient descent): 2 points
class GradientDescent:
def init(self, layers, lr):
self.layers = layers
self.lr = lr
def step(self):
#########################################################################
# TODO: Implement the gradient descent algorithm. Note that self.layers #
# is a list of layers, where each of them could be either Linear or #
# ReLU. Since a ReLU layer doesn't have learnable parameters, we only #
# update the parameters of the Linear layers. Loop through self.layers #
# and update the parameters if the layer is instance of Linear class. #
#########################################################################
# ******** START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ******** #
for layer in self.layers:
if isinstance(layer, Linear):
layer.w -= self.lr * layer.dw
layer.b -= self.lr * layer.db
# ********* END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE) ********* #
main function (no need to implement)
def train_mlp(x_train, x_test, y_train, y_test, features, lr, epochs, log_every):
# set seed
np.random.seed(444)
# make a single linear layer
model = MLP(features)
# make optimizer
optim = GradientDescent(model.layers, lr)
# loss function
n_class = len(np.unique(y_train))
loss_fn = CrossEntropyLoss(n_class)
# begin training
for e in range(1, epochs+1):
# forward (linear layer)
out = model(x_train)
# compute cross-entropy loss and gradient w.r.t out
loss, dout = loss_fn(out, y_train)
# backward (linear layer)
model.backward(dout)
# gradient descent
optim.step()
# print log
if e % log_every == 0:
yhat = softmax(model(x_test))
loss = cross_entropy_loss(yhat, y_test, n_class)
accr = eval_fn(yhat, y_test)
print(f'Epochs: {e}/{epochs}, loss (test): {loss:.4f}, accuracy (test): {accr:.4f}')
return model
The code provided is quite comprehensive and covers various aspects of building and training both softmax regression models and multi-layer perceptrons (MLPs) using numpy. Here's a detailed overview and a discussion on potential issues:
Potential Issues Discovered
Numerical Stability in Softmax:
The softmax function implementation subtracts the maximum of the input x across features (axis=1) for numerical stability, which is good practice.
However, while the transformation is usually sufficient, very large numbers might still cause overflow when exponentiated. A safer approach could involve additional checks or clipping prior to the exponentiation.
Gradient Checking:
The gradients calculated in functions like affine_backward, Linear class's backward, and ReLU class's backward should be verified through numerical gradient checking to ensure they are computed correctly, especially in a manual implementation like this. Gradient checking wasn't provided in the setup.
Uniform Initialization:
The Linear class initializes weights uniformly between [0, 1], which could cause issues with learning dynamics, especially in deeper networks (although this might not significantly impact the smaller networks described here). Typically, weights are initialized to small random values, often scaled according to the input and output sizes (e.g., He or Xavier initialization), to prevent vanishing or exploding gradients.
Learning Rate Adjustment:
While a fixed learning rate is used (lr=1e-2), in practice, learning rates often require tuning. Techniques like learning rate decay or more advanced adaptive learning rate methods like Adam might yield better results, especially for more complex or deeper models.
5 with very few. Accuracy Calculation:
The trace of the output through logs checks model accuracy after updates, but more robust validation techniques, possibly involving a validation set aside from the test set, would be beneficial for a more accurate performance evaluation during model development.
Loss recalculation in Logging:
The loss is recalculated for the test set in the logging section of the train_softmax_regression and train_mlp functions. It's more efficient to use the loss calculated during the forward pass if available, to avoid recomputing it only for logging purposes.
Overall Code Quality
The code generally follows good practices in terms of structure and separation of concerns. Each major function and class is responsible for a distinct aspect of the machine learning workflow (e.g., data preparation, model layer definition, activation functions, loss calculations).
Comments and structured sections help in understanding the flow and purpose of different code blocks.
Enhancements
Implementing early stopping during training could prevent overfitting and unnecessary computations if the model performance degrades or does not improve on a held-out validation set.
Including more comments explaining the gradient computation steps in custom backward methods could improve maintainability and readability, aiding debugging and new feature implementation.
Conclusion
The code provided is functional for educational purposes and small-scale experiments. However, as model complexity or dataset size grows, enhancements in numerical stability, performance optimization, validation practices, and initialization techniques are recommended to ensure scalability and robustness.
ReLU
backward
균일 초기화:
Linear 클래스는 [0, 1] 범위에서 균일하게 가중치를 초기화하는데, 이는 특히 더 깊은 네트워크에서 학습 동역학에 문제를 일으킬 수 있습니다(비록 여기서 설명된 더 작은 네트워크에서는 크게 영향을 미치지 않을 수 있습니다). 일반적으로 가중치는 입력과 출력 크기에 따라 조정된 작은 무작위 값으로 초기화됩니다(예: He 또는 Xavier 초기화)하여 그래디언트 소실 또는 폭발을 방지합니다.
학습률 조정:
고정된 학습률(lr=1e-2)이 사용되지만, 실제로는 학습률을 조정해야 할 필요가 종종 있습니다. 학습률 감소 또는 Adam과 같은 더 고급적인 적응형 학습률 방법이 특히 더 복잡하거나 더 깊은 모델에 대해 더 나은 결과를 얻을 수 있습니다.
정확도 계산:
출력을 통한 로그 추적은 업데이트 후 모델 정확도를 확인하지만, 모델 개발 중 성능 평가를 위해 테스트 세트와 별도로 유효성 검사 세트를 사용하는 더 견고한 검증 기법이 유익할 것입니다.
로그 섹션에서의 손실 재계산:
train_softmax_regression 및 train_mlp 함수의 로깅 섹션에서 테스트 세트에 대한 손실이 재계산됩니다. 로깅 목적으로만 손실을 다시 계산하는 것보다는 사용 가능한 경우 전방 패스 중에 계산된 손실을 사용하는 것이 더 효율적입니다.
전반적인 코드 품질
코드는 구조와 관심사의 분리 측면에서 일반적으로 좋은 관행을 따릅니다. 각 주요 함수와 클래스는 기계 학습 워크플로의 다른 측면(예: 데이터 준비, 모델 레이어 정의, 활성화 함수, 손실 계산)에 대한 책임이 있습니다.
주석과 구조화된 섹션은 다양한 코드 블록의 흐름과 목적을 이해하는 데 도움이 됩니다.
개선 사항
훈련 중에 조기 중단을 구현하면 모델 성능이 저하되거나 개선되지 않는 경우 과적합과 불필요한 계산을 방지할 수 있습니다.
사용자 정의 역방향 메서드에서 그래디언트 계산 단계에 대한 더 많은 주석을 포함하면 유지 관리 및 가독성이 향상되어 디버깅 및 새 기능 구현에 도움이 됩니다.
결론
제공된 코드는 교육 목적 및 소규모 실험에는 기능적입니다. 그러나 모델 복잡성이나 데이터 세트 크기가 증가함에 따라 수치 안정성, 성능 최적화, 검증 관행 및 초기화 기법의 개선이 권장됩니다. 이는 확장성과 견고성을 보장하기 위해 필요합니다.