Jakub Kwiatkowski commited on
Commit
38f87b5
·
1 Parent(s): 758ad23
_.py DELETED
@@ -1,14 +0,0 @@
1
- import os
2
-
3
- start_image = 12000
4
-
5
- from tensorflow.keras.models import load_model
6
- model = load_model("saved_model/1")
7
-
8
- from data_utils import nload, ims, DataSetFromFolder
9
- data = nload("/home/jkwiatkowski/all/dataset/arr/val.npy")
10
- indexes = nload("/home/jkwiatkowski/all/dataset/arr/val_target.npy")
11
-
12
- folders = DataSetFromFolder("/home/jkwiatkowski/all/dataset/arr/RAVEN-10000-release/RAVEN-10000", file_type="dir")
13
- properties = DataSetFromFolder(folders[:], file_type="xml", extension="val")
14
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models.py CHANGED
@@ -1,6 +1,5 @@
1
  import tensorflow as tf
2
  from config_utils import tf_gpu
3
- from data_utils import DataSetFromFolder
4
 
5
  tf_gpu()
6
  tf.experimental.numpy.experimental_enable_numpy_behavior(prefer_float32=True)
@@ -11,19 +10,7 @@ from datasets import load_dataset
11
  repo = "jkwiatkowski/raven"
12
 
13
  data = load_dataset(repo, split="val")
 
14
  model = from_pretrained_keras(repo)
15
 
16
- properties = load_dataset(repo + "_properties", split="val")
17
  START_IMAGE = 12000
18
-
19
-
20
- # def convert(data):
21
- # return {
22
- # 'inputs': tf.cast(data['inputs'], dtype="uint8"),
23
- # 'index': tf.cast(data['index'], dtype="uint8")[..., None],
24
- # 'target': tf.cast(data['target'], dtype="int8"),
25
- # }
26
- #
27
- # model(convert(data[0:1]))
28
-
29
- print("xD")
 
1
  import tensorflow as tf
2
  from config_utils import tf_gpu
 
3
 
4
  tf_gpu()
5
  tf.experimental.numpy.experimental_enable_numpy_behavior(prefer_float32=True)
 
10
  repo = "jkwiatkowski/raven"
11
 
12
  data = load_dataset(repo, split="val")
13
+ properties = load_dataset(repo + "_properties", split="val")
14
  model = from_pretrained_keras(repo)
15
 
 
16
  START_IMAGE = 12000
 
 
 
 
 
 
 
 
 
 
 
 
raven_utils/data.py DELETED
@@ -1,46 +0,0 @@
1
- import os
2
-
3
- import tensorflow as tf
4
-
5
- from models_utils import INPUTS, TARGET
6
-
7
- from raven_utils.config.constant import RAVEN, LABELS, INDEX, FEATURES, RAV_METRICS, IMP_RAV_METRICS, ACC_NO_GROUP
8
-
9
-
10
- from typing import Any
11
-
12
- from data_utils import pre, Data, gather, vec, resize
13
- from data_utils.data_generator import DataGenerator
14
- from funcy import identity
15
-
16
-
17
- def get_data(data, batch_size, steps=None, val_steps=None):
18
- if val_steps is None:
19
- val_steps = steps
20
- fn = identity
21
- train_target_index = data[4] + 8
22
- train_generator = DataGenerator({
23
- INPUTS: Data(data[0], fn),
24
- TARGET: Data(data[2], identity),
25
- LABELS: Data(data[2], identity),
26
- INDEX: train_target_index[:, None],
27
- # FEATURES: data[6]
28
- },
29
- batch=batch_size,
30
- steps=steps
31
- )
32
- val_target_index = data[5] + 8
33
- val_data = {
34
- INPUTS: Data(data[1], fn),
35
- TARGET: Data(data[3], identity),
36
- LABELS: Data(data[3], identity),
37
- INDEX: val_target_index[:, None],
38
- # FEATURES: data[7]
39
- }
40
- val_generator = DataGenerator(
41
- val_data,
42
- batch=batch_size,
43
- sampler="val",
44
- steps=val_steps
45
- )
46
- return train_generator, val_generator
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
raven_utils/decode.py CHANGED
@@ -1,9 +1,24 @@
1
  import numpy as np
2
- from data_utils import np_split
3
- from ml_utils import lw
4
- from models_utils.ops import ibin
5
-
6
  import raven_utils as rv
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
 
9
  def output(x, split_fn=np_split, predict_fn_1=np.argmax, predict_fn_2=ibin):
@@ -62,8 +77,6 @@ def decode_target(target):
62
  return target_group, target_slot, target_properties_splited
63
 
64
 
65
-
66
-
67
  def decode_target_flat(target):
68
  t = decode_target(target)
69
  return t[0], t[1], t[2][0], t[2][1], t[2][2]
@@ -78,17 +91,19 @@ def demask(target, mask=None, group=None, zeroes=None):
78
  mask = RangeMask()(group).numpy()
79
  if zeroes is None:
80
  return np.concatenate([t[mask] for t in lw(target[1:])])
81
- return np.concatenate([target[0][None]] + [t * mask for t in lw(target[1:])],axis=-1)
82
 
83
 
84
- def target_mask(mask,right=1):
85
  shape = mask.shape
86
- return np.concatenate([np.ones([shape[0], 1]) ,mask, np.repeat(mask,3,axis=1), np.ones([shape[0], right])],axis=1)
 
87
 
88
 
89
  def get_full_range_mask(mask):
90
  return np.concatenate([mask, np.repeat(mask, 3, axis=-1)], axis=-1)
91
 
 
92
  def compare(target, predict, mask):
93
  target_comp = target[:, 1:rv.target.END_INDEX]
94
  predict_comp = predict[:, 1:rv.target.END_INDEX]
 
1
  import numpy as np
 
 
 
 
2
  import raven_utils as rv
3
+ import tensorflow as tf
4
+
5
+
6
+ def np_split(ary, indices_or_sections, axis=-1):
7
+ return np.split(ary, np.cumsum(indices_or_sections), axis)[:-1]
8
+
9
+ def lw(data, none_empty=True, convert_tuple=True):
10
+ if isinstance(data, list):
11
+ return data
12
+ elif isinstance(data, tuple) and convert_tuple:
13
+ return list(data)
14
+ if none_empty and data is None:
15
+ return []
16
+ return [data]
17
+
18
+
19
+
20
+ def ibin(x):
21
+ return tf.cast(bin(x), dtype=tf.int32)
22
 
23
 
24
  def output(x, split_fn=np_split, predict_fn_1=np.argmax, predict_fn_2=ibin):
 
77
  return target_group, target_slot, target_properties_splited
78
 
79
 
 
 
80
  def decode_target_flat(target):
81
  t = decode_target(target)
82
  return t[0], t[1], t[2][0], t[2][1], t[2][2]
 
91
  mask = RangeMask()(group).numpy()
92
  if zeroes is None:
93
  return np.concatenate([t[mask] for t in lw(target[1:])])
94
+ return np.concatenate([target[0][None]] + [t * mask for t in lw(target[1:])], axis=-1)
95
 
96
 
97
+ def target_mask(mask, right=1):
98
  shape = mask.shape
99
+ return np.concatenate([np.ones([shape[0], 1]), mask, np.repeat(mask, 3, axis=1), np.ones([shape[0], right])],
100
+ axis=1)
101
 
102
 
103
  def get_full_range_mask(mask):
104
  return np.concatenate([mask, np.repeat(mask, 3, axis=-1)], axis=-1)
105
 
106
+
107
  def compare(target, predict, mask):
108
  target_comp = target[:, 1:rv.target.END_INDEX]
109
  predict_comp = predict[:, 1:rv.target.END_INDEX]
raven_utils/draw.py CHANGED
@@ -1,19 +1,16 @@
1
  import numpy as np
2
- from data_utils import take, EXIST, COR
3
- from data_utils.image import draw_images, add_text
4
  from funcy import identity
5
- from ml_utils import none, filter_keys, lu
6
- from models_utils import is_model
7
- from models_utils import ops as K
8
- from tensorflow.python.saved_model.load import Loader
9
 
10
  from raven_utils.constant import PROPERTY, TARGET, INPUTS
11
  from raven_utils.decode import decode_target, target_mask
 
12
  from raven_utils.render.rendering import render_panels
13
  from raven_utils.render_ import TYPES, SIZES
 
14
  from raven_utils.uitls import get_val_index
15
 
16
 
 
17
  def draw_board(images, target=None, predict=None, image=None, desc=None, layout=None, break_=20):
18
  if image != "target" and predict is not None:
19
  image = images[predict:predict + 1]
@@ -78,9 +75,6 @@ def draw_raven(data, predict=None, pre_fn=identity, layout=1):
78
  res = predict(d)
79
  pro = np.array(target_mask(res['mask'].numpy()) * res["predict"].numpy(),dtype=np.int8)
80
  predict = pre_fn(render_panels(pro, target=False)[None])[0]
81
- # from data_utils import ims
82
- # ims(1 - predict[0])
83
- # if target is not None:
84
  target = data[TARGET]
85
  target_index = data["index"]
86
  images = data[INPUTS]
 
1
  import numpy as np
 
 
2
  from funcy import identity
 
 
 
 
3
 
4
  from raven_utils.constant import PROPERTY, TARGET, INPUTS
5
  from raven_utils.decode import decode_target, target_mask
6
+ from raven_utils.image import EXIST, COR, draw_images, add_text
7
  from raven_utils.render.rendering import render_panels
8
  from raven_utils.render_ import TYPES, SIZES
9
+ from raven_utils.tools import none, is_model, filter_keys
10
  from raven_utils.uitls import get_val_index
11
 
12
 
13
+
14
  def draw_board(images, target=None, predict=None, image=None, desc=None, layout=None, break_=20):
15
  if image != "target" and predict is not None:
16
  image = images[predict:predict + 1]
 
75
  res = predict(d)
76
  pro = np.array(target_mask(res['mask'].numpy()) * res["predict"].numpy(),dtype=np.int8)
77
  predict = pre_fn(render_panels(pro, target=False)[None])[0]
 
 
 
78
  target = data[TARGET]
79
  target_index = data["index"]
80
  images = data[INPUTS]
raven_utils/group.py CHANGED
@@ -1,5 +1,3 @@
1
- import numpy as np
2
-
3
  NAMES = ['center_single',
4
  'distribute_four',
5
  'distribute_nine',
 
 
 
1
  NAMES = ['center_single',
2
  'distribute_four',
3
  'distribute_nine',
raven_utils/image.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ from itertools import groupby
4
+ import numpy as np
5
+ from matplotlib import pyplot as plt, colors
6
+ from skimage.transform import resize
7
+
8
+ # todo different backend maybe diffrent files thata have partial
9
+ # todo depend on mode different min and max
10
+ from raven_utils.tools import is_num, il, image_type, lw, is_int, dict_from_list, if_images, download_file, \
11
+ dir_decorator, list_dir
12
+
13
+ TRAIN = "train"
14
+ VAL = "val"
15
+ TEST = "test"
16
+ COLOR = "color"
17
+ SIZE = "size"
18
+ EXIST = "exist"
19
+ COR = "cor"
20
+ TARGET_SIZE = "target_size"
21
+
22
+
23
+ # https://github.com/qubvel/efficientnet/blob/master/efficientnet/preprocessing.py
24
+ MAP_INTERPOLATION_TO_ORDER = {
25
+ "nearest": 0,
26
+ "bilinear": 1,
27
+ "biquadratic": 2,
28
+ "bicubic": 3,
29
+ }
30
+
31
+
32
+ def center_crop_and_resize(image, image_size, crop_padding=32, interpolation="bicubic"):
33
+ assert image.ndim in {2, 3}
34
+ assert interpolation in MAP_INTERPOLATION_TO_ORDER.keys()
35
+
36
+ h, w = image.shape[:2]
37
+
38
+ padded_center_crop_size = int(
39
+ (image_size / (image_size + crop_padding)) * min(h, w)
40
+ )
41
+ offset_height = ((h - padded_center_crop_size) + 1) // 2
42
+ offset_width = ((w - padded_center_crop_size) + 1) // 2
43
+
44
+ image_crop = image[
45
+ offset_height: padded_center_crop_size + offset_height,
46
+ offset_width: padded_center_crop_size + offset_width,
47
+ ]
48
+ resized_image = resize(
49
+ image_crop,
50
+ (image_size, image_size),
51
+ order=MAP_INTERPOLATION_TO_ORDER[interpolation],
52
+ preserve_range=True,
53
+ )
54
+
55
+ return resized_image
56
+
57
+
58
+ def im_conv(image):
59
+ return image.astype(np.float32) / 255.
60
+
61
+
62
+ def add_dim(x):
63
+ return x[..., None]
64
+
65
+
66
+ def im_conv_black(image):
67
+ return image[..., np.newaxis].astype(np.float32) / 255.
68
+
69
+
70
+ def im_resolve(image):
71
+ return (image * 255).astype(np.uint8)
72
+
73
+
74
+ def minmax(data, axis=None, scale=1.0):
75
+ return ((data - np.min(data, axis=axis)) / (np.max(data, axis=axis) - np.min(data, axis=axis))) * scale
76
+
77
+
78
+ def inverse(x):
79
+ return 1.0 - x
80
+
81
+
82
+ def standarize(img, scaler=0.15, batch=True):
83
+ indexes = tuple(range(1 if batch else 0, img.ndim))
84
+ img = np.array(img)
85
+ img -= np.mean(img, axis=indexes)[tuple([slice(None)] + [None] * len(indexes))]
86
+ img /= np.std(img, axis=indexes)[tuple([slice(None)] + [None] * len(indexes))] + 1e-5
87
+ img *= scaler
88
+ return img
89
+
90
+
91
+ def image_standardization(img, scaler=0.15):
92
+ indexes = tuple(range(1, 4))
93
+ img -= np.mean(img, axis=indexes)
94
+ img /= np.std(img, axis=indexes) + 1e-5
95
+ img *= scaler
96
+ return img
97
+
98
+
99
+ def clip_standardized(img, min=0, max=1):
100
+ img += (max - min) / 2
101
+ return np.clip(img, min, max)
102
+
103
+
104
+ def deprocess_image(img, clip=True):
105
+ # Normalize array: center on 0., ensure variance is 0.15
106
+ img = image_standardization(img)
107
+ if clip:
108
+ img = clip_standardized(img)
109
+ return img
110
+
111
+
112
+ # def im_conv_tf(image,dtype=tf.float32):
113
+ # return tf.image.convert_image_dtype(image,dtype)
114
+
115
+ # todo Grid on edges
116
+ # todo different channels
117
+ def draw_images(data, col=-1, row=-1, grid=True, border=None, mark=None, grid_args={}, border_kwargs={}, *args,
118
+ **kwargs):
119
+ figure, shape = create_grid(data, row=row, col=col, *args, **kwargs)
120
+ if border is not None:
121
+ add_border(figure, border, **border_kwargs)
122
+ figure = create_image_from_grid(figure, *args, **kwargs)
123
+
124
+ if grid:
125
+ figure = add_grid(figure, shape[-3:], **grid_args)
126
+ return figure
127
+
128
+
129
+ def draw_images2(data, col=-1, row=-1, grid=True, color=1, border=None, border_kwargs={}, *args,
130
+ **kwargs):
131
+ figure, shape = create_grid(data, row=row, col=col, *args, **kwargs)
132
+ if border is not None:
133
+ add_border(figure, border, **border_kwargs)
134
+ figure = fill_canvas(figure, color=color, grid=grid)
135
+ return figure
136
+
137
+
138
+ def draw_images3(data, col=-1, row=-1, grid=True, border=None, mark=None, grid_args={}, border_kwargs={}, *args,
139
+ **kwargs):
140
+ if len(np.asarray(data).shape) < 4:
141
+ return data
142
+
143
+ return draw_images(data=data,
144
+ col=col,
145
+ row=row,
146
+ grid=grid,
147
+ border=border,
148
+ mark=mark,
149
+ grid_args=grid_args,
150
+ border_kwargs=border_kwargs,
151
+ *args,
152
+ **kwargs
153
+ )
154
+
155
+
156
+ def fill_canvas(a, color=1, grid=10):
157
+ if not isinstance(a, np.ndarray):
158
+ a = np.asarray(a)
159
+ if grid is True:
160
+ grid = 10
161
+ shape = a.shape
162
+ move_r = shape[2] + grid
163
+ move_c = shape[3] + grid
164
+ if color is None:
165
+ color = 0
166
+ if is_num(color):
167
+ color = np.full((move_r * shape[0], move_c * shape[1]) + shape[-1:], fill_value=color, dtype=a.dtype)
168
+ for r in range(shape[0]):
169
+ for c in range(shape[1]):
170
+ color[move_r * r:move_r * r + shape[2], move_c * c:move_c * c + shape[3]] = a[r, c]
171
+ return color
172
+
173
+
174
+ def create_grid(
175
+ data,
176
+ row=-1,
177
+ col=-1,
178
+ mode="auto",
179
+ # Method for creating grid if row and col not set. Even evenly for row and cows. Shape take shape from input data. Auto use shape for input data that have more then 4 dimention, otherwise even.
180
+ swap=False, # swaping row and columns
181
+ *args, **kwargs):
182
+ if il(data):
183
+ for i, d in enumerate(data):
184
+ if len(d.shape) > 4:
185
+ data[i] = draw_images(d)
186
+ elif len(d.shape) < 3:
187
+ data[i] = d[..., np.newaxis]
188
+ shapes = [d.shape for d in data]
189
+ # padding to make all images same size
190
+ if not all_equal(shapes):
191
+ mh = np.max([sh[-3] for sh in shapes])
192
+ mw = np.max([sh[-2] for sh in shapes])
193
+ canvas = np.zeros((len(data), mh, mw, shapes[0][-1]))
194
+ for j, d in enumerate(data):
195
+ canvas[j, :d.shape[-3], :d.shape[-2]] = d
196
+ data = canvas
197
+ data = np.asarray(data)
198
+ shape = data.shape
199
+ # check in case of no channels
200
+ if shape[-1] > 4:
201
+ data = data[..., np.newaxis]
202
+ shape = data.shape
203
+ if swap and len(shape) > 4:
204
+ data = data.swapaxes(-4, -5)
205
+ h = shape[-3]
206
+ w = shape[-2]
207
+ c = shape[-1]
208
+ if len(shape) > 4:
209
+ im_no = shape[-5] * shape[-4]
210
+ elif len(shape) == 4:
211
+ im_no = shape[-4]
212
+ else:
213
+ return data, shape
214
+ if row == -1 and col == -1:
215
+ if mode == "auto":
216
+ mode = "shape" if len(shape) > 4 else "even"
217
+ if mode == "shape":
218
+ row = shape[-5] if len(shape) > 4 else shape[-4]
219
+ elif mode == "even":
220
+ row = math.ceil(np.sqrt(im_no))
221
+ else:
222
+ row = shape[-5] if len(shape) > 4 else math.ceil(np.sqrt(im_no))
223
+ # eh = -1 if row == -1 else row * h
224
+ # ew = -1 if column == -1 else column * w
225
+ # if number of images is less then available slots in grid add blank images
226
+ if row == -1:
227
+ eh = -1
228
+ m = im_no % col
229
+ if m != 0:
230
+ data = np.concatenate([data, np.zeros((col - m,) + shape[-3:])], axis=-4)
231
+ else:
232
+ eh = row * h
233
+ if col == -1:
234
+ ew = -1
235
+ m = im_no % row
236
+ if m != 0:
237
+ data = np.concatenate([data, np.zeros((row - m,) + shape[-3:])], axis=-4)
238
+ else:
239
+ ew = col * h
240
+ figure = data.reshape(row, col, h, w, c)
241
+ import time
242
+ time.sleep(0.1)
243
+ return figure, shape
244
+
245
+
246
+ def create_image_from_grid(grid, *args, **kwargs):
247
+ shape = grid.shape
248
+ figure = grid.swapaxes(1, 2).reshape(shape[0] * shape[2], shape[1] * shape[3], shape[4])
249
+ return figure
250
+
251
+
252
+ # todo For more dimention
253
+ def add_grid(figure, shape, left=True, right=True, color=1.00, hor=True, ver=True):
254
+ revers = False
255
+ if len(figure.shape) == 2:
256
+ figure = figure[..., None]
257
+ reverse = True
258
+ if hor:
259
+ figure[shape[0]::shape[0], :, :] = color
260
+ if ver:
261
+ figure[:, shape[1]::shape[1], :] = color
262
+ if left:
263
+ figure[0, :, :] = color
264
+ figure[0, :] = color
265
+ if right:
266
+ figure[figure.shape[0] - 1, :, :] = color
267
+ figure[:, ::figure.shape[1] - 1, :] = color
268
+ if revers:
269
+ figure = figure[..., 0]
270
+ return figure
271
+
272
+
273
+ def add_border(figure, cor, exist=True, size=4, color="auto"):
274
+ if color == "auto":
275
+ info = image_type(figure)
276
+ if info.mode == "RGB":
277
+ color = np.array(colors.to_rgb("red")) * info.range_[1]
278
+ else:
279
+ color = info.range_[1]
280
+ if info.reverse:
281
+ color = info.range_[1] - color
282
+
283
+ shape = figure.shape
284
+ for c in lw(cor):
285
+ if not isinstance(c, dict):
286
+ c = dict_from_list([COR, EXIST, SIZE, COLOR], c)
287
+ c = {
288
+ **{
289
+ EXIST: exist if il(exist) else [exist] * 4,
290
+ SIZE: size,
291
+ COLOR: color
292
+ },
293
+ **c
294
+ }
295
+
296
+ if is_int(lw(c[EXIST])[0]):
297
+ c[EXIST] = K.mask(4, c[EXIST])
298
+ if is_int(c[COR]):
299
+ c[COR] = c[COR] // shape[1], c[COR] % shape[1]
300
+ isinstance(lw(c[EXIST])[0], np.integer)
301
+
302
+ cr = c[COR]
303
+ if c[EXIST][0]:
304
+ figure[cr[0], cr[1], 0:c[SIZE], :] = c[COLOR]
305
+ if c[EXIST][1]:
306
+ figure[cr[0], cr[1], :, shape[3] - c[SIZE]:shape[3]] = c[COLOR]
307
+ if c[EXIST][2]:
308
+ figure[cr[0], cr[1], shape[2] - c[SIZE]:shape[2], :] = c[COLOR]
309
+ if c[EXIST][3]:
310
+ figure[cr[0], cr[1], :, 0:c[SIZE]] = c[COLOR]
311
+ return figure
312
+
313
+
314
+ # todo hgih tmp fix
315
+ def get_digitilizer(min=0, max=1, steps=10, mode="numpy"):
316
+ bins = np.linspace(min, max, steps)
317
+ bins = bins + (bins[1] - bins[0]) / 2
318
+ # if mode == "tf":
319
+ # from tensorflow.ops import math_ops
320
+ # func = math_ops._bucketize
321
+ # bins = list(bins)
322
+ # else:
323
+ func = np.digitize
324
+
325
+ def digitilizer(x):
326
+ return func(x, bins)
327
+
328
+ return digitilizer
329
+
330
+
331
+ def save_image_pil(path, data, *args, **kwargs):
332
+ from PIL import Image
333
+ if not isinstance(data, np.ndarray):
334
+ data = np.array(data)
335
+ if if_images(data):
336
+ data = draw_images2(data, *args, **kwargs)
337
+ if np.max(data) <= 1:
338
+ data = im_resolve(data)
339
+ if np.shape(data)[-1] == 1:
340
+ data = data[..., 0]
341
+ img = Image.fromarray(np.array(data, dtype="uint8"))
342
+ # test if black or wihte
343
+ if data.shape[-1] not in [3, 4]:
344
+ img = img.convert('L')
345
+ # todo maybe just check type for np.float
346
+ if path is None:
347
+ img.show()
348
+ else:
349
+ img.save(path)
350
+
351
+
352
+ def save_image_pil2(path, data, *args, **kwargs):
353
+ from PIL import Image
354
+ if np.max(data) <= 1:
355
+ data = im_resolve(data)
356
+ if len(np.shape(data)) == 3 and np.shape(data)[-1] == 1:
357
+ data = data[..., 0]
358
+ img = Image.fromarray(data)
359
+ if len(data.shape) == 2 or (len(data.shape == 3) and data.shape[2] == 1):
360
+ img = img.convert('L')
361
+ # todo maybe just check type for np.float
362
+ if path is None:
363
+ img.show()
364
+ else:
365
+ img.save(path)
366
+
367
+
368
+ #
369
+ # https://towardsdatascience.com/how-to-create-a-gif-from-matplotlib-plots-in-python-6bec6c0c952c
370
+ # duration, fps, loop
371
+ def save_gif(path, data,sort_fn="first", *args, **kwargs):
372
+ data = get_paths_(data, sort_fn=sort_fn)
373
+ import imageio
374
+ with imageio.get_writer(path, mode='I', *args, **kwargs) as writer:
375
+ for filename in data:
376
+ image = imageio.imread(filename)
377
+ writer.append_data(image)
378
+
379
+
380
+ # https://stackoverflow.com/questions/44947505/how-to-make-a-movie-out-of-images-in-python
381
+ # https://docs.opencv.org/4.x/dd/d9e/classcv_1_1VideoWriter.html#ad59c61d8881ba2b2da22cff5487465b5
382
+ # https://github.com/ContinuumIO/anaconda-issues/issues/223
383
+ # https://softron.zendesk.com/hc/en-us/articles/207695697-List-of-FourCC-codes-for-video-codecs
384
+ def save_video(path, data, *args, fps=1, fourcc="MJPG",sort_fn="first", **kwargs):
385
+ data = get_paths_(data, sort_fn=sort_fn)
386
+
387
+ import cv2
388
+
389
+ frame = cv2.imread(data[0])
390
+ height, width, layers = frame.shape
391
+
392
+ if isinstance(fourcc, str):
393
+ fourcc = cv2.VideoWriter_fourcc(*fourcc)
394
+ video = cv2.VideoWriter(path, fourcc, fps, (width, height))
395
+
396
+ for image in data:
397
+ video.write(cv2.imread(image))
398
+
399
+ cv2.destroyAllWindows()
400
+ video.release()
401
+
402
+
403
+ def get_paths_(data, sort_fn="first"):
404
+ if isinstance(data, str):
405
+ data = list_dir(data, sort_fn=sort_fn)
406
+ return data
407
+
408
+
409
+ def add_text(ax, text, pos=None, star_x=25, start_y=25, row_size=30):
410
+ text = lw(text)
411
+ if pos is None:
412
+ pos = [(star_x, start_y + i * row_size) for i in range(len(text))]
413
+ pos = lw(pos)
414
+ for i, t in enumerate(text):
415
+ # draw.text(pos[i], t,fill="black")
416
+ ax.text(pos[i][0], pos[i][1], t)
417
+
418
+
419
+ @dir_decorator
420
+ def save_image(path, data, description=None, size=None, dpi=None, *args, **kwargs):
421
+ if not isinstance(data, np.ndarray):
422
+ data = np.array(data)
423
+ fig = plt.figure()
424
+ if size is not None:
425
+ fig.set_size_inches(size)
426
+ # if title is not None:
427
+ # plt.title(title)
428
+ ax = plt.Axes(fig, [0., 0., 1., 1.])
429
+ ax.set_axis_off()
430
+ fig.add_axes(ax)
431
+ if len(data.shape) == 2 or data.shape[-1] == 1:
432
+ # plt.set_cmap('Greys_r')
433
+ plt.set_cmap('Greys')
434
+ else:
435
+ plt.set_cmap('hot')
436
+ if if_images(data):
437
+ data = draw_images(data, *args, **kwargs)
438
+ ax.imshow(data, aspect='equal')
439
+ if description is not None:
440
+ add_text(ax, description, star_x=data.shape[1])
441
+
442
+ params = {
443
+ "fname": path,
444
+ "bbox_inches": 'tight',
445
+ "pad_inches": 0
446
+ }
447
+ if dpi is not None:
448
+ params['dpi'] = dpi
449
+ if path is None:
450
+ plt.show()
451
+ else:
452
+ plt.savefig(**params)
453
+ plt.clf()
454
+
455
+
456
+ SAMPLE_IMAGES = {
457
+ "panda": "~/all/dataset/examples/panda.jpg",
458
+ "cat": "~/all/dataset/examples/cat.jpg",
459
+ }
460
+
461
+
462
+ def load_image(path=None, dtype="uint8", *args, **kwargs):
463
+ from tensorflow.keras.preprocessing import image
464
+ if path is None:
465
+ path = os.path.expanduser(SAMPLE_IMAGES["panda"])
466
+ if not os.path.isfile(path):
467
+ os.makedirs(os.path.dirname(path), exist_ok=True)
468
+ download_file("https://upload.wikimedia.org/wikipedia/commons/f/fe/Giant_Panda_in_Beijing_Zoo_1.JPG", path)
469
+ if not TARGET_SIZE in kwargs:
470
+ kwargs[TARGET_SIZE] = (224, 224)
471
+ elif path == "cat":
472
+ path = os.path.expanduser(SAMPLE_IMAGES["cat"])
473
+ kwargs[TARGET_SIZE] = (224, 224)
474
+
475
+ img = image.load_img(path, *args, **kwargs)
476
+ img = image.img_to_array(img, dtype=dtype)
477
+ return img
478
+
479
+
480
+ def to_rgb(img, add_dim=True, check_dim=True):
481
+ shape = np.shape(img)
482
+ if add_dim and shape[-1] > 4:
483
+ img = img[..., None]
484
+ shape = np.shape(img)
485
+ if check_dim and shape[-1] != 1:
486
+ return img
487
+ return np.tile(img, reps=(1, 1, 3))
488
+
489
+ # https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical
490
+ def all_equal(iterable, key=None):
491
+ g = groupby(iterable, key=key)
492
+ return next(g, True) and not next(g, False)
raven_utils/params.py DELETED
@@ -1,110 +0,0 @@
1
- from dataclasses import dataclass
2
- from typing import Any, Tuple
3
-
4
- from ml_utils import get_str_name
5
- from grid_transformer.params import ImgSeqTransformerParameters
6
- from raven_utils import output
7
-
8
- from experiment_utils.parameters.nn_default import TP, EP
9
-
10
-
11
- @dataclass
12
- class SudokuParameters(ImgSeqTransformerParameters):
13
- mask: str = "input"
14
- col: int = 3
15
- row: int = 3
16
- pooling: int = 81
17
- output_size: int = 9
18
- size: int = 384
19
-
20
-
21
- @dataclass
22
- class RavenTransParameters(ImgSeqTransformerParameters):
23
- mask: str = "last"
24
- last_index: int = 8
25
- col: int = 1
26
- row: int = 1
27
- output_size: int = output.SIZE
28
- number_loss: bool = 0
29
- pre: str = "images"
30
- num_heads: int = 8
31
-
32
-
33
- MP = RavenTransParameters
34
-
35
-
36
- @dataclass
37
- class RavenSelectTransParameters(RavenTransParameters):
38
- select_type: int = 2
39
- select_out: int = 0
40
- additional_out: int = 0
41
- additional_copy: bool = True
42
- tail_out: Tuple = (1000, 1000)
43
- pre: str = "index"
44
-
45
-
46
- SMP = RavenSelectTransParameters
47
-
48
- from raven_utils.config.models import AVAILABLE_MODELS
49
- from experiment_utils.parameters.nn_clean import Parameters as BaseParameters
50
- from raven_utils.config.constant import RAVEN, LABELS, INDEX, FEATURES, RAV_METRICS, IMP_RAV_METRICS, ACC_NO_GROUP, \
51
- ACC_SAME
52
-
53
- MODEL_NO = -1
54
-
55
-
56
- @dataclass
57
- class RavenParameters(BaseParameters):
58
- dataset_name: str = RAVEN
59
- data: Any = (
60
- f"{dataset_name}/train.npy",
61
- f"{dataset_name}/val.npy",
62
- f"{dataset_name}/train_labels.npy",
63
- f"{dataset_name}/val_labels.npy",
64
- f"{dataset_name}/train_target.npy",
65
- f"{dataset_name}/val_target.npy",
66
- f"arr/train_features_{AVAILABLE_MODELS[MODEL_NO]}.npy",
67
- f"arr/val_features_{AVAILABLE_MODELS[MODEL_NO]}.npy",
68
- f"{dataset_name}/val_index.npy"
69
- # DataParameters2()
70
- )
71
-
72
- # core_metrics: tuple = tuple(RAV_METRICS)
73
- filter_metrics: tuple = tuple(IMP_RAV_METRICS)
74
- # result_metric: str = ACC_NO_GROUP
75
- result_metric: str = ACC_SAME
76
-
77
- lw: float = 0.0001 # Autoencoder
78
- loss_weight: float = 2.0
79
- plw: int = 5.0
80
- mp: RavenTransParameters = RavenTransParameters()
81
-
82
- @property
83
- def experiment(self):
84
- # return "rav/trans"
85
- return "rav/best_test3"
86
- # return "rav/trans_weight"
87
-
88
- # @property
89
- # def name(self):
90
- # # return f"i{self.extractor}_{len(self.tail)}{self.tail[0]}_{self.type_}_{self.epsilon}_{self.last}_{self.epsilon_step}"
91
- # return f"{get_str_name(self.mp.pre)[0]}_{str(self.plw)[0]}_{str(self.mp.number_loss)[0]}_{self.mp.extractor}_{self.mp.noise if self.mp.noise else ''}_{self.mp.augmentation if self.mp.augmentation else ''}_{self.mp.extractor_shape}_{self.mp.no}_{self.mp.num_heads}_{self.mp.size}_{self.mp.pos_emd}_{self.mp.ff_mul}_{self.tp.batch}"
92
-
93
-
94
- @dataclass
95
- class BaselineRavenParameters(RavenParameters):
96
-
97
- @property
98
- def experiment(self):
99
- # return "rav/best_test3"
100
- return "rav/baseline"
101
- # return "rav/trans_weight"
102
-
103
- @property
104
- def name(self):
105
- # return f"i{self.extractor}_{len(self.tail)}{self.tail[0]}_{self.type_}_{self.epsilon}_{self.last}_{self.epsilon_step}"
106
- return f"{get_str_name(self.mp.pre)[0]}_{str(self.plw)[0]}_{str(self.mp.number_loss)[0]}_{self.mp.extractor}_{self.mp.noise if self.mp.noise else ''}_{self.mp.augmentation if self.mp.augmentation else ''}_{self.mp.extractor_shape}_{self.mp.no}_{self.mp.num_heads}_{self.mp.size}_{self.mp.pos_emd}_{self.mp.ff_mul}_{self.tp.batch}"
107
-
108
-
109
- if __name__ == '__main__':
110
- params = PreRavenTransParameters()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
raven_utils/properties.py CHANGED
@@ -1,6 +1,6 @@
1
- import raven_utils as rv
2
- from ml_utils import dict_from_list2, CalcDict
3
  import raven_utils.entity as entity
 
4
 
5
  NAMES = [
6
  'Color',
 
1
+
 
2
  import raven_utils.entity as entity
3
+ from raven_utils.tools import dict_from_list2, CalcDict
4
 
5
  NAMES = [
6
  'Color',
raven_utils/render/rendering.py CHANGED
@@ -6,10 +6,11 @@ import numpy as np
6
  from PIL import Image
7
  #
8
  # from AoT import Root
 
 
9
  import raven_utils.decode
10
  from raven_utils.render.const import CENTER, DEFAULT_WIDTH, IMAGE_SIZE
11
 
12
- from data_utils import Bag
13
 
14
  from raven_utils.render_ import COLOR_VALUES, SIZE_VALUES, TYPE_VALUES, ANGLE_VALUES, RENDER_POSITIONS
15
 
 
6
  from PIL import Image
7
  #
8
  # from AoT import Root
9
+ from data_utils import Bag
10
+
11
  import raven_utils.decode
12
  from raven_utils.render.const import CENTER, DEFAULT_WIDTH, IMAGE_SIZE
13
 
 
14
 
15
  from raven_utils.render_ import COLOR_VALUES, SIZE_VALUES, TYPE_VALUES, ANGLE_VALUES, RENDER_POSITIONS
16
 
raven_utils/rules.py CHANGED
@@ -1,4 +1,5 @@
1
- from ml_utils import dict_from_list
 
2
  COMBINE = "Number/Position"
3
 
4
  ATTRIBUTES = [
 
1
+ from raven_utils.tools import dict_from_list
2
+
3
  COMBINE = "Number/Position"
4
 
5
  ATTRIBUTES = [
raven_utils/tools.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ import inspect
3
+ import os
4
+ import re
5
+ import shutil
6
+ from functools import partial
7
+ from typing import Dict, Counter, Tuple
8
+ import operator
9
+
10
+ import numpy as np
11
+ import requests
12
+ from data_utils import ColumnIndexer, Dynamic
13
+ from funcy import rcompose, identity
14
+ from loguru import logger
15
+ from tensorflow.keras import Model, Sequential
16
+ from tensorflow.keras.layers import Layer
17
+ from tensorflow.keras.losses import Loss
18
+
19
+
20
+ def dir_decorator(fn):
21
+ def deco(path, *args, **kwargs):
22
+ if path is not None:
23
+ folder = os.path.dirname(path)
24
+ if folder:
25
+ os.makedirs(folder, exist_ok=True)
26
+ return fn(path, *args, **kwargs)
27
+
28
+ return deco
29
+
30
+ def extract_args(args):
31
+ if il(args):
32
+ if il(args[0]):
33
+ return tuple(args[0])
34
+ return tuple(args)
35
+ return tuple(lw(args))
36
+
37
+
38
+ def comp(*args):
39
+ return rcompose(*extract_args(args))
40
+
41
+
42
+ def is_model(obj):
43
+ return isinstance(obj, (Model, Layer, Loss))
44
+
45
+ def list_dir(root):
46
+ for path in os.listdir(root):
47
+ yield os.path.join(root, path)
48
+
49
+ def is_int(obj, bool_=False):
50
+ if not bool_ and isinstance(obj, bool):
51
+ return False
52
+ return isinstance(obj, (int, np.integer))
53
+ # return issubclass(type(obj),int)
54
+
55
+
56
+ def is_float(obj):
57
+ return isinstance(obj, (float, np.float))
58
+
59
+
60
+ def is_num(obj, bool_=False):
61
+ return is_int(obj, bool_) or is_float(obj)
62
+
63
+
64
+ def get_args(obj):
65
+ try:
66
+ return list(inspect.signature(obj).parameters.keys())
67
+ except Exception as e:
68
+ logger.error(f"{e}. Returning 1.")
69
+ return ["arg"]
70
+
71
+
72
+ def il(data):
73
+ return isinstance(data, (list, tuple))
74
+
75
+
76
+ def lw(data, none_empty=True, convert_tuple=True):
77
+ if isinstance(data, list):
78
+ return data
79
+ elif isinstance(data, tuple) and convert_tuple:
80
+ return list(data)
81
+ if none_empty and data is None:
82
+ return []
83
+ return [data]
84
+
85
+
86
+ def dict_from_list(keys=None, values=None) -> Dict:
87
+ if values is None:
88
+ values = list(range(len(lw(keys))))
89
+ elif callable(values):
90
+ values = [values(k) for k in keys]
91
+ if keys is None:
92
+ keys = list(range(len(lw(values))))
93
+ elif callable(keys):
94
+ keys = [keys(v) for v in values]
95
+ if not isinstance(values, dict):
96
+ values = dict(zip(keys[:len(lw(values))], lw(values)))
97
+ return values
98
+
99
+
100
+ def call(fn, x=None):
101
+ if len(get_args(fn)) > 0:
102
+ if isinstance(x, dict):
103
+ return fn(**x)
104
+ elif il(x):
105
+ return fn(*x)
106
+ else:
107
+ return fn(x)
108
+ else:
109
+ return fn()
110
+
111
+
112
+ def get_str_comp(str_comp):
113
+ if callable(str_comp):
114
+ return str_comp
115
+ elif isinstance(str_comp, str):
116
+ if str_comp == "in":
117
+ return lambda x, y: x in y
118
+ elif str_comp in ["equal", "="]:
119
+ return lambda x, y: x == y
120
+ elif str_comp == "re":
121
+ return lambda x, y: re.match(x, y)
122
+ return lambda x, y: x == y
123
+
124
+
125
+ def test(filters, x=None, str_comp="in"):
126
+ str_comp = get_str_comp(str_comp)
127
+ result = []
128
+ for f in lw(filters):
129
+ if isinstance(f, str):
130
+ result.append(str_comp(f, x))
131
+ elif callable(f):
132
+ result.append(call(f, x))
133
+ else:
134
+ result.append(f == x)
135
+ return result
136
+
137
+
138
+ test_all = comp([test, all])
139
+ test_any = comp([test, any])
140
+
141
+
142
+ def filter_keys(d, keys, reverse=False, str_comp="=", *args, **kwargs):
143
+ fn = test_any
144
+ if dataclasses.is_dataclass(keys):
145
+ keys = dataclasses.asdict(keys)
146
+ if isinstance(keys, dict):
147
+ keys = list(keys.keys())
148
+ if dataclasses.is_dataclass(d):
149
+ d = dataclasses.asdict(d)
150
+ if reverse:
151
+ fn = comp(test_any, lambda x: not x)
152
+ return {k: v for k, v in d.items() if fn(keys, k, str_comp=str_comp, *args, **kwargs)}
153
+ def none(x):
154
+ return [] if x is None else x
155
+
156
+ def if_images(data):
157
+ if not hasattr(data, "shape"):
158
+ return False
159
+ shape = data.shape
160
+ return len(shape) > 3 or (len(shape) == 3 and shape[-1] > 4)
161
+
162
+
163
+ def download_file(url, path=None):
164
+ if path is None:
165
+ path = url.split("/")[-1]
166
+
167
+ r = requests.get(url, stream=True)
168
+
169
+ if r.status_code == 200:
170
+ r.raw.decode_content = True
171
+
172
+ with open(path, 'wb') as f:
173
+ shutil.copyfileobj(r.raw, f)
174
+
175
+ logger.info(f'File {url} sucessfully downloaded to {path} ')
176
+ else:
177
+ logger.info(f'File {url} couldn\'t be retreived')
178
+
179
+ @dataclasses.dataclass
180
+ class ImageType:
181
+ mode: str = "RGB"
182
+ range_: Tuple = (0, 255)
183
+ channel: bool = True
184
+ reverse: bool = False
185
+ shape: bool = (None, 224, 224, 3)
186
+ dtype: str = "uint8"
187
+ counter: Counter = None
188
+
189
+ def __eq__(self, other):
190
+ return filter_keys(dataclasses.asdict(self), "counter", reverse=True) == filter_keys(dataclasses.asdict(other), "counter", reverse=True)
191
+
192
+
193
+ def image_type(data, histogram=True):
194
+ data = np.asarray(data)
195
+ if not if_images(data):
196
+ return False
197
+ shape = data.shape
198
+ channel = True
199
+ range_ = data.min(), data.max()
200
+ counter = None
201
+ reverse = None
202
+ if shape[-1] == 3:
203
+ mode = "RGB"
204
+ if histogram:
205
+ counter = Counter(list(get_last_dim(data, 3).reshape(-1)))
206
+ reverse = counter.most_common(1)[0][0] == range_[1]
207
+ else:
208
+ mode = "L"
209
+ if shape[-1] != 1:
210
+ channel = False
211
+ if histogram:
212
+ counter = Counter(list(get_last_dim(data).reshape(-1)))
213
+ reverse = counter.most_common(1)[0][0] == range_[1]
214
+ else:
215
+ if histogram:
216
+ counter = Counter(list(get_last_dim(data, 3).reshape(-1)))
217
+ reverse = counter.most_common(1)[0][0] == range_[1]
218
+ return ImageType(mode, range_, channel, reverse, shape, data.dtype, counter)
219
+
220
+ timage = partial(image_type, histogram=False)
221
+
222
+ class OverrideDict(dict):
223
+ def to_dict(self):
224
+ # return {k: v for k, v in self.items()}
225
+ return dict(self)
226
+
227
+ def get_fn(self, index):
228
+ return self.__getitem__(index)
229
+
230
+
231
+ class CalcDict(OverrideDict):
232
+ def operate(self, other, op, right=False):
233
+ if not hasattr(other, "__iter__"):
234
+ other = [other] * len(self)
235
+ if isinstance(other, dict):
236
+ other = other.values()
237
+ it = iter(other)
238
+ if right:
239
+ fn = lambda x, y: op(y, x)
240
+ else:
241
+ fn = op
242
+ return CalcDict({k: fn(v, next(it)) for k, v in self.items()})
243
+
244
+ def __add__(self, other):
245
+ return self.operate(other, operator.add)
246
+
247
+ def __sub__(self, other):
248
+ return self.operate(other, operator.sub)
249
+
250
+ def __mul__(self, other):
251
+ return self.operate(other, operator.mul)
252
+
253
+ def __truediv__(self, other):
254
+ return self.operate(other, operator.truediv)
255
+
256
+ def __radd__(self, other):
257
+ return self.operate(other, operator.add, right=True)
258
+
259
+ def __rsub__(self, other):
260
+ return self.operate(other, operator.sub, right=True)
261
+
262
+ def __rmul__(self, other):
263
+ return self.operate(other, operator.mul, right=True)
264
+
265
+ def __rtruediv__(self, other):
266
+ return self.operate(other, operator.truediv, right=True)
267
+
268
+
269
+ def dict_from_list2(keys, values=None):
270
+ if values is None:
271
+ values = list(range(len(keys)))
272
+ return dict(zip(keys[:len(lw(values))], lw(values)))
273
+
274
+
raven_utils/uitls.py CHANGED
@@ -1,24 +1,34 @@
1
  from functools import partial
2
- from itertools import product
3
 
4
  import numpy as np
5
- from funcy import identity
6
 
7
- from data_utils import gather, DataGenerator, Data
8
- from data_utils.sampling import DataSampler
9
- from models_utils import init_image as def_init_image, INPUTS, TARGET
 
10
 
11
  import raven_utils.group as group
12
 
13
- from data_utils import ops as D
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  init_image = partial(def_init_image, shape=(16, 8, 80, 80, 1))
16
 
17
 
18
- def get_val_index(no=group.NO, base=3,add_end=False):
19
  indexes = np.arange(no) * 2000 + base
20
  if add_end:
21
- indexes = np.concatenate([indexes, no*2000])
22
  return indexes
23
 
24
 
@@ -32,29 +42,6 @@ def get_matrix_from_data(x):
32
  return get_matrix(inputs, index)
33
 
34
 
35
- def get_data_class(data, batch_size=128):
36
- fn = identity
37
- shape = data[0].shape
38
- train_generator = DataGenerator(
39
- {
40
- INPUTS: Data(data[0], fn),
41
- TARGET: Data(data[2], fn),
42
- },
43
- sampler=DataSampler(np.array(list(product(np.arange(shape[0]), np.arange(shape[1]))))),
44
- batch=batch_size
45
- )
46
- shape = data[1].shape
47
- val_generator = DataGenerator(
48
- {
49
- INPUTS: Data(data[1], fn),
50
- TARGET: Data(data[3], fn),
51
- },
52
- sampler=DataSampler(np.array(list(product(np.arange(shape[0]), np.arange(shape[1])))), shuffle=False),
53
- batch=batch_size
54
- )
55
- return train_generator, val_generator
56
-
57
-
58
  def compare_from_result(result, data):
59
  data = data.data.data
60
  answer = D.gather(data['target'].data, data['index'].data[:, 0])
 
1
  from functools import partial
 
2
 
3
  import numpy as np
 
4
 
5
+
6
+ def gather(a, index):
7
+ return a[np.arange(np.shape(a)[0]), index]
8
+
9
 
10
  import raven_utils.group as group
11
 
12
+
13
+ def def_init_image(shape=(10, 64, 64, 3), mode="uniform", min=0, max=1):
14
+ if mode == "normal" or mode == "n":
15
+ return np.random.normal(min, max, shape)
16
+ elif mode == "zero" or mode == 0:
17
+ return np.zeros(shape)
18
+ elif mode == "one" or mode == 1:
19
+ return np.ones(shape)
20
+ elif mode == "int" or isinstance(mode, int):
21
+ return np.random.randint(min, max, shape)
22
+ return np.random.uniform(min, max, shape)
23
+
24
 
25
  init_image = partial(def_init_image, shape=(16, 8, 80, 80, 1))
26
 
27
 
28
+ def get_val_index(no=group.NO, base=3, add_end=False):
29
  indexes = np.arange(no) * 2000 + base
30
  if add_end:
31
+ indexes = np.concatenate([indexes, no * 2000])
32
  return indexes
33
 
34
 
 
42
  return get_matrix(inputs, index)
43
 
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  def compare_from_result(result, data):
46
  data = data.data.data
47
  answer = D.gather(data['target'].data, data['index'].data[:, 0])
utils.py CHANGED
@@ -1,14 +1,25 @@
1
  import numpy as np
2
- from data_utils.image import draw_images
3
- from ml_utils import il
4
 
5
  import raven_utils as rv
 
 
 
 
 
6
  from raven_utils.uitls import get_matrix
7
  from tensorflow.keras.models import load_model
8
  from raven_utils.draw import render_from_model
9
  import models
10
  import ast
11
 
 
 
 
 
 
 
 
12
 
13
  def load_example(index=0):
14
  index = ast.literal_eval(str(index))
 
1
  import numpy as np
2
+ from funcy import identity
 
3
 
4
  import raven_utils as rv
5
+ from raven_utils.constant import PROPERTY
6
+ from raven_utils.decode import target_mask
7
+ from raven_utils.image import draw_images
8
+ from raven_utils.render.rendering import render_panels
9
+ from raven_utils.tools import filter_keys, is_model, il
10
  from raven_utils.uitls import get_matrix
11
  from tensorflow.keras.models import load_model
12
  from raven_utils.draw import render_from_model
13
  import models
14
  import ast
15
 
16
+ def render_from_model(data,predict,pre_fn=identity):
17
+ data = filter_keys(data, PROPERTY, reverse=True)
18
+ if is_model(predict) or str(type(predict)) == "<class 'tensorflow.python.saved_model.load.Loader._recreate_base_user_object.<locals>._UserObject'>":
19
+ predict = predict(data)
20
+ pro = np.array(target_mask(predict['predict_mask'].numpy()) * predict["predict"].numpy(), dtype=np.int8)
21
+ return pre_fn(render_panels(pro, target=False)[None])[0]
22
+
23
 
24
  def load_example(index=0):
25
  index = ast.literal_eval(str(index))