python 降噪

Autoencoders aren’t too useful in practice, but they can be used to denoise images quite successfully just by training the network on noisy images. We can generate noisy images by adding Gaussian noise to the training images, then clipping the values to be between 0 and 1.

自动编码器在实践中并不太有用,但是仅通过在嘈杂的图像上训练网络,它们就可以非常成功地对图像进行去噪。 我们可以通过将高斯噪声添加到训练图像中,然后将值裁剪为0到1之间的方式来生成嘈杂的图像。

“Denoising auto-encoder forces the hidden layer to extract more robust features and restrict it from merely learning the identity. Autoencoder reconstructs the input from a corrupted version of it.”

去噪自动编码器会强制隐藏层提取更强大的功能,并限制其仅学习身份。 自动编码器会从损坏的版本中重建输入。”

A denoising auto-encoder does two things:

去噪自动编码器有两件事:

  • Encode the input (preserve the information about the data)编码输入(保留有关数据的信息)
  • Undo the effect of a corruption process stochastically applied to the input of the auto-encoder.撤消随机应用于自动编码器输入的损坏过程的影响。

For the depiction of the denoising capabilities of Autoencoders, we’ll use noisy images as input and the original, clean images as targets.

为了描述自动编码器的降噪功能,我们将使用嘈杂的图像作为输入,并使用原始的干净图像作为目标。

Example: Top image is input, and the bottom image is the target.

示例:输入了顶部图像,而底部图像是目标。

问题陈述: (Problem Statement:)

Build the model for the denoising autoencoder. Add deeper and additional layers to the network. Using MNIST dataset, add noise to the data and try to define and train an autoencoder to denoise the images.

为降噪自动编码器构建模型。 向网络添加更深的层。 使用MNIST数据集,向数据添加噪声,并尝试定义和训练自动编码器以对图像进行降噪。

解: (Solution:)

Import Libraries and Load Dataset: Given below is the standard procedure to import the libraries and load the MNIST dataset.

导入库和加载数据集:以下是导入库和加载MNIST数据集的标准过程。

import torchimport numpy as npfrom torchvision import datasetsimport torchvision.transforms as transforms# convert data to torch.FloatTensortransform = transforms.ToTensor()# load the training and test datasetstrain_data = datasets.MNIST(root='data', train=True, download=True, transform=transform)test_data = datasets.MNIST(root='data', train=False, download=True, transform=transform)# Create training and test dataloadersnum_workers = 0# how many samples per batch to loadbatch_size = 20# prepare data loaderstrain_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, num_workers=num_workers)test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, num_workers=num_workers)

Visualize the Data: You can use standard matplotlib library to view whether you’ve loaded your dataset correctly or not.

可视化数据:可以使用标准的matplotlib库查看是否正确加载了数据集。

import matplotlib.pyplot as plt%matplotlib inline

# obtain one batch of training imagesdataiter = iter(train_loader)images, labels = dataiter.next()images = images.numpy()# get one image from the batchimg = np.squeeze(images[0])fig = plt.figure(figsize = (5,5)) ax = fig.add_subplot(111)ax.imshow(img, cmap='gray')

The output should be something like this:

输出应该是这样的:

Network Architecture: The most crucial part is the network generation. It is because denoising is a hard problem for the network; hence we’ll need to use deeper convolutional layers here. It is recommended to start with a depth of 32 for the convolutional layers in the encoder, and the same depth going backwards through the decoder.

网络体系结构:最关键的部分是网络生成。 这是因为去噪是网络的难题。 因此我们需要在这里使用更深的卷积层。 对于编码器中的卷积层,建议从32的深度开始,并向后穿过解码器。

import torch.nn as nnimport torch.nn.functional as F# define the NN architectureclass ConvDenoiser(nn.Module):    def __init__(self):        super(ConvDenoiser, self).__init__()        ## encoder layers ##        # conv layer (depth from 1 --> 32), 3x3 kernels        self.conv1 = nn.Conv2d(1, 32, 3, padding=1)          # conv layer (depth from 32 --> 16), 3x3 kernels        self.conv2 = nn.Conv2d(32, 16, 3, padding=1)        # conv layer (depth from 16 --> 8), 3x3 kernels        self.conv3 = nn.Conv2d(16, 8, 3, padding=1)        # pooling layer to reduce x-y dims by two; kernel and stride of 2        self.pool = nn.MaxPool2d(2, 2)

        ## decoder layers ##        # transpose layer, a kernel of 2 and a stride of 2 will increase the spatial dims by 2        self.t_conv1 = nn.ConvTranspose2d(8, 8, 3, stride=2)  # kernel_size=3 to get to a 7x7 image output        # two more transpose layers with a kernel of 2        self.t_conv2 = nn.ConvTranspose2d(8, 16, 2, stride=2)        self.t_conv3 = nn.ConvTranspose2d(16, 32, 2, stride=2)        # one, final, normal conv layer to decrease the depth        self.conv_out = nn.Conv2d(32, 1, 3, padding=1)def forward(self, x):        ## encode ##        # add hidden layers with relu activation function        # and maxpooling after        x = F.relu(self.conv1(x))        x = self.pool(x)        # add second hidden layer        x = F.relu(self.conv2(x))        x = self.pool(x)        # add third hidden layer        x = F.relu(self.conv3(x))        x = self.pool(x)  # compressed representation

        ## decode ##        # add transpose conv layers, with relu activation function        x = F.relu(self.t_conv1(x))        x = F.relu(self.t_conv2(x))        x = F.relu(self.t_conv3(x))        # transpose again, output should have a sigmoid applied        x = F.sigmoid(self.conv_out(x))

        return x# initialize the NNmodel = ConvDenoiser()print(model)

Training: The training of the network takes significantly less time with GPU; hence I would recommend using one. Though here we are only concerned with the training images, which we can get from the train_loader.

培训:使用GPU进行网络培训所需的时间大大减少; 因此,我建议使用一个。 虽然在这里我们只关心训练图像,但可以从train_loader获得。

# specify loss functioncriterion = nn.MSELoss()# specify loss functionoptimizer = torch.optim.Adam(model.parameters(), lr=0.001)# number of epochs to train the modeln_epochs = 20# for adding noise to imagesnoise_factor=0.5for epoch in range(1, n_epochs+1):    # monitor training loss    train_loss = 0.0

    ###################    # train the model #    ###################    for data in train_loader:        # _ stands in for labels, here        # no need to flatten images        images, _ = data

        ## add random noise to the input images        noisy_imgs = images + noise_factor * torch.randn(*images.shape)        # Clip the images to be between 0 and 1        noisy_imgs = np.clip(noisy_imgs, 0., 1.)

        # clear the gradients of all optimized variables        optimizer.zero_grad()        ## forward pass: compute predicted outputs by passing *noisy* images to the model        outputs = model(noisy_imgs)        # calculate the loss        # the "target" is still the original, not-noisy images        loss = criterion(outputs, images)        # backward pass: compute gradient of the loss with respect to model parameters        loss.backward()        # perform a single optimization step (parameter update)        optimizer.step()        # update running training loss        train_loss += loss.item()*images.size(0)

    # print avg training statistics     train_loss = train_loss/len(train_loader)    print('Epoch: {} \tTraining Loss: {:.6f}'.format(        epoch,         train_loss        ))

In this case, we are actually adding some noise to these images and we’ll feed these noisy_imgs to our model. The model will produce reconstructed images based on the noisy input. But, we want it to produce normal un-noisy images, and so, when we calculate the loss, we will still compare the reconstructed outputs to the original images!

在这种情况下,我们实际上 会在这些图像上 添加一些噪点 ,并将这些 noisy_imgs 入模型。 该模型将根据嘈杂的输入产生重建的图像。 但是,我们希望它产生正常的无噪图像,因此,当我们计算损耗时,我们仍然会将重构的输出与原始图像进行比较!

Because we’re comparing pixel values in input and output images, it will be best to use a loss that is meant for a regression task. Regression is all about comparing quantities rather than probabilistic values. So, in this case, I’ll use MSELoss.

因为我们正在比较输入和输出图像中的像素值,所以最好使用用于回归任务的损耗。 回归全是比较数量而不是概率值。 因此,在这种情况下,我将使用MSELoss

Results: Here let’s add noise to the test images and pass them through the autoencoder.

结果:在这里,我们将噪声添加到测试图像中,然后将其通过自动编码器。

# obtain one batch of test imagesdataiter = iter(test_loader)images, labels = dataiter.next()# add noise to the test imagesnoisy_imgs = images + noise_factor * torch.randn(*images.shape)noisy_imgs = np.clip(noisy_imgs, 0., 1.)# get sample outputsoutput = model(noisy_imgs)# prep images for displaynoisy_imgs = noisy_imgs.numpy()# output is resized into a batch of iagesoutput = output.view(batch_size, 1, 28, 28)# use detach when it's an output that requires_gradoutput = output.detach().numpy()# plot the first ten input images and then reconstructed imagesfig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(25,4))# input images on top row, reconstructions on bottomfor noisy_imgs, row in zip([noisy_imgs, output], axes):    for img, ax in zip(noisy_imgs, row):        ax.imshow(np.squeeze(img), cmap='gray')        ax.get_xaxis().set_visible(False)        ax.get_yaxis().set_visible(False)

It does a surprisingly great job of removing the noise, even though it’s sometimes difficult to tell what the original number is.

尽管有时很难说出原始数字是多少,但是它在消除噪声方面却做得非常出色。

Code: You can find this code on my Github: Denoising Autoencoder

代码:您可以在我的Github上找到此代码: Denoising Autoencoder

Conclusion: In this article, we learnt how to code denoising autoencoder in python properly. We also learnt that denoising is a hard problem for the network, hence using deeper convolutional layers provide exceptionally accurate results.

结论:在本文中,我们学习了如何在python中正确编码去噪自动编码器。 我们还了解到,去噪对于网络来说是一个难题,因此使用更深的卷积层可提供异常准确的结果。

Reference: I learnt this topic from “Udacity’s Secure and Private AI Scholarship Challenge Nanodegree Program.”

参考资料:我从“ Udacity的安全和私人AI奖学金挑战纳米学位计划”中学到了这个主题。

翻译自: https://towardsdatascience.com/reconstruct-corrupted-data-using-denoising-autoencoder-python-code-aeaff4b0958e

python 降噪


http://www.taodudu.cc/news/show-863681.html

相关文章:

  • bert简介_BERT简介
  • 卷积神经网络结构_卷积神经网络
  • html两个框架同时_两个框架的故事
  • 深度学习中交叉熵_深度计算机视觉,用于检测高熵合金中的钽和铌碎片
  • 梯度提升树python_梯度增强树回归— Spark和Python
  • 5行代码可实现5倍Scikit-Learn参数调整的更快速度
  • tensorflow 多人_使用TensorFlow2.x进行实时多人2D姿势估计
  • keras构建卷积神经网络_在Keras中构建,加载和保存卷积神经网络
  • 深度学习背后的数学_深度学习背后的简单数学
  • 深度学习:在图像上找到手势_使用深度学习的人类情绪和手势检测器:第1部分
  • 单光子探测技术应用_我如何最终在光学/光子学应用程序中使用机器学习作为博士学位
  • 基于深度学习的病理_组织病理学的深度学习(第二部分)
  • ai无法启动产品_启动AI启动的三个关键教训
  • 达尔文进化奖_使用Kydavra GeneticAlgorithmSelector将达尔文进化应用于特征选择
  • 变异函数 python_使用Python进行变异测试
  • 信号处理深度学习机器学习_机器学习与信号处理
  • PinnerSage模型
  • 零信任模型_关于信任模型
  • 乐器演奏_深度强化学习代理演奏的蛇
  • 深度学习模型建立过程_所有深度学习都是统计模型的建立
  • 使用TensorFlow进行鬼写
  • 使用OpenCV和Python从图像中提取形状
  • NLP的特征工程
  • 无监督学习 k-means_无监督学习-第1部分
  • keras时间序列数据预测_使用Keras的时间序列数据中的异常检测
  • 端口停止使用_我停止使用
  • opencv 分割边界_电影观众:场景边界分割
  • 监督学习无监督学习_无监督学习简介
  • kusto使用_Python查找具有数据重复问题的Kusto表
  • 使用GridSearchCV和RandomizedSearchCV进行超参数调整

python 降噪_使用降噪自动编码器重建损坏的数据(Python代码)相关推荐

  1. Python基础_第5章_Python中的数据序列

    Python基础_第5章_Python中的数据序列 文章目录 Python基础_第5章_Python中的数据序列 Python中的数据序列 一.字典--Python中的==查询==神器 1.为什么需要 ...

  2. 视频教程-Python数据分析与案例教程:分析人口普查数据-Python

    Python数据分析与案例教程:分析人口普查数据 多年互联网从业经验: 有丰富的的企业网站.手游.APP开发经验: 曾担任上海益盟软件技术股份有限公司项目经理及产品经理: 参与项目有益盟私募工厂.睿妙 ...

  3. 大学使用python 编辑器_[雪峰磁针石博客]2018 最佳python编辑器和IDE

    IDE没有统一的标准,自己习惯就是最好的.本文列出一些较常用的IDE,供大家参考. 一般而言,WingIDE.PyCharm.Spyder.Vim是比较常用的IDE. Spyder Spyder是Py ...

  4. 逻辑性不好可以学python吗_如果本文若未能让你学会“Python”,可能真的不适合学习Python...

    很多小伙伴们会问学习Python难学吗? python就是以他简单易学出名的.几乎是现在最简单,却可塑性最高的语言了.一般有其它编程语言基础的,自学,三小时左右就能学会.现在Python都有给小朋友的 ...

  5. ubuntu安装python百度经验_如何在Ubuntu 20.04上安装Python 3.9(含python编译安装和使用Apt命令安装)...

    在本文中,我们将向您展示在Ubuntu 20.04上安装Python 3.9的两种方法.第一种使用APT命令安装Python3.9,第二种是在Ubuntu20.04上编译安装Python 3.9.本教 ...

  6. python类加载_如何重新加载一个类在python shell?

    如果我导入一个定义了属于同一个包的同名类的模块,它将被导入为一个类,而不是一个模块,因为父包的__init__.py.详情请参见 different import results at differe ...

  7. excel用python数据分析_(转载)像Excel一样使用python进行数据分析

    Excel是数据分析中最常用的工具,本篇文章通过python与excel的功能对比介绍如何使用python通过函数式编程完成excel中的数据处理及分析工作.在Python中pandas库用于数据处理 ...

  8. c语言转换为python语言_【转】用C语言扩展Python的功能

    一.简介 Python是一门功能强大的高级脚本语言,它的强大不仅表现在其自身的功能上,而且还表现在其良好的可扩展性上,正因如此,Python已经开始受到越来越多人的青睐,并且被屡屡成功地应用于各类大型 ...

  9. vscode导入python包_使用Visual Studio Code将请求导入Python

    前言:我试过这篇文章中的每一个建议.它们都不起作用. 我试图将模块requests导入到一个python文件中(使用python2.7.14). Visual Studio代码在控制台中输出了此代码: ...

最新文章

  1. 联想lenovo Z470笔记本的驱动安装
  2. 算法与数据结构(归并排序)
  3. 实例化vue对象 绑定子组件_Vue-双向数据绑定
  4. C/C++ VS中调用matlab函数的方法
  5. 淘宝网的软件质量属性分析
  6. 深度的卷积神经网络CNN(MNIST数据集示例)
  7. Caffe学习笔记2--Ubuntu 14.04 64bit 安装Caffe(GPU版本)
  8. [Python+Anaconda] 查看Python、Anaconda下python、CUDA、函数库的版本
  9. Android Studio开发
  10. displayTag使用详解
  11. 企业该如何做好IT规划
  12. Jmeter——控制器与取样器
  13. 移动开发平台WorkPlus | 快速实现企业移动应用集成化
  14. Incapsula免费CDN服务申请
  15. 推荐书籍---豆瓣9.2分---《编码:隐匿在计算机软硬件背后的语言》
  16. 守护线程和用户线程的真正区别(实例讲解)
  17. 桌面快捷图标变成白色处理方案
  18. MySQL索引、事务与引擎基础详解,理论加实例
  19. python openssl 证书加解密过程感觉是这样
  20. 数字经济是什么?如何发展数字经济?

热门文章

  1. 安卓拒绝服务漏洞分析及漏洞检测
  2. SharePoint工作流开发点滴(2) - 开发第一个SharePiont工作流: HelloWorldSequential 的注意事项...
  3. 开源ETL软件在智能化集成系统中的应用
  4. memcached全面剖析–2.理解 memcached的内存存储
  5. grid系列--删除
  6. python星空画法教程_对比几段代码,看看你是 Python 菜鸟还是老鸟
  7. 获取数组名称 php,php 获取美国50个州的名称、简写对应数组用法示例
  8. smartdns使用指南_Windows10 玩SmartDNS告别污染
  9. 网站加速和服务器加速区别,cdn加速与不加速区别
  10. 广西大学计算机类开设课程,操作系统教学大纲-广西大学计算机与电子信息学院.DOC...