Mô Hình Hồi Quy Tuyến Tính Với PyTorch: Hướng Dẫn Thực Hành

1. Nhập thư viện cần thiết

import torch
import matplotlib.pyplot as plt
import random
Sử dụng PyTorch cho xử lý tensor và tính toán, matplotlib cho trực quan hóa, random để hỗ trợ ngẫu nhiên hóa dữ liệu.

2. Tạo dữ liệu mẫu

def generate_sample_data(weights, bias, num_samples):
    x = torch.normal(0, 2, (num_samples, len(weights)))
    y = torch.matmul(x, weights) + bias
    y += torch.normal(0, 0.01, y.shape)
    return x, y

3. Khởi tạo dữ liệu và kiểm tra

sample_size = 500
real_weights = torch.tensor([7.8, 1.5, 3.2, 4.5])
real_bias = torch.tensor(0.8)
X, Y = generate_sample_data(real_weights, real_bias, sample_size)
plt.scatter(X[:, 0], Y, 1)
plt.show()

4. Cung cấp dữ liệu theo batch

def data_loader(features, labels, batch_size):
    indices = list(range(len(labels)))
    random.shuffle(indices)
    for start in range(0, len(labels), batch_size):
        batch_indices = indices[start:start + batch_size]
        yield features[batch_indices], labels[batch_indices]

batch_size = 32

5. Định nghĩa hàm cơ bản

def predict(features, weights, bias):
    return torch.matmul(features, weights) + bias

def mean_absolute_error(predictions, targets):
    return torch.sum(torch.abs(predictions - targets)) / len(targets)

def stochastic_gradient_descent(parameters, learning_rate):
    with torch.no_grad():
        for param in parameters:
            param -= param.grad * learning_rate
            param.grad.zero_()

6. Khởi tạo tham số

learning_rate = 0.005
initial_weights = torch.normal(0, 0.02, real_weights.shape, requires_grad=True)
initial_bias = torch.tensor(0.0, requires_grad=True)

7. Huấn luyện mô hình

epochs = 100
for epoch in range(epochs):
    total_loss = 0
    for batch_x, batch_y in data_loader(X, Y, batch_size):
        predictions = predict(batch_x, initial_weights, initial_bias)
        loss = mean_absolute_error(predictions, batch_y)
        loss.backward()
        stochastic_gradient_descent([initial_weights, initial_bias], learning_rate)
        total_loss += loss.item()
    print(f"Epoch {epoch+1:03d}: Loss = {total_loss:.6f}")

8. Đánh giá kết quả

print("Thực tế:", real_weights, real_bias)
print("Dự đoán:", initial_weights, initial_bias)

9. Trực quan hóa kết quả

feature_idx = 2
plt.plot(X[:, feature_idx].detach().numpy(), 
         (X[:, feature_idx] * initial_weights[feature_idx]).detach().numpy() + initial_bias.detach().numpy())
plt.scatter(X[:, feature_idx], Y, 1)
plt.show()

Thẻ: PyTorch Linear Regression Stochastic Gradient Descent Tensor Operations

Đăng vào ngày 31 tháng 5 lúc 16:12