简体   繁体   English

如何向图像数据添加 Keras- 高斯噪声

[英]How to add Keras- Gaussian noise to image data

Importing the modules:导入模块:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.layers import GaussianNoise
from tensorflow.keras.datasets import mnist

(X_train, y_train), (X_test, y_test) = mnist.load_data()

Re-scaling the data重新缩放数据

X_train = X_train/255
X_test = X_test/255
plt.imshow(X_train[0])

Adding Gaussian Noise with std dev=0.2使用 std dev=0.2 添加高斯噪声

sample = GaussianNoise(0.2)
noisey = sample(X_test[0:2],training=True)   #plt.imshow(noisey[0])

Getting Error:获取错误:

ValueError: Tensor conversion requested dtype float64 for Tensor with dtype float32: 'Tensor("gaussian_noise_4_1/random_normal:0", shape=(2, 28, 28), dtype=float32)'

Type casting is costly, and so Tensorflow doesn't do automatic type casting.类型转换成本很高,因此 Tensorflow 不进行自动类型转换。 As a default, Tensorflow's dtype is float32 , and the dataset you imported has a dtype float64 .默认情况下,Tensorflow 的 dtype 是float32 ,而您导入的数据集的 dtype 是float64 You will just have to pass the optional dtype argument to GaussianNoise :您只需将可选的 dtype 参数传递给GaussianNoise

sample = GaussianNoise(0.2, dtype=tf.float64)

Or cast the array:或者投射数组:

noisey = sample(X_test[0:2].astype(np.float32),training=True)

I suggest the second one.我建议第二个。

I tried this in my localhost for Jupyter Notebook and the following was the result with a warning.我在我的本地主机上为 Jupyter Notebook 尝试了这个,以下是带有警告的结果。

尝试警告

From the warning it's clear that the problem of Type casting which is very costly.从警告中可以清楚地看出类型转换的问题是非常昂贵的。 You can improve it as:您可以将其改进为:

X_train = X_train.astype('float32') / 255

X_test = X_test.astype('float32') / 255

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM