语义通信高斯信道仿真代码
1️⃣ 代码
def AWGN(coding, snr, device='cpu'):"""为输入张量添加高斯白噪声(AWGN),根据指定的 SNR(分贝)控制噪声强度。参数:coding (torch.Tensor): 输入张量,形状为 [batch_size, ...](例如 [batch_size, 128])snr (float): 信噪比(dB)device (str or torch.device): 张量所在的设备返回:coding_noise (torch.Tensor): 添加噪声后的张量,形状与输入相同"""coding_shape = coding.shapecoding_reshape = coding.reshape(coding_shape[0], -1)# 归一化信号功率coding_reshape = torch.sqrt(torch.tensor(coding_reshape.shape[1], dtype=torch.float, device=device)) * \F.normalize(coding_reshape, p=2, dim=1)# 计算信号功率power = torch.mean(coding_reshape **2)# 计算噪声标准差noise_stddev = torch.sqrt(torch.tensor(10** (-snr / 10), dtype=torch.float, device=device)) * power# 生成高斯噪声n = torch.randn_like(coding_reshape, device=device)coding_noise = coding_reshape + n * noise_stddev# 恢复原始形状coding_noise = coding_noise.reshape(coding_shape)return coding_noise
2️⃣ 解释