I'll extend the implementation to include the Hammerstein input nonlinearity with the specified form. Here's the complete solution:
import streamlit as st
import torch
import torch.nn as nn
import numpy as np
from typing import List, Tuple, Dict, Optional
from dataclasses import dataclass
import matplotlib.pyplot as plt
@dataclass
class NonlinearityParams:
a: float
x0: float
@dataclass
class TTCoreConfig:
rank_left: int
rank_right: int
@dataclass
class TTModelConfig:
input_features: int
output_features: int
tt_ranks: List[int]
learning_rate: float
l1_weight: float
max_epochs: int
fir_taps: int = 60
def create_basis_functions(n_basis: int = 10) -> List[callable]:
"""Create basis functions for approximating the nonlinearity"""
basis_functions = []
# Polynomial basis
for i in range(n_basis // 2):
basis_functions.append(lambda x, i=i: x ** i)
# Sigmoid-like basis
for i in range(n_basis // 2):
alpha = 0.5 + i * 2.0
basis_functions.append(lambda x, alpha=alpha: torch.sigmoid(alpha * (x - 0.5)))
return basis_functions
def hammerstein_nonlinearity(x: torch.Tensor, a: torch.Tensor, x0: torch.Tensor) -> torch.Tensor:
"""Compute the Hammerstein nonlinearity g(x)"""
eps = 1e-8
numerator = 1 - torch.exp(-a * (x - x0))
denominator = 1 - torch.exp(-a * (1 - x0)) + eps
return numerator / denominator
class InputNonlinearity(nn.Module):
def __init__(self, n_inputs: int):
super().__init__()
self.a = nn.Parameter(torch.ones(n_inputs) * 2.0)
self.x0 = nn.Parameter(torch.ones(n_inputs) * 0.5)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# Apply nonlinearity to each input dimension
result = torch.zeros_like(x)
for i in range(x.shape[1]):
result[:, i] = hammerstein_nonlinearity(x[:, i], self.a[i], self.x0[i])
return result
class FIRModel(nn.Module):
def __init__(self, n_inputs: int, n_outputs: int, n_taps: int):
super().__init__()
self.n_taps = n_taps
self.weights = nn.Parameter(torch.randn(n_inputs * n_taps, n_outputs) * 0.01)
def forward(self, x: torch.Tensor) -> torch.Tensor:
batch_size, seq_len, n_features = x.shape
# Create time-delayed features
delayed_features = []
for tap in range(self.n_taps):
if tap == 0:
delayed_features.append(x)
else:
padded = torch.cat([torch.zeros(batch_size, tap, n_features), x[:, :-tap, :]], dim=1)
delayed_features.append(padded)
# Stack all delayed features
X_delayed = torch.cat(delayed_features, dim=-1)
# Apply FIR weights
return torch.matmul(X_delayed, self.weights)
def optimize_nonlinearity_and_fir(
X: torch.Tensor,
y: torch.Tensor,
n_taps: int,
l1_weight: float,
max_epochs: int,
progress_bar
) -> Tuple[InputNonlinearity, FIRModel, List[float]]:
"""First stage: optimize input nonlinearity with FIR model"""
n_inputs = X.shape[1] if len(X.shape) == 2 else X.shape[2]
n_outputs = y.shape[1] if len(y.shape) == 2 else y.shape[2]
# Initialize models
nonlinearity = InputNonlinearity(n_inputs)
fir_model = FIRModel(n_inputs, n_outputs, n_taps)
# Optimizer
optimizer = torch.optim.Adam(
list(nonlinearity.parameters()) + list(fir_model.parameters()),
lr=0.01
)
mse_loss = nn.MSELoss()
losses = []
# Ensure proper dimensions
if len(X.shape) == 2:
X = X.unsqueeze(1) # Add sequence dimension
if len(y.shape) == 2:
y = y.unsqueeze(1)
for epoch in range(max_epochs):
optimizer.zero_grad()
# Apply nonlinearity
X_nonlinear = nonlinearity(X)
# Apply FIR model
y_pred = fir_model(X_nonlinear)
# Calculate losses
mse = mse_loss(y_pred, y)
l1_reg = torch.sum(torch.abs(fir_model.weights))
loss = mse + l1_weight * l1_reg
# Backward pass
loss.backward()
optimizer.step()
losses.append(loss.item())
progress_bar.progress((epoch + 1) / max_epochs)
return nonlinearity, fir_model, losses
class TTCore(nn.Module):
def __init__(self, config: TTCoreConfig):
super().__init__()
# Each dimension has length 2 for monomial representation (1, x_i)
self.core = nn.Parameter(
torch.randn(config.rank_left, 2, 2, config.rank_right) * 0.1
)
def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
# input_tensor shape: (batch, 2)
return torch.einsum('ijkl,bj->bikl', self.core, input_tensor)
class TensorTrainModel(nn.Module):
def __init__(self, config: TTModelConfig, nonlinearity: InputNonlinearity):
super().__init__()
self.config = config
self.nonlinearity = nonlinearity
# Create cores
self.cores = nn.ModuleList([
TTCore(TTCoreConfig(
rank_left=config.tt_ranks[i],
rank_right=config.tt_ranks[i+1]
)) for i in range(config.input_features)
])
def create_monomial_features(self, x: torch.Tensor) -> torch.Tensor:
"""Create monomial features (1, x_i) for each input"""
batch_size = x.shape[0]
features = []
for i in range(x.shape[1]):
# Create [1, x_i] for each dimension
ones = torch.ones(batch_size, 1)
x_i = x[:, i:i+1]
monomial = torch.cat([ones, x_i], dim=1)
features.append(monomial)
return features
def forward(self, x: torch.Tensor) -> torch.Tensor:
# Apply nonlinearity
x_nonlinear = self.nonlinearity(x)
# Create monomial features
monomial_features = self.create_monomial_features(x_nonlinear)
# Initialize with first core
current = self.cores[0](monomial_features[0])
current = current.squeeze(1) # Remove singleton dimension
# Contract with remaining cores
for i in range(1, len(self.cores)):
# Apply core to monomial features
core_output = self.cores[i](monomial_features[i])
# Contract tensors
current = torch.einsum('bij,bjkl->bikl', current, core_output)
# Reshape for next iteration
if i < len(self.cores) - 1:
current = current.reshape(current.shape[0], current.shape[1], -1)
# Final output
return current.squeeze()
def train_tt_model(
model: TensorTrainModel,
train_data: Dict[str, torch.Tensor],
config: TTModelConfig,
progress_bar
) -> List[float]:
optimizer = torch.optim.Adam(model.parameters(), lr=config.learning_rate)
mse_loss = nn.MSELoss()
losses = []
X, y = train_data['X'], train_data['y']
for epoch in range(config.max_epochs):
optimizer.zero_grad()
# Forward pass
y_pred = model(X)
# Calculate losses
mse = mse_loss(y_pred, y)
l1_reg = sum(p.abs().sum() for p in model.cores.parameters())
loss = mse + config.l1_weight * l1_reg
# Backward pass
loss.backward()
optimizer.step()
losses.append(loss.item())
progress_bar.progress((epoch + 1) / config.max_epochs)
return losses
def create_streamlit_ui():
st.title("Tensor Train System Identification with Hammerstein Nonlinearity")
# Model configuration inputs
st.header("Model Configuration")
col1, col2 = st.columns(2)
with col1:
input_features = st.number_input("Input Features", min_value=1, value=4)
output_features = st.number_input("Output Features", min_value=1, value=1)
with col2:
fir_taps = st.number_input("FIR Taps", min_value=1, value=60)
fir_l1_weight = st.number_input("FIR L1 Weight", value=0.01, format="%.4f")
# TT-ranks input
ranks_input = st.text_input("TT-ranks (comma-separated)", "1,2,2,2,1")
tt_ranks = [int(r) for r in ranks_input.split(",")]
# Training parameters
col3, col4 = st.columns(2)
with col3:
learning_rate = st.number_input("TT Learning Rate", value=0.001, format="%.4f")
l1_weight = st.number_input("TT L1 Weight", value=0.001, format="%.4f")
with col4:
fir_epochs = st.number_input("FIR Training Epochs", min_value=1, value=200)
tt_epochs = st.number_input("TT Training Epochs", min_value=1, value=500)
# Data generation or upload
st.header("Data Input")
data_source = st.radio("Data Source", ["Generate Synthetic", "Upload CSV"])
if data_source == "Generate Synthetic":
n_samples = st.number_input("Number of Samples", min_value=100, value=1000)
if st.button("Generate Data"):
# Generate synthetic data
t = np.linspace(0, 10, n_samples)
X = np.column_stack([
np.sin(2 * np.pi * 0.5 * t),
np.cos(2 * np.pi * 0.3 * t),
np.sin(2 * np.pi * 0.7 * t),
np.random.randn(n_samples) * 0.1
])[:, :input_features]
# Synthetic nonlinear system
y = np.sum(X**2, axis=1) + 0.5 * np.sum(X, axis=1) + np.random.randn(n_samples) * 0.01
st.session_state['X'] = torch.tensor(X, dtype=torch.float32)
st.session_state['y'] = torch.tensor(y.reshape(-1, 1), dtype=torch.float32)
st.success("Data generated successfully!")
else:
input_file = st.file_uploader("Upload input time series (CSV)")
output_file = st.file_uploader("Upload output time series (CSV)")
if input_file and output_file:
X = torch.tensor(np.loadtxt(input_file, delimiter=","), dtype=torch.float32)
y = torch.tensor(np.loadtxt(output_file, delimiter=","), dtype=torch.float32)
if len(y.shape) == 1:
y = y.reshape(-1, 1)
st.session_state['X'] = X
st.session_state['y'] = y
st.success("Data loaded successfully!")
# Training
if st.button("Train Model") and 'X' in st.session_state and 'y' in st.session_state:
X = st.session_state['X']
y = st.session_state['y']
# Stage 1: Optimize nonlinearity with FIR
st.subheader("Stage 1: Optimizing Input Nonlinearity with FIR Model")
progress_bar1 = st.progress(0)
nonlinearity, fir_model, fir_losses = optimize_nonlinearity_and_fir(
X, y, fir_taps, fir_l1_weight, fir_epochs, progress_bar1
)
# Plot FIR training progress
fig1, ax1 = plt.subplots()
ax1.plot(fir_losses)
ax1.set_xlabel("Epoch")
ax1.set_ylabel("Loss")
ax1.set_title("FIR Model Training Progress")
st.pyplot(fig1)
# Display learned nonlinearity parameters
st.write("Learned Nonlinearity Parameters:")
for i in range(input_features):
st.write(f"Input {i+1}: a={nonlinearity.a[i].item():.3f}, x0={nonlinearity.x0[i].item():.3f}")
# Stage 2: Train TT model with fixed nonlinearity
st.subheader("Stage 2: Training Tensor Train Model")
progress_bar2 = st.progress(0)
# Create TT model configuration
config = TTModelConfig(
input_features=input_features,
output_features=output_features,
tt_ranks=tt_ranks,
learning_rate=learning_rate,
l1_weight=l1_weight,
max_epochs=tt_epochs,
fir_taps=fir_taps
)
# Create and train TT model
tt_model = TensorTrainModel(config, nonlinearity)
train_data = {"X": X, "y": y}
tt_losses = train_tt_model(tt_model, train_data, config, progress_bar2)
# Plot TT training progress
fig2, ax2 = plt.subplots()
ax2.plot(tt_losses)
ax2.set_xlabel("Epoch")
ax2.set_ylabel("Loss")
ax2.set_title("Tensor Train Model Training Progress")
st.pyplot(fig2)
# Save models
st.session_state['tt_model'] = tt_model