-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataAugmenter.py
53 lines (37 loc) · 1.61 KB
/
DataAugmenter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
"""
from tensorflow.keras.layers import Layer
from tensorflow.keras import backend as K
import tensorflow as tf
import numpy as np
class DataAugmenter(Layer):
"""Shifts and scales input
Only active at training time since it is a regularization layer.
# Arguments
attenuation: how much to attenuate the input
# Input shape
Arbitrary.
# Output shape
Same as the input shape.
"""
def __init__(self, batch_size, **kwargs):
super(DataAugmenter, self).__init__(**kwargs)
self.supports_masking = True
self.batch_size = batch_size
def call(self, inputs, training=None):
def augmented():
angles = (15*(2*np.random.rand(self.batch_size)-1))*np.pi/180
shifts = 4*(2*np.random.rand(self.batch_size, 2)-1)
inputs_shifted = tf.contrib.image.translate(inputs, shifts)
inputs_shifted_rotated = tf.contrib.image.rotate(inputs_shifted,angles)
random_number = tf.random_uniform([self.batch_size])
inputs_shifted_rotated_flipped = tf.where(random_number<0.5, tf.image.flip_left_right(inputs_shifted_rotated), inputs_shifted_rotated)
return inputs_shifted_rotated_flipped
return K.in_train_phase(augmented, inputs, training=training)
def get_config(self):
config = {}
config['batch_size'] = self.batch_size
base_config = super(DataAugmenter, self).get_config()
return dict(list(base_config.items()) + list(config.items()))