通过flow matching 拟合y(t) = e^{-t^2} , python 实现
- User
通过flow matching 拟合y(t) = e^{-t^2} , python 实现
- Assistant
通过flow matching 拟合y(t) = e^{-t^2} , python 实现
Flow matching is a technique used in continuous normalizing flows and generative modeling to learn a transformation (flow) that maps a simple base distribution to a target distribution by matching their vector fields. In this context, if you want to fit a specific function such as ( y(t) = e^{-t^2} ), you can use flow matching to model this function as a transformation governed by a learned vector field.
Below is a step-by-step guide along with a Python implementation using PyTorch to fit ( y(t) = e^{-t^2} ) using flow matching principles.
We aim to model the function ( y(t) = e^{-t^2} ) using a neural network to learn the vector field that defines the flow from a base distribution to the target distribution defined by ( y(t) ).
First, ensure you have the necessary libraries installed. We'll use PyTorch for building and training the neural network.
pip install torch matplotlib
Here's the complete Python implementation:
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
# Define the target function y(t) = e^{-t^2}
def target_function(t):
return torch.exp(-t**2)
# Define the vector field model
class VectorField(nn.Module):
def __init__(self):
super(VectorField, self).__init__()
# Simple MLP with 2 hidden layers
self.net = nn.Sequential(
nn.Linear(1, 32),
nn.Tanh(),
nn.Linear(32, 32),
nn.Tanh(),
nn.Linear(32, 1)
)
def forward(self, t):
return self.net(t)
# Define the flow model
class FlowModel(nn.Module):
def __init__(self, vector_field):
super(FlowModel, self).__init__()
self.vector_field = vector_field
def forward(self, t_initial, t_final, num_steps=100):
t = t_initial
dt = (t_final - t_initial) / num_steps
for _ in range(num_steps):
v = self.vector_field(t)
t = t + v * dt
return t
# Training parameters
learning_rate = 1e-3
num_epochs = 2000
t_initial = torch.tensor([-3.0], requires_grad=True) # Starting point
t_final = torch.tensor([0.0]) # We map to t_final=0
# Initialize model, optimizer, and loss function
vector_field = VectorField()
flow_model = FlowModel(vector_field)
optimizer = optim.Adam(flow_model.parameters(), lr=learning_rate)
mse_loss = nn.MSELoss()
# Training loop
loss_history = []
for epoch in range(num_epochs):
optimizer.zero_grad()
# Forward pass through the flow
t_mapped = flow_model(t_initial, t_final)
# Compute target value at t_final
y_target = target_function(t_final)
# Compute loss
loss = mse_loss(t_mapped, y_target)
loss.backward()
optimizer.step()
loss_history.append(loss.item())
if (epoch+1) % 200 == 0:
print(f'Epoch {epoch+1}/{num_epochs}, Loss: {loss.item():.6f}')
# Plot the loss history
plt.figure(figsize=(8, 4))
plt.plot(loss_history)
plt.xlabel('Epoch')
plt.ylabel('MSE Loss')
plt.title('Training Loss History')
plt.grid(True)
plt.show()
# Testing the flow
with torch.no_grad():
t_initial_test = torch.linspace(-3, 3, steps=100).unsqueeze(1)
t_final_test = flow_model(t_initial_test, t_initial_test.new_tensor([0.0]), num_steps=100)
y_pred = target_function(t_final_test)
# Plot the results
plt.figure(figsize=(8, 6))
plt.plot(t_initial_test.numpy(), target_function(t_initial_test).numpy(), label='Target y(t) = exp(-t^2)')
plt.plot(t_initial_test.numpy(), y_pred.numpy(), label='Flow Matched y(t)', linestyle='--')
plt.xlabel('t')
plt.ylabel('y(t)')
plt.title('Flow Matching Fit to y(t) = exp(-t^2)')
plt.legend()
plt.grid(True)
plt.show()
Target Function: We define the target function ( y(t) = e^{-t^2} ).
Vector Field Model: A simple neural network (Multi-Layer Perceptron) is defined to represent the vector field ( v(t) ) that governs the flow. This network takes ( t ) as input and outputs ( v(t) ).
Flow Model: The FlowModel class uses the vector field to iteratively update the value of ( t ) from an initial point ( t_{\text{initial}} ) to a final time ( t_{\text{final}} ) using Euler's method. The number of steps can be adjusted for better approximation.
Training: We train the model by minimizing the Mean Squared Error (MSE) between the flow-mapped ( t ) and the target value ( y(t) ) at ( t_{\text{final}} ). The optimizer updates the vector field's parameters to reduce this loss.
Visualization: After training, we plot the loss history to ensure that the model is learning. We then test the flow model by mapping a range of ( t ) values and plot the predicted ( y(t) ) against the target function to visualize the fit.
After running the training, the loss should decrease, indicating that the vector field is effectively learning to map the initial distribution to the target distribution defined by ( y(t) = e^{-t^2} ). The final plot should show that the flow-matched ( y(t) ) closely follows the target function.
Numerical Integration: The current implementation uses Euler’s method for simplicity. For better accuracy, especially for more complex functions, consider using higher-order integration methods like Runge-Kutta (e.g., torchdiffeq library).
Flow Complexity: For more complex target functions, you may need a deeper or more sophisticated vector field model.
Base and Target Distributions: The example above simplifies the problem by directly mapping from an initial point. For more general scenarios involving probability distributions, you would define base and target distributions and match their flows accordingly.
This example demonstrates a basic application of flow matching to fit a specific function using a neural network to learn the underlying vector field. While simplified for illustrative purposes, the principles can be extended to more complex scenarios in generative modeling and other areas where flow-based transformations are applicable.