import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
# -------------------------
# 1. 简单的扩散模型定义
# -------------------------
class SimpleDiffusionModel(nn.Module):
def __init__(self, seq_len, channels=2, hidden_dim=64):
super().__init__()
self.seq_len = seq_len
self.channels = channels
self.hidden_dim = hidden_dim
# 编码器:提取特征
self.encoder = nn.Sequential(
nn.Conv1d(channels, hidden_dim, kernel_size=3, padding=1),
nn.ReLU(),
nn.Conv1d(hidden_dim, hidden_dim, kernel_size=3, padding=1),
nn.ReLU()
)
# 去噪器:预测噪声
self.denoiser = nn.Sequential(
nn.Conv1d(hidden_dim, hidden_dim, kernel_size=3, padding=1),
nn.ReLU(),
nn.Conv1d(hidden_dim, channels, kernel_size=3, padding=1)
)
def forward(self, x, t):
"""
x: [B, 2, seq_len] noised IQ signal at timestep t
t: diffusion timestep scalar or tensor
"""
h = self.encoder(x) # 中间特征
noise_pred = self.denoiser(h) # 预测噪声
return noise_pred, h
# -------------------------
# 2. 判别器定义(基于扩散模型中间特征)
# -------------------------
class Classifier(nn.Module):
def __init__(self, hidden_dim=64, num_classes=10):
super().__init__()
self.conv = nn.Sequential(
nn.Conv1d(hidden_dim, hidden_dim, kernel_size=3, padding=1),
nn.ReLU(),
nn.AdaptiveAvgPool1d(1)
)
self.fc = nn.Linear(hidden_dim, num_classes)
def forward(self, features):
"""
features: [B, hidden_dim, seq_len]
"""
x = self.conv(features).squeeze(-1) # [B, hidden_dim]
logits = self.fc(x)
return logits
# -------------------------
# 3. 扩散过程相关函数
# -------------------------
def q_sample(x_start, t, noise=None):
"""
扩散过程:给定原始信号x_start,添加噪声得到x_t
这里简化为线性噪声调制
"""
if noise is None:
noise = torch.randn_like(x_start)
alpha = 1 - t / 1000 # 简单线性衰减
return torch.sqrt(alpha) * x_start + torch.sqrt(1 - alpha) * noise
def p_sample(model, x_t, t):
"""
去噪过程:给定x_t和t,预测噪声并还原x_{t-1}
"""
noise_pred, features = model(x_t, t)
alpha = 1 - t / 1000
x_prev = (x_t - torch.sqrt(1 - alpha) * noise_pred) / torch.sqrt(alpha)
return x_prev, features
# -------------------------
# 4. 训练示例流程
# -------------------------
def train_step(model, classifier, optimizer, x_start, labels, t):
"""
x_start: 原始IQ信号 [B, 2, seq_len]
labels: 设备ID标签 [B]
t: 扩散时间步标量或tensor
"""
model.train()
classifier.train()
# 1) 扩散过程,添加噪声
noise = torch.randn_like(x_start)
x_t = q_sample(x_start, t, noise)
# 2) 预测噪声,计算扩散模型损失
noise_pred, features = model(x_t, t)
diffusion_loss = F.mse_loss(noise_pred, noise)
# 3) 利用扩散模型中间特征训练判别器
logits = classifier(features.detach()) # detach防止梯度回传到扩散模型
cls_loss = F.cross_entropy(logits, labels)
# 4) 总损失
loss = diffusion_loss + cls_loss
optimizer.zero_grad()
loss.backward()
optimizer.step()
return loss.item(), diffusion_loss.item(), cls_loss.item()
# -------------------------
# 5. 推理示例:利用去噪过程提取鲁棒特征进行识别
# -------------------------
@torch.no_grad()
def inference(model, classifier, x_start, t=500):
model.eval()
classifier.eval()
# 添加噪声
noise = torch.randn_like(x_start)
x_t = q_sample(x_start, t, noise)
# 去噪过程
x_denoised, features = p_sample(model, x_t, t)
# 分类
logits = classifier(features)
preds = torch.argmax(logits, dim=1)
return preds
# -------------------------
# 6. 示例主函数
# -------------------------
def main():
batch_size = 16
seq_len = 128
num_classes = 10
model = SimpleDiffusionModel(seq_len=seq_len)
classifier = Classifier(num_classes=num_classes)
optimizer = torch.optim.Adam(list(model.parameters()) + list(classifier.parameters()), lr=1e-3)
# 假设有训练数据x_train, y_train
# 这里用随机数据模拟
x_train = torch.randn(batch_size, 2, seq_len)
y_train = torch.randint(0, num_classes, (batch_size,))
t = torch.randint(1, 1000, (1,)).item() # 随机扩散步数
loss, diff_loss, cls_loss = train_step(model, classifier, optimizer, x_train, y_train, t)
print(f"Train Loss: {loss:.4f}, Diffusion Loss: {diff_loss:.4f}, Classifier Loss: {cls_loss:.4f}")
# 推理示例
preds = inference(model, classifier, x_train)
print("Predictions:", preds)
if __name__ == "__main__":
main()