-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
170 lines (135 loc) · 6.78 KB
/
main.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
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
import argparse
from random import choice
import re
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import Layer, Dense, LSTM, Flatten, TimeDistributed
from tensorflow.keras.layers import RepeatVector, Reshape, Conv2DTranspose
from tensorflow.keras.optimizers import Adam
max_query_length = 7
max_answer_length = 4
unique_characters = "0123456789+- "
class Encoder(Layer):
""" The section of the model that encodes the batch of onehot encoded matrices
to a matrix of latent vectors.
"""
def __init__(self, latent_dim):
""" latent_dim: dimension of the space where the input text is encoded to
"""
super().__init__()
# instantiate layers
self.lstm_1 = LSTM(latent_dim, return_sequences=True)
self.lstm_2 = LSTM(latent_dim, return_sequences=True)
self.lstm_3 = LSTM(latent_dim)
def call(self, inputs):
x = self.lstm_1(inputs)
x = self.lstm_2(x)
return self.lstm_3(x)
class Decoder(Layer):
""" The final part of the model responsible for upscaling each latent vector
to a sequence of 4 28x28 images.
"""
def __init__(self):
super().__init__()
# instantiate layers
self.repeat = RepeatVector(4)
self.lstm_1 = LSTM(256, return_sequences=True)
self.lstm_2 = LSTM(256, return_sequences=True)
self.time_distr_dense = TimeDistributed(Dense(1024, activation="relu"))
self.flatten = Flatten()
self.reshape = Reshape((64, 8, 8))
self.conv2d_transp_1 = Conv2DTranspose(8, 5, strides=1, data_format="channels_first")
self.conv2d_transp_2 = Conv2DTranspose(4, 6, strides=2, activation="sigmoid", data_format="channels_first")
def call(self, inputs):
x = self.repeat(inputs)
x = self.lstm_1(x)
x = self.lstm_2(x)
x = self.time_distr_dense(x)
x = self.flatten(x)
x = self.reshape(x)
x = self.conv2d_transp_1(x)
return self.conv2d_transp_2(x)
class Text2Image(tf.keras.Model):
""" Text to image model using an encoder-decoder structure
composed of LSTM and Conv2DTranspose layers.
Given a sequence of input characters representing
an addition/subtraction between two numbers of maximum 3 digits,
it outputs the result as a sequence of 4 28x28 images (sign and digits).
"""
def __init__(self, latent_dim=128):
super().__init__()
# instantiate encoder and decoder
self.encoder = Encoder(latent_dim=latent_dim)
self.decoder = Decoder()
def call(self, inputs):
embedding = self.encoder(inputs)
return self.decoder(embedding)
def build_graph(self):
x = tf.keras.layers.Input(shape=(max_query_length, len(unique_characters)))
return tf.keras.Model(inputs=[x], outputs=self.call(x))
def train(self, x_train, x_test, y_train, y_test, weights_path="training_output/weights"):
self.compile(loss="binary_crossentropy", optimizer=Adam(learning_rate=0.001), metrics=["mae"])
early_stop = tf.keras.callbacks.EarlyStopping(monitor="val_loss", mode="min", min_delta=0.0001, patience=20)
history = self.fit(x_train, y_train, epochs=100, batch_size=32, validation_split=0.05, callbacks=[early_stop])
self.evaluate(x_test, y_test)
self.save_weights(weights_path)
return history
def encode_text(text):
""" OneHot encode the input text into a 7x13 matrix
Each row represents a char
"""
char_map = dict(zip(unique_characters, range(len(unique_characters))))
one_hot_mat = np.zeros((1, max_query_length, len(unique_characters)))
for i, char in enumerate(text):
one_hot_mat[0, i, char_map[char]] = 1
return one_hot_mat
def save_output(output, output_path, img_name):
if output_path[-1] not in ["/", "\\"]:
img_name = "/" + img_name
for i in range(4):
plt.subplot(1, 4, i+1)
plt.imshow(output[0][i])
plt.axis("off")
plt.savefig(output_path + img_name + ".png")
print(f"Output saved in {output_path}{img_name}.png")
if __name__ == "__main__":
parser = argparse.ArgumentParser(formatter_class=argparse.MetavarTypeHelpFormatter)
parser.add_argument("--train", type=str, default=None, help="Path where to store trained weights")
parser.add_argument("--data", type=str, default=None, help="Path to dataset. The data should be in numpy \
format: x_text.npy and y_img.npy")
parser.add_argument("--train_size", type=float, default=0.8, help="Fraction of data to use for training the model")
parser.add_argument("--eval", type=str, default=None, help="String to evaluate. \
Must have the form ddd?ddd, d=digit or whitespace and ?=\"+\" or \"-\"")
parser.add_argument("--eval_out", type=str, default=".", help="Path where to store the output of the evaluation")
parser.add_argument("--pretrained", type=str, default=None, help="Path to pretrained weights")
parser.add_argument("--summary", help="Include this argument to print the summary of the model", action="store_true")
args = parser.parse_args()
if args.train is None and args.eval is None:
parser.error("Use at least one argument between --train and --eval.")
# instantiate t2i model and create weights
t2i = Text2Image(latent_dim=128)
t2i(tf.ones(shape=(1, max_query_length, len(unique_characters))))
if args.summary:
t2i.build_graph().summary()
if args.pretrained is not None:
t2i.load_weights(args.pretrained)
if args.train:
if args.data is None:
parser.error("Include the path to the dataset with --data.")
# load dataset and onehot encode it
x_text, y_img = np.load(args.data + "x_text.npy"), np.load(args.data + "y_img.npy")
x_text_oh = np.zeros((x_text.shape[0], max_query_length, len(unique_characters)))
for i, text in enumerate(x_text):
x_text_oh[i] = encode_text(text)
# start training
x_train, x_test, y_train, y_test = train_test_split(x_text_oh, y_img, test_size=1-args.train_size, shuffle=True, random_state=42)
t2i.train(x_train, x_test, y_train, y_test, weights_path=args.train)
if args.eval is not None:
# evaluate a single string given as argument --eval and save the output as a png
# check if the string has the correct format
if len(args.eval) != 7 or not re.search(r"(?: | \d|\d\d)\d(?:\+|-)(?: | \d|\d\d)\d", args.eval):
exit("Evaluation string must have the form ddd?ddd, d=digit or whitespace and ?=\"+\" or \"-\"")
else:
save_output(t2i(encode_text(args.eval)), output_path=args.eval_out, img_name=args.eval.replace(" ", ""))