基于循环神经网络的一维信号降噪方法(简单版本,Python)

代码非常简单。

import torch 
import torch.nn as nn
from torch.autograd import Variable
from scipy.io.wavfile import write
#need install pydub module
#pip install pydub
import numpy as np
import pydub 
from scipy import signal
import IPython
import matplotlib.pylab as plt
from mpl_toolkits.mplot3d import Axes3D
# For running on GPU
#device = torch.device("cuda")# choose your device
device = torch.device("cpu")
a = torch.rand(5, 5, device=device)# change by either using the device argument
a = a.to(device)# or by .to()

Make data

fs = 512
x = np.linspace(0, 20*np.pi * (1-1/(10*fs)), fs*10)
y_sin = 0.5*np.sin(x)
plt.plot(x, y_sin)
plt.xlabel('Angle [rad]')
plt.ylabel('sin(x)')
plt.axis('tight')
plt.show()

y_triangle = 0.5*signal.sawtooth(x, 0.5)
plt.plot(x, y_triangle)
plt.xlabel('Phase [rad]')
plt.ylabel('triangle(x)')
plt.axis('tight')
plt.show()

y_saw = 0.5*signal.sawtooth(x, 1)plt.plot(x, y_saw)plt.xlabel('Phase [rad]')plt.ylabel('sawtooth(x)')plt.axis('tight')plt.show()

Add Gaussian Noise

Add noise


# Add guassian noise
y_sin_n = y_sin + 0.1*np.random.normal(size=len(x))
y_triangle_n = y_triangle + 0.1*np.random.normal(size=len(x))
y_saw_n = y_saw + 0.1*np.random.normal(size=len(x))plt.plot(x, y_sin_n)
plt.xlabel('Angle [rad]')
plt.ylabel('sin(x) + noise')
plt.axis('tight')
plt.show()

plt.plot(x, y_triangle_n)
plt.xlabel('Phase [rad]')
plt.ylabel('triangle(x) + noise')
plt.axis('tight')
plt.show()

plt.plot(x, y_saw_n)
plt.xlabel('Phase [rad]')
plt.ylabel('sawtooth(x) + noise')
plt.axis('tight')
plt.show()

Creating Dataset

def give_part_of_data(x, y, n_samples=10000, sample_size=100) :data_inp = np.zeros((n_samples, sample_size))data_out = np.zeros((n_samples, sample_size))for i in range(n_samples):random_offset = np.random.randint(0, len(x) - sample_size)sample_inp = x[random_offset:random_offset+sample_size]sample_out = y[random_offset:random_offset+sample_size]data_inp[i, :] = sample_inpdata_out[i, :] = sample_outreturn data_inp, data_out
# Train, Validationa, and Test
sin_train_in, sin_train_out = give_part_of_data(y_sin_n[0:int(7/10 * len(x))], y_sin[0:int(7/10 * len(x))], 2000, int(len(x)/6))
tri_train_in, tri_train_out = give_part_of_data(y_triangle_n[0:int(7/10 * len(x))], y_triangle[0:int(7/10 * len(x))], 2000, int(len(x)/6))
saw_train_in, saw_train_out = give_part_of_data(y_saw_n[0:int(7/10 * len(x))], y_saw[0:int(7/10 * len(x))], 2000, int(len(x)/6))sin_val_in, sin_val_out = y_sin_n[int(7/10 * len(x)):int(8/10 * len(x))], y_sin[int(7/10 * len(x)):int(8/10 * len(x))]
tri_val_in, tri_val_out = y_triangle_n[int(7/10 * len(x)):int(8/10 * len(x))], y_triangle[int(7/10 * len(x)):int(8/10 * len(x))]
saw_val_in, saw_val_out = y_saw_n[int(7/10 * len(x)):int(8/10 * len(x))], y_saw[int(7/10 * len(x)):int(8/10 * len(x))]sin_test_in, sin_test_out = y_sin_n[int(8/10 * len(x)):int(10/10 * len(x))], y_sin[int(8/10 * len(x)):int(10/10 * len(x))]
tri_test_in, tri_test_out = y_triangle_n[int(8/10 * len(x)):int(10/10 * len(x))], y_triangle[int(8/10 * len(x)):int(10/10 * len(x))]
saw_test_in, saw_test_out = y_saw_n[int(8/10 * len(x)):int(10/10 * len(x))], y_saw[int(8/10 * len(x)):int(10/10 * len(x))]
plt.plot(range(853), sin_train_in[3])
plt.plot(range(853), sin_train_out[3])plt.xlabel('Phase [rad]')
plt.ylabel('sin(x) + noise')
plt.axis('tight')
plt.show()

RNN + Sin

# RNN model
input_dim = 1
hidden_size_1 = 60
hidden_size_2 = 60
output_size = 1class CustomRNN(nn.Module):def __init__(self, input_size, hidden_size_1, hidden_size_2, output_size):super(CustomRNN, self).__init__()self.rnn = nn.RNN(input_size=input_size, hidden_size=hidden_size_1, batch_first=True)self.linear = nn.Linear(hidden_size_1, hidden_size_2, )self.act = nn.Tanh()self.linear = nn.Linear(hidden_size_2, output_size, )self.act = nn.Tanh()def forward(self, x):pred, hidden = self.rnn(x, None)pred = self.act(self.linear(pred)).view(pred.data.shape[0], -1, 1)return predmodel = CustomRNN(input_dim, hidden_size_1, hidden_size_2, output_size)
model = model.to(device)
optimizer = torch.optim.Adam(model.parameters())
loss_func = nn.MSELoss()lr = 1e-2for t in range(1000):inp = torch.Tensor(sin_train_in[..., np.newaxis] )inp.requires_grad = Trueinp = inp.to(device)out = torch.Tensor(sin_train_out[..., np.newaxis])out = out.to(device)pred = model(inp)optimizer.zero_grad()loss = loss_func(pred, out)if t%20==0:print(t, loss.data.item())lr = lr / 1.0001optimizer.param_groups[0]['lr'] = lrloss.backward()optimizer.step()
test_in = sin_test_in
inp = torch.Tensor(test_in[np.newaxis, ... , np.newaxis] )
inp = inp.to(device)
pred = model(inp).cpu().detach().numpy()
plt.plot(range(len(sin_test_in)), test_in)
plt.plot(range(len(sin_test_in)), pred[0, :,0])plt.showorginal_SNR = np.sum(np.abs(sin_test_out)**2) / np.sum(np.abs(sin_test_in - sin_test_out)**2)
orginal_SNR_db = 10*np.log(orginal_SNR)/np.log(10)
print('Original SNR : ', orginal_SNR)
print('Original SNR DB : ', orginal_SNR_db)network_SNR = np.sum(np.abs(sin_test_out)**2) / np.sum(np.abs(pred[0, :,0] - sin_test_out)**2)
network_SNR_db = 10*np.log(network_SNR)/np.log(10)
print('Network SNR : ', network_SNR)
print('Network SNR DB : ', network_SNR_db)
Original SNR :  12.951857235597608
Original SNR DB :  11.123320486750668
Network SNR :  107.29848229242438
Network SNR DB :  20.305935790331755

RNN + Triangular

# RNN model
input_dim = 1
hidden_size_1 = 60
hidden_size_2 = 60
output_size = 1class CustomRNN(nn.Module):def __init__(self, input_size, hidden_size_1, hidden_size_2, output_size):super(CustomRNN, self).__init__()self.rnn = nn.RNN(input_size=input_size, hidden_size=hidden_size_1, batch_first=True)self.linear = nn.Linear(hidden_size_1, hidden_size_2, )self.act = nn.Tanh()self.linear = nn.Linear(hidden_size_2, output_size, )self.act = nn.Tanh()def forward(self, x):pred, hidden = self.rnn(x, None)pred = self.act(self.linear(pred)).view(pred.data.shape[0], -1, 1)return predmodel = CustomRNN(input_dim, hidden_size_1, hidden_size_2, output_size)
model = model.to(device)
optimizer = torch.optim.Adam(model.parameters())
loss_func = nn.MSELoss()lr = 1e-2for t in range(1000):inp = torch.Tensor(tri_train_in[..., np.newaxis] )inp.requires_grad = Trueinp = inp.to(device)out = torch.Tensor(tri_train_out[..., np.newaxis])out = out.to(device)pred = model(inp)optimizer.zero_grad()loss = loss_func(pred, out)if t%20==0:print(t, loss.data.item())lr = lr / 1.0001optimizer.param_groups[0]['lr'] = lrloss.backward()optimizer.step()
test_in = tri_test_in
inp = torch.Tensor(test_in[np.newaxis, ... , np.newaxis] )
inp = inp.to(device)
pred = model(inp).cpu().detach().numpy()
plt.plot(range(len(tri_test_in)), test_in)
plt.plot(range(len(tri_test_in)), pred[0, :,0])plt.showorginal_SNR = np.sum(np.abs(tri_test_out)**2) / np.sum(np.abs(tri_test_in - tri_test_out)**2)
orginal_SNR_db = 10*np.log(orginal_SNR)/np.log(10)
print('Original SNR : ', orginal_SNR)
print('Original SNR DB : ', orginal_SNR_db)network_SNR = np.sum(np.abs(tri_test_out)**2) / np.sum(np.abs(pred[0, :,0] - tri_test_out)**2)
network_SNR_db = 10*np.log(network_SNR)/np.log(10)
print('Network SNR : ', network_SNR)
print('Network SNR DB : ', network_SNR_db)
Original SNR :  9.06282337035853
Original SNR DB :  9.572635159053185
Network SNR :  46.622532666082044
Network SNR DB :  16.685958619136

RNN + Sawtooth

# RNN model
input_dim = 1
hidden_size_1 = 60
hidden_size_2 = 60
output_size = 1class CustomRNN(nn.Module):def __init__(self, input_size, hidden_size_1, hidden_size_2, output_size):super(CustomRNN, self).__init__()self.rnn = nn.RNN(input_size=input_size, hidden_size=hidden_size_1, batch_first=True)self.linear = nn.Linear(hidden_size_1, hidden_size_2, )self.act = nn.Tanh()self.linear = nn.Linear(hidden_size_2, output_size, )self.act = nn.Tanh()def forward(self, x):pred, hidden = self.rnn(x, None)pred = self.act(self.linear(pred)).view(pred.data.shape[0], -1, 1)return predmodel = CustomRNN(input_dim, hidden_size_1, hidden_size_2, output_size)
model = model.to(device)
optimizer = torch.optim.Adam(model.parameters())
loss_func = nn.MSELoss()lr = 1e-2for t in range(1000):inp = torch.Tensor(tri_train_in[..., np.newaxis] )inp.requires_grad = Trueinp = inp.to(device)out = torch.Tensor(tri_train_out[..., np.newaxis])out = out.to(device)pred = model(inp)optimizer.zero_grad()loss = loss_func(pred, out)if t%20==0:print(t, loss.data.item())lr = lr / 1.0001optimizer.param_groups[0]['lr'] = lrloss.backward()optimizer.step()
test_in = saw_test_in
inp = torch.Tensor(test_in[np.newaxis, ... , np.newaxis] )
inp = inp.to(device)
pred = model(inp).cpu().detach().numpy()
plt.plot(range(len(saw_test_in)), test_in)
plt.plot(range(len(saw_test_in)), pred[0, :,0])plt.showorginal_SNR = np.sum(np.abs(saw_test_out)**2) / np.sum(np.abs(saw_test_in - saw_test_out)**2)
orginal_SNR_db = 10*np.log(orginal_SNR)/np.log(10)
print('Original SNR : ', orginal_SNR)
print('Original SNR DB : ', orginal_SNR_db)network_SNR = np.sum(np.abs(saw_test_out)**2) / np.sum(np.abs(pred[0, :,0] - saw_test_out)**2)
network_SNR_db = 10*np.log(network_SNR)/np.log(10)
print('Network SNR : ', network_SNR)
print('Network SNR DB : ', network_SNR_db)
Original SNR :  8.918716305325825
Original SNR DB :  9.50302349708762
Network SNR :  26.97065260659425
Network SNR DB :  14.308914551667852

知乎学术咨询:
https://www.zhihu.com/consult/people/792359672131756032?isMe=1

工学博士,担任《Mechanical System and Signal Processing》《中国电机工程学报》《控制与决策》等期刊审稿专家,擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/367219.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

美术馆预约小程序的设计

管理员账户功能包括:系统首页,个人中心,展品信息管理,管理员管理,用户管理,美术馆管理,基础数据管理,论坛管理 微信端账号功能包括:系统首页,美术馆&#xf…

【C语言】文件的顺序读写

©作者:末央& ©系列:C语言初阶(适合小白入门) ©说明:以凡人之笔墨,书写未来之大梦 目录 前言字符输入输出函数 - fgetc和fputc文本行输入输出函数 - fgets和fputs格式化输入输出函数 - fscanf和fprintf 前言 对文件数据的读写可以分为顺序…

小红书 达芬奇:生活问答 AI 机器人

小红书去年 9 月开始内测的生活问答 AI 机器人:达芬奇,现在可以在小红书 APP 上用了 得益于小红书平台的特性,该助手擅长吃、住、宠、喝、学等等各类生活知识,目前还在搞活动,写评测笔记最高得 666 元

ABAQUS软件天津正版代理商亿达四方:创新技术,驱动产业升级

在环渤海经济圈的核心地带——天津,随着智能制造与高新技术产业的蓬勃发展,对高端仿真软件的需求日益增长。亿达四方,作为ABAQUS在天津的官方正版代理商,凭借其深厚的行业经验和卓越的服务体系,正为这片热土上的科研机…

音乐播放器小程序的设计

管理员账户功能包括:系统首页,个人中心,歌曲信息管理,会员优惠管理,用户管理,会员办理管理,歌曲分类管理,会员信息管理 微信端账号功能包括:系统首页,歌曲信…

深入了解激光粒度分析仪:检测物质粒度分布的利器

在科研、工业生产以及环境监测等多个领域中,精确测量物质粒度分布是确保产品质量、研究准确性和环境安全的重要步骤。 近年来,激光粒度分析仪以其独特的技术优势,在这些领域发挥着越来越重要的作用。 在这篇文章中,佰德将带您了…

机器学习Python代码实战(二)分类算法:k-最近邻

一.k-最近邻算法步骤 1.选择适当的k值。它表示在预测新的数据点时要考虑的邻居数量。 2.计算距离。计算未知点与其他所有点之间的距离。常用的距离计算方法主要有欧氏距离,曼哈顿距离等。 3.选择邻居。在训练集中选择与要预测的数据点距离最近的k个邻居。 4.预测…

递归算法练习

112. 路径总和 package Tree;import java.util.HashMap; import java.util.Map;class TreeNode {int val;TreeNode left;TreeNode right;public TreeNode(int val) {this.val val;} }/*** 求 树的路径和* <p>* 递归 递减* <p>* 询问是否存在从*当前节点 root 到叶…

JDBC学习(Java DataBase Connectivity)

JDBC简介 JDBC入门 驱动jar包&#xff1a;C:\Users\49960\Desktop\mysql-connector-j-9.0.0 需要配置add library&#xff01;&#xff01;&#xff01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.Stack;pub…

如何构建智能聊天系统

聊天分为听、思考、读&#xff0c;简单的通过ASR、LLM、TTS三类模型的组合可以实现&#xff0c;最近openai推出支持多模态的GPT-4o模型&#xff0c;可以把三个模型真正融合成在一起。 现在市面上的模型百花齐放&#xff0c;各有所长。要实现可落地的方案&#xff0c;需要结合业…

Python实现万花筒效果:创造炫目的动态图案

文章目录 引言准备工作前置条件 代码实现与解析导入必要的库初始化Pygame定义绘制万花筒图案的函数主循环 完整代码 引言 万花筒效果通过反射和旋转图案创造出美丽的对称图案。在这篇博客中&#xff0c;我们将使用Python来实现一个动态的万花筒效果。通过利用Pygame库&#xf…

数据结构算法之B树

一、绪论 1.1 数据结构的概念和作用 1.2 B树的起源和应用领域 二、B树的基本原理 2.1 B树的定义和特点 2.2 B树的结构和节点组成 2.3 B树的插入 2.4 B树的删除操作 三、B树的优势和应用 3.1 B树在数据库系统中的应用 3.2 B树在文件系统中的应用 3.3 B树在内存管理中…

java+mysql教师管理系统

完整源码地址 教师信息管理系统使用命令行交互的方式及数据库连接实现教师信息管理系统&#xff0c;该系统旨在实现教师信息的管理&#xff0c;并根据需要进行教师信息展示。该软件的功能有如下功能 (1)基本信息管理(教师号、姓名、性别、出生年月、职称、学历、学位、教师类型…

Linux基础指令介绍与详解——原理学习

前言&#xff1a;本节内容标题虽然为指令&#xff0c;但是并不只是讲指令&#xff0c; 更多的是和指令相关的一些原理性的东西。 如果友友只想要查一查某个指令的用法&#xff0c; 很抱歉&#xff0c; 本节不是那种带有字典性质的文章。但是如果友友是想要来学习的&#xff0c;…

Pytest+Allure+Yaml+PyMsql+Jenkins+Gitlab接口自动化(五)Jenkins配置

一、背景 Jenkins&#xff08;本地宿主机搭建&#xff09; 拉取GitLab(服务器)代码到在Jenkins工作空间本地运行并生成Allure测试报告 二、框架改动点 框架主运行程序需要先注释掉运行代码&#xff08;可不改&#xff0c;如果运行报allure找不到就直接注释掉&#xff09; …

Linux修炼之路之进程概念,fork函数,进程状态

目录 一&#xff1a;进程概念 二&#xff1a;Linux中的进程概念 三&#xff1a;用getpid(),getppid()获取该进程的PID,PPID 四&#xff1a;用fork()来创建子进程 五&#xff1a;操作系统学科的进程状态 六&#xff1a;Linux中的进程状态 接下来的日子会顺顺利利&#xf…

《梦醒蝶飞:释放Excel函数与公式的力量》8.3 COUNTBLANK函数

8.3 COUNTBLANK函数 在数据处理和分析中&#xff0c;我们经常需要识别和统计数据集中的空白单元格。COUNTBLANK函数是Excel中用于统计某个范围内空白单元格数量的强大工具。 8.3.1 函数简介 COUNTBLANK函数用于统计指定范围内的空白单元格数量。这在数据清洗、数据完整性检查…

【RT摩拳擦掌】RT云端测试之百度天工物接入构建(设备型)

【RT摩拳擦掌】RT云端测试之百度天工物接入构建&#xff08;设备型&#xff09; 一&#xff0c; 文档介绍二&#xff0c; 物接入IOT Hub物影子构建2.1 创建设备型项目2.2 创建物模型2.3 创建物影子 三&#xff0c; MQTT fx客户端连接云端3.1 MQTT fx配置3.2 MQTT fx订阅3.3 MQT…

昇思MindSpore学习入门-保存与加载

在训练网络模型的过程中&#xff0c;实际上我们希望保存中间和最后的结果&#xff0c;用于微调&#xff08;fine-tune&#xff09;和后续的模型推理与部署&#xff0c;本章节我们将介绍如何保存与加载模型。 保存和加载模型权重 保存模型使用save_checkpoint接口&#xff0c;…

从hugging face 下模型

支持国内下载hugging face 的东西 下模型权重 model_id 是红色圈复制的 代码 记得设置下载的存储位置 import os from pathlib import Path from huggingface_hub import hf_hub_download from huggingface_hub import snapshot_downloadmodel_id"llava-hf/llava-v1…