Skip to content

Commit 2d4762e

Browse files
committed
Rename '*_dic' to '*_dict'
1 parent 6ea08ec commit 2d4762e

File tree

14 files changed

+151
-160
lines changed

14 files changed

+151
-160
lines changed

Util/Bases.py

+31-31
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ class ModelBase:
4646
clf_timing = Timing()
4747

4848
def __init__(self, **kwargs):
49-
self._plot_label_dic = {}
49+
self._plot_label_dict = {}
5050
self._title = self._name = None
5151
self._metrics, self._available_metrics = [], {
5252
"acc": ClassifierBase.acc
@@ -135,9 +135,9 @@ def scatter2d(self, x, y, padding=0.5, title=None):
135135
y_max += y_padding
136136

137137
if labels.ndim == 1:
138-
if not self._plot_label_dic:
139-
self._plot_label_dic = {c: i for i, c in enumerate(set(labels))}
140-
dic = self._plot_label_dic
138+
if not self._plot_label_dict:
139+
self._plot_label_dict = {c: i for i, c in enumerate(set(labels))}
140+
dic = self._plot_label_dict
141141
n_label = len(dic)
142142
labels = np.array([dic[label] for label in labels])
143143
else:
@@ -181,9 +181,9 @@ def scatter3d(self, x, y, padding=0.1, title=None):
181181

182182
def transform_arr(arr):
183183
if arr.ndim == 1:
184-
_dic = {c: i for i, c in enumerate(set(arr))}
185-
n_dim = len(_dic)
186-
arr = np.array([_dic[label] for label in arr])
184+
dic = {c: i for i, c in enumerate(set(arr))}
185+
n_dim = len(dic)
186+
arr = np.array([dic[label] for label in arr])
187187
else:
188188
n_dim = arr.shape[1]
189189
arr = np.argmax(arr, axis=1)
@@ -197,15 +197,15 @@ def transform_arr(arr):
197197

198198
labels, n_label = transform_arr(labels)
199199
colors = plt.cm.rainbow([i / n_label for i in range(n_label)])[labels]
200-
_indices = [labels == i for i in range(n_label)]
201-
_scatters = []
200+
indices = [labels == i for i in range(n_label)]
201+
scatters = []
202202
fig = plt.figure()
203203
plt.title(title)
204204
ax = fig.add_subplot(111, projection='3d')
205-
for _index in _indices:
206-
_scatters.append(ax.scatter(axis[0][_index], axis[1][_index], axis[2][_index], c=colors[_index]))
207-
ax.legend(_scatters, ["$c_{}$".format("{" + str(i) + "}") for i in range(len(_scatters))],
208-
ncol=math.ceil(math.sqrt(len(_scatters))), fontsize=8)
205+
for _index in indices:
206+
scatters.append(ax.scatter(axis[0][_index], axis[1][_index], axis[2][_index], c=colors[_index]))
207+
ax.legend(scatters, ["$c_{}$".format("{" + str(i) + "}") for i in range(len(scatters))],
208+
ncol=math.ceil(math.sqrt(len(scatters))), fontsize=8)
209209
plt.show()
210210

211211
# Util
@@ -344,9 +344,9 @@ def get_base(_nx, _ny):
344344
z = self.predict(base_matrix).reshape((nx, ny))
345345

346346
if labels.ndim == 1:
347-
if not self._plot_label_dic:
348-
self._plot_label_dic = {c: i for i, c in enumerate(set(labels))}
349-
dic = self._plot_label_dic
347+
if not self._plot_label_dict:
348+
self._plot_label_dict = {c: i for i, c in enumerate(set(labels))}
349+
dic = self._plot_label_dict
350350
n_label = len(dic)
351351
labels = np.array([dic[label] for label in labels])
352352
else:
@@ -366,9 +366,9 @@ def get_base(_nx, _ny):
366366
plt.contour(xf, yf, z, c='k-', levels=[0])
367367
plt.scatter(axis[0], axis[1], c=colors)
368368
if emphasize is not None:
369-
_indices = np.array([False] * len(axis[0]))
370-
_indices[np.asarray(emphasize)] = True
371-
plt.scatter(axis[0][_indices], axis[1][_indices], s=80,
369+
indices = np.array([False] * len(axis[0]))
370+
indices[np.asarray(emphasize)] = True
371+
plt.scatter(axis[0][indices], axis[1][indices], s=80,
372372
facecolors="None", zorder=10)
373373
if extra is not None:
374374
plt.scatter(*np.asarray(extra).T, s=80, zorder=25, facecolors="red")
@@ -411,9 +411,9 @@ def get_base(_nx, _ny):
411411
print("Drawing figures...")
412412
xy_xf, xy_yf = np.meshgrid(xf, yf, sparse=True)
413413
if labels.ndim == 1:
414-
if not self._plot_label_dic:
415-
self._plot_label_dic = {c: i for i, c in enumerate(set(labels))}
416-
dic = self._plot_label_dic
414+
if not self._plot_label_dict:
415+
self._plot_label_dict = {c: i for i, c in enumerate(set(labels))}
416+
dic = self._plot_label_dict
417417
n_label = len(dic)
418418
labels = np.array([dic[label] for label in labels])
419419
else:
@@ -439,9 +439,9 @@ def get_base(_nx, _ny):
439439
plt.contour(xf, yf, z, c='k-', levels=[0])
440440
plt.scatter(axis[0], axis[1], c=colors)
441441
if emphasize is not None:
442-
_indices = np.array([False] * len(axis[0]))
443-
_indices[np.asarray(emphasize)] = True
444-
plt.scatter(axis[0][_indices], axis[1][_indices], s=80,
442+
indices = np.array([False] * len(axis[0]))
443+
indices[np.asarray(emphasize)] = True
444+
plt.scatter(axis[0][indices], axis[1][indices], s=80,
445445
facecolors="None", zorder=10)
446446
if extra is not None:
447447
plt.scatter(*np.asarray(extra).T, s=80, zorder=25, facecolors="red")
@@ -503,9 +503,9 @@ def get_base(_nx, _ny, _nz):
503503

504504
def transform_arr(arr):
505505
if arr.ndim == 1:
506-
_dic = {c: i for i, c in enumerate(set(arr))}
507-
n_dim = len(_dic)
508-
arr = np.array([_dic[label] for label in arr])
506+
dic = {c: i for i, c in enumerate(set(arr))}
507+
n_dim = len(dic)
508+
arr = np.array([dic[label] for label in arr])
509509
else:
510510
n_dim = arr.shape[1]
511511
arr = np.argmax(arr, axis=1)
@@ -566,9 +566,9 @@ def _draw(_ax, _x, _xf, _y, _yf, _z):
566566
def _emphasize(_ax, axis0, axis1, _c):
567567
_ax.scatter(axis0, axis1, c=_c)
568568
if emphasize is not None:
569-
_indices = np.array([False] * len(axis[0]))
570-
_indices[np.asarray(emphasize)] = True
571-
_ax.scatter(axis0[_indices], axis1[_indices], s=80,
569+
indices = np.array([False] * len(axis[0]))
570+
indices[np.asarray(emphasize)] = True
571+
_ax.scatter(axis0[indices], axis1[indices], s=80,
572572
facecolors="None", zorder=10)
573573

574574
def _extra(_ax, axis0, axis1, _c, _ex0, _ex1):

Util/Util.py

+18-27
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,6 @@
2020

2121

2222
class Util:
23-
@staticmethod
24-
def get_and_pop(dic, key, default):
25-
try:
26-
val = dic[key]
27-
dic.pop(key)
28-
except KeyError:
29-
val = default
30-
return val
31-
3223
@staticmethod
3324
def callable(obj):
3425
_str_obj = str(obj)
@@ -123,14 +114,14 @@ def get_dataset(name, path, train_num=None, tar_idx=None, shuffle=True,
123114
if train_num is None:
124115
return x, y
125116
return (x[:train_num], y[:train_num]), (x[train_num:], y[train_num:])
126-
x, y, wc, features, feat_dics, label_dic = DataUtil.quantize_data(x, y, **kwargs)
117+
x, y, wc, features, feat_dicts, label_dict = DataUtil.quantize_data(x, y, **kwargs)
127118
if one_hot:
128119
y = (y[..., None] == np.arange(np.max(y)+1)).astype(np.int8)
129120
if train_num is None:
130-
return x, y, wc, features, feat_dics, label_dic
121+
return x, y, wc, features, feat_dicts, label_dict
131122
return (
132123
(x[:train_num], y[:train_num]), (x[train_num:], y[train_num:]),
133-
wc, features, feat_dics, label_dic
124+
wc, features, feat_dicts, label_dict
134125
)
135126

136127
@staticmethod
@@ -205,34 +196,34 @@ def quantize_data(x, y, wc=None, continuous_rate=0.1, separate=False):
205196
wc = np.array([False] * len(xt))
206197
else:
207198
wc = np.asarray(wc)
208-
feat_dics = [{_l: i for i, _l in enumerate(feats)} if not wc[i] else None
199+
feat_dicts = [{_l: i for i, _l in enumerate(feats)} if not wc[i] else None
209200
for i, feats in enumerate(features)]
210201
if not separate:
211202
if np.all(~wc):
212203
dtype = np.int
213204
else:
214205
dtype = np.float32
215-
x = np.array([[feat_dics[i][_l] if not wc[i] else _l for i, _l in enumerate(sample)]
206+
x = np.array([[feat_dicts[i][_l] if not wc[i] else _l for i, _l in enumerate(sample)]
216207
for sample in x], dtype=dtype)
217208
else:
218-
x = np.array([[feat_dics[i][_l] if not wc[i] else _l for i, _l in enumerate(sample)]
209+
x = np.array([[feat_dicts[i][_l] if not wc[i] else _l for i, _l in enumerate(sample)]
219210
for sample in x], dtype=np.float32)
220211
x = (x[:, ~wc].astype(np.int), x[:, wc])
221-
label_dic = {l: i for i, l in enumerate(set(y))}
222-
y = np.array([label_dic[yy] for yy in y], dtype=np.int8)
223-
label_dic = {i: l for l, i in label_dic.items()}
224-
return x, y, wc, features, feat_dics, label_dic
212+
label_dict = {l: i for i, l in enumerate(set(y))}
213+
y = np.array([label_dict[yy] for yy in y], dtype=np.int8)
214+
label_dict = {i: l for l, i in label_dict.items()}
215+
return x, y, wc, features, feat_dicts, label_dict
225216

226217
@staticmethod
227-
def transform_data(x, y, wc, feat_dics, label_dic):
218+
def transform_data(x, y, wc, feat_dicts, label_dict):
228219
if np.all(~wc):
229220
dtype = np.int
230221
else:
231222
dtype = np.float32
232-
label_dic = {l: i for i, l in label_dic.items()}
233-
x = np.array([[feat_dics[i][_l] if not wc[i] else _l for i, _l in enumerate(sample)]
223+
label_dict = {l: i for i, l in label_dict.items()}
224+
x = np.array([[feat_dicts[i][_l] if not wc[i] else _l for i, _l in enumerate(sample)]
234225
for sample in x], dtype=dtype)
235-
y = np.array([label_dic[yy] for yy in y], dtype=np.int8)
226+
y = np.array([label_dict[yy] for yy in y], dtype=np.int8)
236227
return x, y
237228

238229

@@ -338,9 +329,9 @@ def make_mp4(ims, name="", fps=20, scale=1, extend=30):
338329

339330

340331
class Overview:
341-
def __init__(self, label_dic, shape=(1440, 576)):
332+
def __init__(self, label_dict, shape=(1440, 576)):
342333
self.shape = shape
343-
self.label_dic = label_dic
334+
self.label_dict = label_dict
344335
self.n_col = self.n_row = 0
345336
self.ans = self.pred = self.results = self.prob = None
346337

@@ -354,7 +345,7 @@ def _get_detail(self, event, x, y, *_):
354345
title = "Detail (prob: {:6.4})".format(prob)
355346
else:
356347
title = "True label: {} (prob: {:6.4})".format(
357-
self.label_dic[self.ans[idx]], prob)
348+
self.label_dict[self.ans[idx]], prob)
358349
while 1:
359350
cv2.imshow(title, self.results[idx])
360351
if cv2.waitKey(20) & 0xFF == 27:
@@ -377,7 +368,7 @@ def _get_results(self, ans, y_pred, images):
377368
for i, img in enumerate(images):
378369
pred = y_pred[i]
379370
indices = np.argsort(pred)[-3:][::-1]
380-
ps, labels = pred[indices], self.label_dic[indices]
371+
ps, labels = pred[indices], self.label_dict[indices]
381372
if true_classes is None:
382373
color = np.array([255, 255, 255], dtype=np.uint8)
383374
else:

Zhihu/CvDTree/three/CvDTree.py

+24-24
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def __init__(self, tree=None, base=2, ent=None,
9090
self._prev_feat = prev_feat
9191
self.leafs = {}
9292
self.pruned = False
93-
self.label_dic = {}
93+
self.label_dict = {}
9494

9595
def __getitem__(self, item):
9696
if isinstance(item, str):
@@ -105,7 +105,7 @@ def __str__(self):
105105
return "CvDNode ({}) ({} -> {})".format(
106106
self._depth, self._prev_feat, self.feature_dim)
107107
return "CvDNode ({}) ({} -> class: {})".format(
108-
self._depth, self._prev_feat, self.label_dic[self.category])
108+
self._depth, self._prev_feat, self.label_dict[self.category])
109109

110110
__repr__ = __str__
111111

@@ -128,7 +128,7 @@ def prev_feat(self):
128128
return self._prev_feat
129129

130130
@property
131-
def info_dic(self):
131+
def info_dict(self):
132132
return {
133133
"ent": self.ent,
134134
"labels": self.labels
@@ -163,25 +163,25 @@ def get_class(self):
163163

164164
def _gen_children(self, feat, con_chaos):
165165
features = self._data[:, feat]
166-
_new_feats = self.feats[:]
167-
_new_feats.remove(feat)
166+
new_feats = self.feats[:]
167+
new_feats.remove(feat)
168168
for feat in set(features):
169-
_feat_mask = features == feat
170-
_new_node = self.__class__(
169+
feat_mask = features == feat
170+
new_node = self.__class__(
171171
self.tree, self._base, ent=con_chaos,
172172
depth=self._depth + 1, parent=self, is_root=False, prev_feat=feat)
173-
_new_node.feats = _new_feats
174-
_new_node.label_dic = self.label_dic
175-
self.children[feat] = _new_node
176-
_local_weights = None if self.sample_weights is None else self.sample_weights[_feat_mask]
177-
_new_node.fit(self._data[_feat_mask, :], self.labels[_feat_mask], _local_weights)
173+
new_node.feats = new_feats
174+
new_node.label_dict = self.label_dict
175+
self.children[feat] = new_node
176+
_local_weights = None if self.sample_weights is None else self.sample_weights[feat_mask]
177+
new_node.fit(self._data[feat_mask, :], self.labels[feat_mask], _local_weights)
178178

179179
def _handle_terminate(self):
180180
self.category = self.get_class()
181-
_parent = self
182-
while _parent is not None:
183-
_parent.leafs[self.key] = self.info_dic
184-
_parent = _parent.parent
181+
parent = self
182+
while parent is not None:
183+
parent.leafs[self.key] = self.info_dict
184+
parent = parent.parent
185185

186186
def fit(self, data, labels, sample_weights, eps=1e-8):
187187
if data is not None and labels is not None:
@@ -212,7 +212,7 @@ def prune(self):
212212
while _parent is not None:
213213
for _k in _pop_lst:
214214
_parent.leafs.pop(_k)
215-
_parent.leafs[self.key] = self.info_dic
215+
_parent.leafs[self.key] = self.info_dict
216216
_parent = _parent.parent
217217
self.mark_pruned()
218218
self.children = {}
@@ -265,7 +265,7 @@ def __init__(self, max_depth=None, node=None):
265265
self._max_depth = max_depth
266266
self.root = node
267267
self.root.feed_tree(self)
268-
self.label_dic = {}
268+
self.label_dict = {}
269269
self.prune_alpha = 1
270270

271271
def __str__(self):
@@ -282,11 +282,11 @@ def acc(y, y_pred):
282282
return np.sum(np.array(y) == np.array(y_pred)) / len(y)
283283

284284
def fit(self, data=None, labels=None, sample_weights=None, eps=1e-8, **kwargs):
285-
_dic = {c: i for i, c in enumerate(set(labels))}
286-
labels = np.array([_dic[yy] for yy in labels])
287-
self.label_dic = {value: key for key, value in _dic.items()}
285+
dic = {c: i for i, c in enumerate(set(labels))}
286+
labels = np.array([dic[yy] for yy in labels])
287+
self.label_dict = {value: key for key, value in dic.items()}
288288
data = np.array(data)
289-
self.root.label_dic = self.label_dic
289+
self.root.label_dict = self.label_dict
290290
self.root.feats = [i for i in range(data.shape[1])]
291291
self.root.fit(data, labels, sample_weights, eps)
292292
self.prune_alpha = kwargs.get("alpha", self.prune_alpha)
@@ -318,7 +318,7 @@ def prune(self):
318318

319319
def predict_one(self, x, transform=True):
320320
if transform:
321-
return self.label_dic[self.root.predict_one(x)]
321+
return self.label_dict[self.root.predict_one(x)]
322322
return self.root.predict_one(x)
323323

324324
def predict(self, x, transform=True):
@@ -357,7 +357,7 @@ def draw(self, radius=24, width=1200, height=800, padding=0.2, plot_num=30, titl
357357
text = str(node.feature_dim)
358358
color = (0, 0, 255)
359359
else:
360-
text = str(self.label_dic[node.category])
360+
text = str(self.label_dict[node.category])
361361
color = (0, 255, 0)
362362
cv2.putText(img, text, (x-7*len(text)+2, y+3), cv2.LINE_AA, 0.6, color, 1)
363363

0 commit comments

Comments
 (0)