Here's an implementation of a multi-class logistic regression from scratch using PyTorch that meets your specifications:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader, random_split
import numpy as np
# Function to set random seed for reproducibility
def set_random_seed(seed):
torch.manual_seed(seed)
np.random.seed(seed)
# Custom Dataset to handle the data structure
class CustomDataset(Dataset):
def __init__(self, x, y, sample_weight):
self.x = x
self.y = y
self.sample_weight = sample_weight
def __len__(self):
return len(self.y)
def __getitem__(self, idx):
return self.x[idx], self.y[idx], self.sample_weight[idx]
# Logistic Regression Model
class LogisticRegressionModel(nn.Module):
def __init__(self, input_dim, output_dim):
super(LogisticRegressionModel, self).__init__()
self.linear = nn.Linear(input_dim, output_dim)
def forward(self, x):
return self.linear(x)
# Main Logistic Regression class
class LogisticRegression:
def __init__(self, random_seed=None):
self.model = None
self.random_seed = random_seed
self.data = {}
def fit(self, X, y, sample_weight=None, num_epochs=100, learning_rate=0.01, batch_size=32):
# Set random seed for reproducibility
if self.random_seed is not None:
set_random_seed(self.random_seed)
# Convert input data to tensors
X = torch.tensor(X).float()
y = torch.tensor(y).long()
if sample_weight is not None:
sample_weight = torch.tensor(sample_weight).float()
else:
sample_weight = torch.ones(len(y)).float()
# Determine input and output dimensions
input_dim = X.shape[1]
output_dim = torch.unique(y).numel()
# Initialize the model
self.model = LogisticRegressionModel(input_dim, output_dim)
# Prepare the data dictionary as per HF dataset structure
self.data['train'] = {
'x': X,
'y': y,
'sample_weight': sample_weight
}
# Sample 0.1% of the training data for early stopping validation
num_samples = len(y)
num_val_samples = max(1, int(0.001 * num_samples))
num_train_samples = num_samples - num_val_samples
# Ensure reproducibility in sampling
indices = torch.randperm(num_samples, generator=torch.Generator().manual_seed(self.random_seed))
train_indices = indices[:num_train_samples]
val_indices = indices[num_train_samples:]
self.data['early_stopping_validation'] = {
'x': X[val_indices],
'y': y[val_indices],
'sample_weight': sample_weight[val_indices]
}
# Create datasets and dataloaders
train_dataset = CustomDataset(
X[train_indices], y[train_indices], sample_weight[train_indices]
)
val_dataset = CustomDataset(
self.data['early_stopping_validation']['x'],
self.data['early_stopping_validation']['y'],
self.data['early_stopping_validation']['sample_weight']
)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
# Define loss function and optimizer
criterion = nn.CrossEntropyLoss(reduction='none') # Use 'none' to apply sample weights manually
optimizer = optim.SGD(self.model.parameters(), lr=learning_rate)
# Variables for early stopping
best_val_loss = float('inf')
patience = 5 # Number of epochs to wait before early stopping
counter = 0
# Training loop
for epoch in range(num_epochs):
# Training phase
self.model.train()
total_train_loss = 0.0
for xb, yb, wb in train_loader:
optimizer.zero_grad()
outputs = self.model(xb)
loss = criterion(outputs, yb)
# Apply sample weights
loss = loss * wb
loss = loss.mean()
loss.backward()
optimizer.step()
total_train_loss += loss.item() * xb.size(0)
avg_train_loss = total_train_loss / num_train_samples
# Validation phase
self.model.eval()
total_val_loss = 0.0
with torch.no_grad():
for xb, yb, wb in val_loader:
outputs = self.model(xb)
loss = criterion(outputs, yb)
# Apply sample weights
loss = loss * wb
loss = loss.mean()
total_val_loss += loss.item() * xb.size(0)
avg_val_loss = total_val_loss / num_val_samples
# Early stopping check
if avg_val_loss < best_val_loss:
best_val_loss = avg_val_loss
counter = 0
best_model_state = self.model.state_dict()
else:
counter += 1
if counter >= patience:
print(f"Early stopping at epoch {epoch + 1}")
break
print(f"Epoch {epoch + 1}/{num_epochs} - "
f"Train Loss: {avg_train_loss:.4f} - Val Loss: {avg_val_loss:.4f}")
# Load the best model state
self.model.load_state_dict(best_model_state)
def predict(self, X):
self.model.eval()
X = torch.tensor(X).float()
with torch.no_grad():
outputs = self.model(X)
_, predicted = torch.max(outputs, 1)
return predicted.numpy()
def predict_proba(self, X):
self.model.eval()
X = torch.tensor(X).float()
with torch.no_grad():
outputs = self.model(X)
probabilities = nn.functional.softmax(outputs, dim=1)
return probabilities.numpy()
Explanation
-
Random Seed: The set_random_seed function sets the random seed for both NumPy and PyTorch to ensure reproducibility.
-
Data Handling: The data is structured to mimic the Hugging Face dataset format:
self.data['train'] = {
'x': X,
'y': y,
'sample_weight': sample_weight
}
-
Sample Weighting: The sample_weight parameter is used to weight the loss function during training. If no sample weights are provided, a tensor of ones is used.
-
Determining Layer Sizes: The input dimension is determined by input_dim = X.shape[1], and the output dimension (number of classes) is determined by output_dim = torch.unique(y).numel().
-
Model Definition: A simple linear layer is used for the multi-class logistic regression.
self.model = LogisticRegressionModel(input_dim, output_dim)
-
Early Stopping Validation Set: 0.1% of the training data is sampled for early stopping validation.
num_val_samples = max(1, int(0.001 * num_samples))
-
Data Loaders: Custom datasets and data loaders are created for both training and validation data.
-
Loss Function and Optimizer: Cross-entropy loss with reduction='none' is used to manually apply sample weights. Stochastic Gradient Descent (SGD) is used as the optimizer.
-
Training Loop: The model is trained for a specified number of epochs, with early stopping implemented based on validation loss.
-
Predictions: The predict method returns the class labels, while predict_proba returns the class probabilities.
Usage Example
# Example data
import numpy as np
# Sample data (Replace with your actual data)
X_sample = np.random.rand(1000, 10) # 1000 samples, 10 features
y_sample = np.random.randint(0, 3, size=(1000,)) # 3 classes
sample_weight_sample = np.random.rand(1000)
# Initialize the model with a random seed for reproducibility
model = LogisticRegression(random_seed=42)
# Fit the model
model.fit(X_sample, y_sample, sample_weight=sample_weight_sample)
# Make predictions
predictions = model.predict(X_sample)
# Predict probabilities
probabilities = model.predict_proba(X_sample)
Notes
-
Reproducibility: The random_seed parameter ensures that data shuffling and other stochastic processes produce the same result every time.
-
HF Dataset Structure: The data is stored in a dictionary mimicking the Hugging Face datasets structure, which can be helpful if you plan to integrate with other libraries or tools that use this format.
-
Early Stopping: You can adjust the patience parameter or the percentage of data used for validation to better suit your dataset size.
-
Batch Size and Learning Rate: The batch_size and learning_rate parameters can be adjusted according to your needs.
Remarks
This implementation provides a customizable and extensible base for multi-class logistic regression using PyTorch, adhering to your specified requirements.