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?? 解釋