tensorflow - TF2 数据增强随机性
问题描述
我一直在尝试将自定义增强添加到模型中。但是,虽然库函数(例如tf.image.random_flip_left_right
ortf.image.random_brightness
实际工作并为每个样本中的每个图像创建随机变化),但我的自定义函数始终对所有批次中的所有图像具有相同的效果。
例如,这些是我用于“随机”高斯和运动模糊的函数:
@tf.function
def gaussian(image, n_channels, dtype):
size = np.random.randint(2, 6)
sigma = np.random.uniform(0.5, 4.0)
x = tf.range(-size // 2 + 1, size // 2 + 1, dtype=dtype)
g = tf.math.exp(-(tf.pow(x, 2) / (2 * tf.pow(tf.cast(sigma, dtype), 2))))
g_norm2d = tf.pow(tf.reduce_sum(g), 2)
k = tf.tensordot(g, g, axes=0) / g_norm2d
k = tf.expand_dims(k, axis=-1)
k = tf.expand_dims(tf.tile(k, (1, 1, n_channels)), axis=-1)
return tf.nn.depthwise_conv2d(image[None], k, [1,1,1,1], 'SAME')[0]
@tf.function
def motion(image, n_channels, dtype):
size = np.random.randint(2, 11)
k = np.zeros((size, size))
k[int((size-1)/2), :] = np.ones(size)
k = k / size
k = tf.convert_to_tensor(k, dtype=dtype)
k = tf.expand_dims(k, axis=-1)
k = tf.expand_dims(tf.tile(k, (1, 1, n_channels)), axis=-1)
return tf.nn.depthwise_conv2d(image[None], k, [1,1,1,1], 'SAME')[0]
正如我所说,我的图像会得到随机亮度、翻转等。但它们都得到相同的运动和高斯模糊,这不是我想要的。
编辑:为了澄清,我在一个函数中按顺序调用所有增强函数,该augment(image, label)
函数通过dataset.map(augment)
. 这对其他增强效果很好。
解决方案
好的,所以我尝试了很多东西,但使它起作用的是只使用 TF 函数……这迫使我稍微更改代码并使事情变得更复杂,但嘿,这对你来说是 TF。
代码现在看起来像这样:
@tf.function
def gaussian(image, n_channels):
size = tf.random.uniform([1], 2, 6, dtype=tf.int32)[0]
sigma = tf.random.uniform([1], 0, 4.0, dtype=tf.float32)[0]
x = tf.range(-size // 2 + 1, size // 2 + 1, dtype=tf.float32)
g = tf.math.exp(-(tf.pow(x, 2) / (2 * tf.pow(tf.cast(sigma, dtype=tf.float32), 2))))
g_norm2d = tf.pow(tf.reduce_sum(g), 2)
k = tf.tensordot(g, g, axes=0) / g_norm2d
k = tf.expand_dims(k, axis=-1)
k = tf.expand_dims(tf.tile(k, (1, 1, n_channels)), axis=-1)
return tf.nn.depthwise_conv2d(image[None], k, [1,1,1,1], 'SAME')[0]
@tf.function
def motion(image, n_channels):
size = tf.random.uniform([1], 2, 11, dtype=tf.int32)[0]
a = tf.zeros(((size-1)/2, size))
b = tf.reshape(tf.ones((size)), [1,size])
k = tf.concat([a,b,a], 0)
k = k / tf.cast(size, tf.float32)
k = tf.expand_dims(k, axis=-1)
k = tf.expand_dims(tf.tile(k, (1, 1, n_channels)), axis=-1)
return tf.nn.depthwise_conv2d(image[None], k, [1,1,1,1], 'SAME')[0]
推荐阅读
- c# - GetWindowTextLength 和 GetClassName 可重用类在新项目中失败?
- ios - 弹出窗口不会在 iOS 12 中请求访问相机的权限
- typescript - 为什么在 Typescript 泛型中使用 '&'
- android - Google Play 和 Launcher 推出了分开的活动
- symfony - 覆盖来自另一个包的包模板
- vba - 如果输出工作簿名称已存在则合并
- vespa - vespa 中特定文档的总数
- windows - PowerShell 脚本晨检
- wifi - 如何在没有物理访问路由器的情况下扩展公共 wifi(用于一个或多个设备)
- visual-studio - 如何动态更改 Foreach 循环递归属性