aboutsummaryrefslogtreecommitdiff
path: root/losses.py
blob: f08a734cb93b23397a5cd620cb7d37befc45a4b8 (plain)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import tensorflow as tf
import numpy as np
from tensorflow.keras.layers import \
    Conv2D, AveragePooling2D
from skimage import transform
import hyperparameters as hp

class YourModel(tf.keras.Model):
    """ Your own neural network model. """

    def __init__(self, content_image, style_image): #normalize these images to float values
        super(YourModel, self).__init__()
       
        self.content_image = transform.resize(content_image, tf.shape(style_image), anti_aliasing=True)
        self.content_image = tf.expand_dims(self.content_image, axis=0)
        print(self.content_image)
        
        #perhaps consider cropping to avoid distortion
        self.style_image = transform.resize(style_image, tf.shape(style_image), anti_aliasing=True)
        self.style_image = tf.expand_dims(self.style_image, axis=0)
        #self.x = tf.Variable(initial_value = self.content_image.numpy().astype(np.float32), trainable=True) 
        self.x = tf.Variable(initial_value = np.random.rand(self.content_image.shape[0],
        self.content_image.shape[1], self.content_image.shape[2], self.content_image.shape[3]).astype(np.float32), trainable=True) 

        self.alpha = hp.alpha
        self.beta = hp.beta

        self.photo_layers = None
        self.art_layers = None



        #(self.x.shape)

        #print(self.content_image.shape, self.style_image.shape)

        self.optimizer = tf.keras.optimizers.Adam(hp.learning_rate)

        self.vgg16 = [
            # Block 1
            Conv2D(64, 3, 1, padding="same",
                   activation="relu", name="block1_conv1"),
            Conv2D(64, 3, 1, padding="same",
                   activation="relu", name="block1_conv2"),
            AveragePooling2D(2, name="block1_pool"),
            # Block 2
            Conv2D(128, 3, 1, padding="same",
                   activation="relu", name="block2_conv1"),
            Conv2D(128, 3, 1, padding="same",
                   activation="relu", name="block2_conv2"),
            AveragePooling2D(2, name="block2_pool"),
            # Block 3
            Conv2D(256, 3, 1, padding="same",
                   activation="relu", name="block3_conv1"),  
            Conv2D(256, 3, 1, padding="same",
                   activation="relu", name="block3_conv2"),
            Conv2D(256, 3, 1, padding="same",
                   activation="relu", name="block3_conv3"),
            AveragePooling2D(2, name="block3_pool"),
            # Block 4
            Conv2D(512, 3, 1, padding="same",
                   activation="relu", name="block4_conv1"),
            Conv2D(512, 3, 1, padding="same",
                   activation="relu", name="block4_conv2"),
            Conv2D(512, 3, 1, padding="same",
                   activation="relu", name="block4_conv3"),
            AveragePooling2D(2, name="block4_pool"),
            # Block 5
            Conv2D(512, 3, 1, padding="same",
                   activation="relu", name="block5_conv1"),
            Conv2D(512, 3, 1, padding="same",
                   activation="relu", name="block5_conv2"),
            Conv2D(512, 3, 1, padding="same",
                   activation="relu", name="block5_conv3"),
            AveragePooling2D(2, name="block5_pool"),
        ]
        for layer in self.vgg16:
               layer.trainable = False

        self.layer_to_filters = {layer.name: layer.filters for layer in self.vgg16 if "conv" in layer.name}
        self.indexed_layers = [layer for layer in self.vgg16 if "conv1" in layer.name]
        self.desired = [layer.name for layer in self.vgg16 if "conv1" in layer.name]

        self.vgg16 = tf.keras.Sequential(self.vgg16, name="vgg")

        # create a map of the layers to their corresponding number of filters if it is a convolutional layer

    def call(self, x):
        layers = []
        for layer in self.vgg16.layers:
            # pass the x through
            x = layer(x)
       #      print("Sotech117 is so so sus")

            # save the output of each layer if it is in the desired list
            if layer.name in self.desired:
              layers.append(x)
            
        return x, layers

    def loss_fn(self, p, a, x):
       # print(p)
       if(self.photo_layers == None):
              _, self.photo_layers = self.call(p)
       # print(a)
       if(self.art_layers == None): 
              _, self.art_layers = self.call(a)
       # print(x) 
       _, input_layers = self.call(x)
         

       content_l = self.content_loss(self.photo_layers, input_layers)
       style_l = self.style_loss(self.art_layers, input_layers)
        # Equation 7
       print('style_loss', style_l) 
       print('content_loss', content_l) 
       return (self.alpha * content_l) + (self.beta * style_l)
        
    def content_loss(self, photo_layers, input_layers):
        L_content = tf.constant(0.0)
        for i in range(len(photo_layers)):
              pl = photo_layers[i]
              il = input_layers[i]
              L_content = tf.math.add(L_content, tf.reduce_mean(tf.square(pl - il)))
       
        #print('content loss', L_content)
        return L_content
    
    def layer_loss(self, art_layer, input_layer):
       # vectorize the art_layers
       art_layer = tf.reshape(art_layer, (-1, art_layer.shape[-1]))
       # # vectorize the input_layers
       input_layer = tf.reshape(input_layer, (-1, input_layer.shape[-1]))
       # get the gram matrices
       G_l = tf.matmul(tf.transpose(input_layer), input_layer)
       A_l = tf.matmul(tf.transpose(art_layer), art_layer)
       

       # vals = []
       # for i in range(input_dim):
       #        vals_i = []
       #        for j in range(input_dim):
       #               il = tf.reshape(input_layers[i], [-1])
       #               al = tf.reshape(art_layers[j], [-1])
       #               k = tf.reduce_sum(tf.multiply(il, al))
       #               vals_i.append(k)
       #        vals.append(tf.stack(vals_i))
       # G = tf.stack(vals)

       # get the loss per each lateral layer
       # N depends on # of filters in the layer, M depends on hight and width of feature map
       M_l = art_layer.shape[0]
       N_l = art_layer.shape[1]
       
       # layer.filters might not work
       E_l = 1/4 * (M_l**(-2)) *(N_l**(-2)) * tf.reduce_sum(tf.square(G_l - A_l))

       # while Sotech is botty:
       #         Jayson_tatum.tear_acl()
       #         return ("this is just another day")
       #print('Layer loss', E_l)
       return E_l

    def style_loss(self, art_layers, input_layers):
        L_style = tf.constant(0.0)
        for i in range(len(art_layers)):
            art_layer = art_layers[i]
            input_layer = input_layers[i]
            L_style = tf.math.add(L_style, self.layer_loss(art_layer, input_layer)*(1/5))
        #print('style loss', L_style)
        return L_style
            
    def train_step(self):
       with tf.GradientTape(watch_accessed_variables=False) as tape:
              tape.watch(self.x)
              loss = self.loss_fn(self.content_image, self.style_image, self.x)
       print('loss', loss)
       #print('self.x', self.x)
       gradients = tape.gradient(loss, [self.x])
       #print('gradients', gradients)
       self.optimizer.apply_gradients(zip(gradients, [self.x]))