【Guest Post】Essential Tools for blueqat Interns and Key Points of Mathematical Optimization
This is a continuation of the previous article. We will look at practical model workflows, starting from very basic concepts. Although we will eventually use more advanced models, linear regression and models such as Random Forest and XGboost frequently appear in practical applications. Advanced time-series neural networks are also common, so it is necessary to master the fundamentals properly.
The third part is here
【Guest Post】Summary of blueqat Intern Course: LLM, Diffusion Models, and Tensor Networks
Session 3: From Regression Models to Time-Series AI
In practical applications, there are many scenarios involving "continuous numerical values," such as sales forecasting and stock price analysis. This time, we will experience their evolution using the same data, ranging from classical methods to the modern mainstream Transformer.
1. Fundamentals: Regression Models (Linear & Polynomial)
All basics involve fitting a "line (function)" to the data.
Linear and Polynomial Regression
- Linear Regression: The simplest straight line. It is suitable for capturing overall trends such as an "upward slope."
- Polynomial Regression: By increasing inputs to \(x, x^2, x^3, \dots\) (feature transformation), the algorithm expresses a "curve" while remaining linear.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline
# 1. Generate common data (noisy sine wave)
np.random.seed(42)
x_base = np.linspace(0, 10, 100).reshape(-1, 1)
y_base = np.sin(x_base).flatten() + np.random.normal(0, 0.1, 100)
# Prepare models
lin_reg = LinearRegression().fit(x_base, y_base)
poly_reg = Pipeline([
("poly", PolynomialFeatures(degree=3)),
("linreg", LinearRegression())
]).fit(x_base, y_base)
# Visualization
plt.figure(figsize=(10, 5))
plt.scatter(x_base, y_base, alpha=0.5, label="Raw Data")
plt.plot(x_base, lin_reg.predict(x_base), label="Linear (1st deg)", color="red", linestyle="--")
plt.plot(x_base, poly_reg.predict(x_base), label="Polynomial (3rd deg)", color="green", linewidth=3)
plt.title("Step 1: Regression Basics")
plt.legend()
plt.show()
2. Evolution: RNN (Recurrent Neural Network)
While regression models only see "at that point," RNNs remember the "flow from the past."
How RNN Works
RNNs have a "memory room" called a "Hidden State" internally. Each time data is input, this memory is updated.
import torch
import torch.nn as nn
# Prepare data (predict next step from past 10 steps)
def make_sequences(data, seq_len=10):
X, Y = [], []
for i in range(len(data)-seq_len):
X.append(data[i:i+seq_len])
Y.append(data[i+seq_len])
return torch.FloatTensor(np.array(X)).unsqueeze(-1), torch.FloatTensor(np.array(Y)).unsqueeze(-1)
X_rnn, y_rnn = make_sequences(y_base)
# Model definition
class SimpleRNN(nn.Module):
def __init__(self):
super().__init__()
self.rnn = nn.RNN(1, 32, batch_first=True) # Increase memory capacity to 32
self.fc = nn.Linear(32, 1)
def forward(self, x):
out, _ = self.rnn(x)
return self.fc(out[:, -1, :])
model = SimpleRNN()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
# --- Important: Training Loop ---
for epoch in range(200): # Learn by iterating 200 times
model.train()
optimizer.zero_grad()
outputs = model(X_rnn)
loss = criterion(outputs, y_rnn)
loss.backward()
optimizer.step()
if (epoch+1) % 50 == 0:
print(f'Epoch [{epoch+1}/200], Loss: {loss.item():.4f}')
# Inference
model.eval()
y_rnn_pred = model(X_rnn).detach().numpy()
plt.figure(figsize=(10, 4))
plt.plot(y_base[10:], label="Actual", color="gray", alpha=0.5)
plt.plot(y_rnn_pred, label="RNN Predicted (After Training)", color="orange", linewidth=2)
plt.title("RNN: High-Precision Sequence Prediction")
plt.legend()
plt.show()
3. Latest: Transformer (Self-Attention)
RNNs had the drawback of forgetting old information easily (vanishing gradient). The Transformer solved this issue.
Attention: Shining a Spotlight
Instead of relying on "order," Transformers directly look at "which part of the past is important for the current prediction." This is called "Attention."
# --- 1. Define Transformer Model ---
class TimeSeriesTransformer(nn.Module):
def __init__(self, input_dim=1, model_dim=32, nhead=4, num_layers=2):
super().__init__()
# Convert 1D value to vector of model_dim dimensions
self.input_fc = nn.Linear(input_dim, model_dim)
# TransformerEncoderLayer: Layer containing Multi-head Attention
encoder_layer = nn.TransformerEncoderLayer(
d_model=model_dim,
nhead=nhead,
batch_first=True,
dropout=0.1
)
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
# Layer to output a single predicted value
self.output_fc = nn.Linear(model_dim, 1)
def forward(self, x):
# x: [Batch, Seq_len, 1]
x = self.input_fc(x)
# Pass through Transformer
# "Correlations" between data points are calculated all at once here
x = self.transformer(x)
# Use only the data from the last time step to predict the future
return self.output_fc(x[:, -1, :])
# --- 2. Execute Training ---
tf_model = TimeSeriesTransformer()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(tf_model.parameters(), lr=0.005) # Smaller learning rate stabilizes Transformers
for epoch in range(200):
tf_model.train()
optimizer.zero_grad()
outputs = tf_model(X_rnn)
loss = criterion(outputs, y_rnn)
loss.backward()
optimizer.step()
if (epoch+1) % 50 == 0:
print(f'Epoch [{epoch+1}/200], Loss: {loss.item():.4f}')
# --- 3. Inference and Visualization ---
tf_model.eval()
with torch.no_grad():
y_tf_pred = tf_model(X_rnn).numpy() # Convert to numpy here (no detach needed)
plt.figure(figsize=(10, 4))
plt.plot(y_base[10:], label="Actual", color="gray", alpha=0.5)
plt.plot(y_tf_pred, label="Transformer Predicted", color="purple", linewidth=2)
plt.title("Transformer: High-Precision Sequence Prediction")
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
Session 4: The Evolution of Image Recognition — MLP, CNN, and Vision Transformer
The history of image recognition tasks is also the history of "how models preserve spatial information within images." Using the same MNIST (handwritten digits) dataset, we will compare how three generations of models "see" images and learn their respective practical advantages.
1. Data Preparation (Common)
All models use common data. MNIST consists of \(28 \times 28\) pixel grayscale images.
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
# Device settings (use GPU if available)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Load MNIST data
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True)
testloader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST(root='./data', train=False, transform=transform),
batch_size=5, shuffle=True
)2. First Generation: MLP (Multilayer Perceptron)
"Treating images as a one-dimensional sequence of numbers"
MLPs are the most basic networks. They receive images as \(784\) (\(= 28 \times 28\)) "just a sequence of numbers."
- Design Philosophy: All pixels contribute to all outputs (fully connected).
- Practical Nature: Highly accurate if the image is fixed in the center, but extremely weak to "positional shifts."
- Visualization Perspective: If you revert the learned weights back to , you can see a template resembling the "average shadow" of that digit.
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Flatten(),
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10)
)
def forward(self, x): return self.net(x)3. Second Generation: CNN (Convolutional Neural Network)
"Scanning local patterns (lines and corners)"
CNNs extract features while preserving spatial information by sliding a small "filter (kernel)" over the image.
- Design Philosophy: "Local Receptive Fields." Instead of viewing everything at once, they hierarchically stack connections between pixels in narrow ranges (edges or patterns).
- Practical Nature: Since objects can be detected regardless of where they are located (translation invariance), it is the practical standard for image recognition.
- Visualization Perspective: Looking at the internal "feature maps" confirms that the image has been processed like edge extraction.
class CNN(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(1, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2),
nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2),
nn.Flatten(),
nn.Linear(64*7*7, 128), nn.ReLU(),
nn.Linear(128, 10)
)
def forward(self, x): return self.net(x)4. Third Generation: ViT (Vision Transformer)
"Combining puzzle pieces to measure overall relevance"
This is the latest method applying the Transformer, successful in natural language processing, to images. It divides the image into small "patches" and calculates which other patches each patch is related to ("Attention").
- Design Philosophy: "Self-Attention." While CNNs only look "nearby," ViT considers the connections between all patches in the entire image at once.
- Practical Nature: When trained on very large-scale data, it exhibits performance surpassing CNNs.
- Visualization Perspective: The image is divided into a grid (patches), showing that the model understands the "composition of the digit" as a puzzle.
class SimpleViT(nn.Module):
def __init__(self):
super().__init__()
self.patch_size = 7 # Dividing 28x28 into 7x7 size patches results in a total of 16 patches (4x4)
self.patch_embed = nn.Linear(7*7, 64)
encoder_layer = nn.TransformerEncoderLayer(d_model=64, nhead=8, batch_first=True)
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=3)
self.fc = nn.Linear(64, 10)
def forward(self, x):
# Expand image into patches
p = x.unfold(2, 7, 7).unfold(3, 7, 7).reshape(x.size(0), -1, 49)
x = self.patch_embed(p)
x = self.transformer(x)
return self.fc(x.mean(dim=1)) # Judge based on the average of all patches5. Executing Learning and Inference Comparison
We actually train the three models and visualize "where they get the answer right and where they make mistakes" with multiple test images.
# Training loop (simplified for interns)
def train_and_eval():
models = {"MLP": MLP(), "CNN": CNN(), "ViT": SimpleViT()}
results = {}
for name, model in models.items():
print(f"Training {name}...")
model.to(device)
opt = optim.Adam(model.parameters(), lr=0.001)
crit = nn.CrossEntropyLoss()
# Execute only 2 epochs
for _ in range(2):
for imgs, lbs in trainloader:
imgs, lbs = imgs.to(device), lbs.to(device)
opt.zero_grad()
crit(model(imgs), lbs).backward()
opt.step()
model.eval()
results[name] = model
# Compare using 5 test images
imgs, lbs = next(iter(testloader))
imgs = imgs.to(device)
fig, axes = plt.subplots(3, 5, figsize=(15, 9))
for idx, (name, m) in enumerate(results.items()):
with torch.no_grad():
preds = m(imgs).argmax(dim=1).cpu().numpy()
for i in range(5):
axes[idx, i].imshow(imgs[i][0].cpu().numpy(), cmap='gray')
color = "green" if preds[i] == lbs[i] else "red"
axes[idx, i].set_title(f"{name}: {preds[i]}", color=color)
axes[idx, i].axis('off')
plt.tight_layout()
plt.show()
train_and_eval()
✅ Summary of Chapter 4
- MLP is the simplest, but because it relies too much on "pixel location," it has limitations for diverse images in practice.
- CNN efficiently extracts "local patterns," reigning as the basic tool for image recognition.
- ViT focuses on "relationships between patches" and possesses the most powerful expressive power if sufficient computational resources are available.
In practice, the standard flow is to start by "creating a baseline with CNN" and then consider "ViT" depending on task difficulty and data volume.