project_name
stringlengths
6
104
file_name
stringlengths
4
89
full_name
stringlengths
1
102
func_name
stringlengths
1
85
docstring
stringlengths
13
836
docstring_tokens
listlengths
4
122
code
stringlengths
23
39.7k
code_tokens
stringlengths
29
44.6k
url
int64
3
986k
p-lambda/wilds
amazon_dataset.py
AmazonDataset.eval
eval
Computes all evaluation metrics.
[ "Computes", "all", "evaluation", "metrics." ]
def eval(self, y_pred: torch.Tensor, y_true: torch.LongTensor, metadata: torch.Tensor, prediction_fn=None) -> Tuple[Dict[str, Any], str]: metric: Accuracy = Accuracy(prediction_fn=prediction_fn) if self.split_scheme == 'user': g: torch.Tensor = self._eval_grouper.metadata_to_group(metadata) resu...
['def', 'eval(self,', 'y_pred:', 'torch.Tensor,', 'y_true:', 'torch.LongTensor,', 'metadata:', 'torch.Tensor,', 'prediction_fn=None)', '->', 'Tuple[Dict[str,', 'Any],', 'str]:', 'metric:', 'Accuracy', '=', 'Accuracy(prediction_fn=prediction_fn)', 'if', 'self.split_scheme', '==', "'user':", 'g:', 'torch.Tensor', '=', 's...
959,701
p-lambda/wilds
globalwheat_dataset.py
GlobalWheatDataset.eval
eval
The main evaluation metric, detection_acc_avg_dom, measures the simple average of the detection accuracies of each domain.
[ "The", "main", "evaluation", "metric,", "detection_acc_avg_dom,", "measures", "the", "simple", "average", "of", "the", "detection", "accuracies", "of", "each", "domain." ]
def eval(self, y_pred, y_true, metadata): (results, results_str) = self.standard_group_eval(self._metric, self._eval_grouper, y_pred, y_true, metadata) detection_accs = [] for (k, v) in results.items(): if k.startswith('detection_acc_session:'): d = k.split(':')[1] count = re...
['def', 'eval(self,', 'y_pred,', 'y_true,', 'metadata):', '(results,', 'results_str)', '=', 'self.standard_group_eval(self._metric,', 'self._eval_grouper,', 'y_pred,', 'y_true,', 'metadata)', 'detection_accs', '=', '[]', 'for', '(k,', 'v)', 'in', 'results.items():', 'if', "k.startswith('detection_acc_session:'):", 'd',...
959,716
p-lambda/wilds
sqf_dataset.py
SQFDataset.get_split_maps
get_split_maps
Using the existing split indices, create a map to put entries to training and validation sets.
[ "Using", "the", "existing", "split", "indices,", "create", "a", "map", "to", "put", "entries", "to", "training", "and", "validation", "sets." ]
def get_split_maps(self, data_df, train_idxs, test_idxs, val_idxs): split_array = np.zeros(data_df.shape[0]) split_array[train_idxs] = 0 split_array[test_idxs] = 1 split_array[val_idxs] = 2 return split_array
['def', 'get_split_maps(self,', 'data_df,', 'train_idxs,', 'test_idxs,', 'val_idxs):', 'split_array', '=', 'np.zeros(data_df.shape[0])', 'split_array[train_idxs]', '=', '0', 'split_array[test_idxs]', '=', '1', 'split_array[val_idxs]', '=', '2', 'return', 'split_array']
959,724
p-lambda/wilds
sqf_dataset.py
SQFDataset.get_split_features
get_split_features
Get features that include precinct if we're splitting on race or don't include if we're using borough splits.
[ "Get", "features", "that", "include", "precinct", "if", "we're", "splitting", "on", "race", "or", "don't", "include", "if", "we're", "using", "borough", "splits." ]
def get_split_features(self, columns): feats_to_use = [] if 'bronx' not in self._split_scheme and 'borough' not in self._split_scheme: feats_to_use.append('precinct') feats_to_use += ['suspect.height', 'suspect.weight', 'suspect.age', 'observation.period', 'inside.outside', 'location.housing', 'radi...
['def', 'get_split_features(self,', 'columns):', 'feats_to_use', '=', '[]', 'if', "'bronx'", 'not', 'in', 'self._split_scheme', 'and', "'borough'", 'not', 'in', 'self._split_scheme:', "feats_to_use.append('precinct')", 'feats_to_use', '+=', "['suspect.height',", "'suspect.weight',", "'suspect.age',", "'observation.peri...
959,725
p-lambda/wilds
wilds_dataset.py
WILDSDataset.data_dir
data_dir
The full path to the folder in which the dataset is stored.
[ "The", "full", "path", "to", "the", "folder", "in", "which", "the", "dataset", "is", "stored." ]
def data_dir(self): return self._data_dir
['def', 'data_dir(self):', 'return', 'self._data_dir']
959,735
p-lambda/wilds
wilds_dataset.py
WILDSDataset.split_array
split_array
An array of integers, with split_array[i] representing what split the i-th data point belongs to.
[ "An", "array", "of", "integers,", "with", "split_array[i]", "representing", "what", "split", "the", "i-th", "data", "point", "belongs", "to." ]
def split_array(self): return self._split_array
['def', 'split_array(self):', 'return', 'self._split_array']
959,741
p-lambda/wilds
wilds_dataset.py
WILDSDataset.original_resolution
original_resolution
Original image resolution for image datasets.
[ "Original", "image", "resolution", "for", "image", "datasets." ]
def original_resolution(self): return getattr(self, '_original_resolution', None)
['def', 'original_resolution(self):', 'return', 'getattr(self,', "'_original_resolution',", 'None)']
959,750
p-lambda/wilds
wilds_unlabeled_dataset.py
WILDSUnlabeledDataset.split_names
split_names
A dictionary mapping splits to their pretty names, Keys should match up with split_dict.
[ "A", "dictionary", "mapping", "splits", "to", "their", "pretty", "names,", "Keys", "should", "match", "up", "with", "split_dict." ]
def split_names(self): return getattr(self, '_split_names', WILDSUnlabeledDataset.DEFAULT_SPLIT_NAMES)
['def', 'split_names(self):', 'return', 'getattr(self,', "'_split_names',", 'WILDSUnlabeledDataset.DEFAULT_SPLIT_NAMES)']
959,764
imoscovitz/wittgenstein
base.py
pos_neg_split
pos_neg_split
Split df into pos and neg classes.
[ "Split", "df", "into", "pos", "and", "neg", "classes." ]
def pos_neg_split(df, class_feat, pos_class): pos_df = pos(df, class_feat, pos_class) neg_df = neg(df, class_feat, pos_class) return (pos_df, neg_df)
['def', 'pos_neg_split(df,', 'class_feat,', 'pos_class):', 'pos_df', '=', 'pos(df,', 'class_feat,', 'pos_class)', 'neg_df', '=', 'neg(df,', 'class_feat,', 'pos_class)', 'return', '(pos_df,', 'neg_df)']
959,807
imoscovitz/wittgenstein
base.py
pos
pos
Returns subset of instances that are labeled positive.
[ "Returns", "subset", "of", "instances", "that", "are", "labeled", "positive." ]
def pos(df, class_feat, pos_class): return df[df[class_feat] == pos_class]
['def', 'pos(df,', 'class_feat,', 'pos_class):', 'return', 'df[df[class_feat]', '==', 'pos_class]']
959,809
imoscovitz/wittgenstein
base.py
num_neg
num_neg
Returns number of instances that are NOT labeled positive.
[ "Returns", "number", "of", "instances", "that", "are", "NOT", "labeled", "positive." ]
def num_neg(df, class_feat, pos_class): return len(df[df[class_feat] != pos_class])
['def', 'num_neg(df,', 'class_feat,', 'pos_class):', 'return', 'len(df[df[class_feat]', '!=', 'pos_class])']
959,812
imoscovitz/wittgenstein
base.py
argmin
argmin
Returns index of minimum value.
[ "Returns", "index", "of", "minimum", "value." ]
def argmin(list_): lowest_val = list_[0] lowest_i = 0 for (i, val) in enumerate(list_): if val < lowest_val: lowest_val = val lowest_i = i return lowest_i
['def', 'argmin(list_):', 'lowest_val', '=', 'list_[0]', 'lowest_i', '=', '0', 'for', '(i,', 'val)', 'in', 'enumerate(list_):', 'if', 'val', '<', 'lowest_val:', 'lowest_val', '=', 'val', 'lowest_i', '=', 'i', 'return', 'lowest_i']
959,815
imoscovitz/wittgenstein
base.py
Rule.covers
covers
Returns instances covered by the Rule.
[ "Returns", "instances", "covered", "by", "the", "Rule." ]
def covers(self, df): covered = df.copy() for cond in self.conds: covered = cond.covers(covered) return covered
['def', 'covers(self,', 'df):', 'covered', '=', 'df.copy()', 'for', 'cond', 'in', 'self.conds:', 'covered', '=', 'cond.covers(covered)', 'return', 'covered']
959,826
imoscovitz/wittgenstein
irep.py
IREP.fit
fit
Fit a Ruleset model using a training DataFrame.
[ "Fit", "a", "Ruleset", "model", "using", "a", "training", "DataFrame." ]
def fit(self, df, y=None, class_feat=None, pos_class=None, n_discretize_bins=None, random_state=None): (df, self.class_feat, self.pos_class) = base.trainset_classfeat_posclass(df, y=y, class_feat=class_feat, pos_class=pos_class) numeric_feats = base.find_numeric_feats(df, min_unique=n_discretize_bins, ignore_fe...
['def', 'fit(self,', 'df,', 'y=None,', 'class_feat=None,', 'pos_class=None,', 'n_discretize_bins=None,', 'random_state=None):', '(df,', 'self.class_feat,', 'self.pos_class)', '=', 'base.trainset_classfeat_posclass(df,', 'y=y,', 'class_feat=class_feat,', 'pos_class=pos_class)', 'numeric_feats', '=', 'base.find_numeric_f...
959,833
imoscovitz/wittgenstein
abstract_ruleset_classifier.py
AbstractRulesetClassifier.out_model
out_model
Print trained Ruleset model line-by-line: V represents 'or'; ^ represents 'and'.
[ "Print", "trained", "Ruleset", "model", "line-by-line:", "V", "represents", "'or';", "^", "represents", "'and'." ]
def out_model(self): if hasattr(self, 'ruleset_'): self.ruleset_.out_pretty() else: print('no model fitted')
['def', 'out_model(self):', 'if', 'hasattr(self,', "'ruleset_'):", 'self.ruleset_.out_pretty()', 'else:', "print('no", 'model', "fitted')"]
959,839
imoscovitz/wittgenstein
base.py
Ruleset.count_rules
count_rules
Return number of rules in the Ruleset.
[ "Return", "number", "of", "rules", "in", "the", "Ruleset." ]
def count_rules(self): return len(self.rules)
['def', 'count_rules(self):', 'return', 'len(self.rules)']
959,851
imoscovitz/wittgenstein
base.py
Ruleset.count_conds
count_conds
Return total number of conds in the Ruleset.
[ "Return", "total", "number", "of", "conds", "in", "the", "Ruleset." ]
def count_conds(self): return sum([len(r.conds) for r in self.rules])
['def', 'count_conds(self):', 'return', 'sum([len(r.conds)', 'for', 'r', 'in', 'self.rules])']
959,852
imoscovitz/wittgenstein
base.py
Rule.covers
covers
Return instances covered by the Rule.
[ "Return", "instances", "covered", "by", "the", "Rule." ]
def covers(self, df): covered = df.head(len(df)) for cond in self.conds: covered = cond.covers(covered) return covered
['def', 'covers(self,', 'df):', 'covered', '=', 'df.head(len(df))', 'for', 'cond', 'in', 'self.conds:', 'covered', '=', 'cond.covers(covered)', 'return', 'covered']
959,857
imoscovitz/wittgenstein
base_functions.py
gain
gain
Calculates the information gain from before to after.
[ "Calculates", "the", "information", "gain", "from", "before", "to", "after." ]
def gain(before, after, pos_df, neg_df): p0count = before.num_covered(pos_df) p1count = after.num_covered(pos_df) n0count = before.num_covered(neg_df) n1count = after.num_covered(neg_df) return p1count * (math.log2((p1count + 1) / (p1count + n1count + 1)) - math.log2((p0count + 1) / (p0count + n0cou...
['def', 'gain(before,', 'after,', 'pos_df,', 'neg_df):', 'p0count', '=', 'before.num_covered(pos_df)', 'p1count', '=', 'after.num_covered(pos_df)', 'n0count', '=', 'before.num_covered(neg_df)', 'n1count', '=', 'after.num_covered(neg_df)', 'return', 'p1count', '*', '(math.log2((p1count', '+', '1)', '/', '(p1count', '+',...
959,865
imoscovitz/wittgenstein
base_functions.py
best_successor
best_successor
Return for a Rule its best successor Rule according to FOIL information gain metric.
[ "Return", "for", "a", "Rule", "its", "best", "successor", "Rule", "according", "to", "FOIL", "information", "gain", "metric." ]
def best_successor(rule, possible_conds, pos_df, neg_df, verbosity=0): best_gain = 0 best_successor_rule = None for successor in rule.successors(possible_conds, pos_df, neg_df): g = gain(rule, successor, pos_df, neg_df) if g > best_gain: best_gain = g best_successor_r...
['def', 'best_successor(rule,', 'possible_conds,', 'pos_df,', 'neg_df,', 'verbosity=0):', 'best_gain', '=', '0', 'best_successor_rule', '=', 'None', 'for', 'successor', 'in', 'rule.successors(possible_conds,', 'pos_df,', 'neg_df):', 'g', '=', 'gain(rule,', 'successor,', 'pos_df,', 'neg_df)', 'if', 'g', '>', 'best_gain:...
959,870
imoscovitz/wittgenstein
base_functions.py
neg
neg
Return subset of instances that are labeled negative.
[ "Return", "subset", "of", "instances", "that", "are", "labeled", "negative." ]
def neg(df, class_feat, pos_class): return df[df[class_feat] != pos_class]
['def', 'neg(df,', 'class_feat,', 'pos_class):', 'return', 'df[df[class_feat]', '!=', 'pos_class]']
959,877
imoscovitz/wittgenstein
base_functions.py
num_neg
num_neg
Return number of instances that are labeled negative.
[ "Return", "number", "of", "instances", "that", "are", "labeled", "negative." ]
def num_neg(df, class_feat, pos_class): return len(df[df[class_feat] != pos_class])
['def', 'num_neg(df,', 'class_feat,', 'pos_class):', 'return', 'len(df[df[class_feat]', '!=', 'pos_class])']
959,879
imoscovitz/wittgenstein
base_functions.py
nCr
nCr
Return number of combinations C(n, r).
[ "Return", "number", "of", "combinations", "C(n,", "r)." ]
def nCr(n, r): def product(numbers): return reduce(op.mul, numbers, 1) num = product(range(n, n - r, -1)) den = product(range(1, r + 1)) return num // den
['def', 'nCr(n,', 'r):', 'def', 'product(numbers):', 'return', 'reduce(op.mul,', 'numbers,', '1)', 'num', '=', 'product(range(n,', 'n', '-', 'r,', '-1))', 'den', '=', 'product(range(1,', 'r', '+', '1))', 'return', 'num', '//', 'den']
959,880
imoscovitz/wittgenstein
base_functions.py
rm_rule_covers_cn
rm_rule_covers_cn
Return positive and negative indices not covered by object.
[ "Return", "positive", "and", "negative", "indices", "not", "covered", "by", "object." ]
def rm_rule_covers_cn(cn, rule, pos_idx, neg_idx): return (pos_idx - cn.rule_covers(rule, pos_idx), neg_idx - cn.rule_covers(rule, neg_idx))
['def', 'rm_rule_covers_cn(cn,', 'rule,', 'pos_idx,', 'neg_idx):', 'return', '(pos_idx', '-', 'cn.rule_covers(rule,', 'pos_idx),', 'neg_idx', '-', 'cn.rule_covers(rule,', 'neg_idx))']
959,884
imoscovitz/wittgenstein
base_functions.py
stop_early
stop_early
Function to decide whether to halt training.
[ "Function", "to", "decide", "whether", "to", "halt", "training." ]
def stop_early(ruleset, max_rules, max_total_conds): return max_rules is not None and len(ruleset.rules) >= max_rules or (max_total_conds is not None and ruleset.count_conds() >= max_total_conds)
['def', 'stop_early(ruleset,', 'max_rules,', 'max_total_conds):', 'return', 'max_rules', 'is', 'not', 'None', 'and', 'len(ruleset.rules)', '>=', 'max_rules', 'or', '(max_total_conds', 'is', 'not', 'None', 'and', 'ruleset.count_conds()', '>=', 'max_total_conds)']
959,886
imoscovitz/wittgenstein
catnap.py
CatNap.pos_idx_neg_idx
pos_idx_neg_idx
Pass in df, pos_class, and class_feat or pos_df and neg_df.
[ "Pass", "in", "df,", "pos_class,", "and", "class_feat", "or", "pos_df", "and", "neg_df." ]
def pos_idx_neg_idx(self, df=None, class_feat=None, pos_class=None, pos_df=None, neg_df=None): if pos_df is None and neg_df is None: pos_df = df[df[class_feat] == pos_class] neg_df = df[df[class_feat] != pos_class] pos_idx = set(pos_df.index.tolist()) neg_idx = set(neg_df.index.tolist()) ...
['def', 'pos_idx_neg_idx(self,', 'df=None,', 'class_feat=None,', 'pos_class=None,', 'pos_df=None,', 'neg_df=None):', 'if', 'pos_df', 'is', 'None', 'and', 'neg_df', 'is', 'None:', 'pos_df', '=', 'df[df[class_feat]', '==', 'pos_class]', 'neg_df', '=', 'df[df[class_feat]', '!=', 'pos_class]', 'pos_idx', '=', 'set(pos_df.i...
959,887
imoscovitz/wittgenstein
discretize.py
BinTransformer.transform
transform
Return df with seemingly continuous features binned, and the bin_transformer or None depending on whether binning occurs.
[ "Return", "df", "with", "seemingly", "continuous", "features", "binned,", "and", "the", "bin_transformer", "or", "None", "depending", "on", "whether", "binning", "occurs." ]
def transform(self, df, ignore_feats=[]): if n_discretize_bins is None: return df if self.bins_ == {}: return df isbinned = False continuous_feats = find_continuous_feats(df, ignore_feats=ignore_feats) if self.n_discretize_bins: if continuous_feats: if self.verbos...
['def', 'transform(self,', 'df,', 'ignore_feats=[]):', 'if', 'n_discretize_bins', 'is', 'None:', 'return', 'df', 'if', 'self.bins_', '==', '{}:', 'return', 'df', 'isbinned', '=', 'False', 'continuous_feats', '=', 'find_continuous_feats(df,', 'ignore_feats=ignore_feats)', 'if', 'self.n_discretize_bins:', 'if', 'continuo...
959,889
imoscovitz/wittgenstein
irep.py
IREP.out_model
out_model
Prints trained Ruleset model line-by-line: V represents 'or'; ^ represents 'and'.
[ "Prints", "trained", "Ruleset", "model", "line-by-line:", "V", "represents", "'or';", "^", "represents", "'and'." ]
def out_model(self): super().out_model()
['def', 'out_model(self):', 'super().out_model()']
959,894
imoscovitz/wittgenstein
abstract_ruleset_classifier.py
AbstractRulesetClassifier.copy
copy
Return deep copy of classifier.
[ "Return", "deep", "copy", "of", "classifier." ]
def copy(self): return deepcopy(self)
['def', 'copy(self):', 'return', 'deepcopy(self)']
959,901
imoscovitz/wittgenstein
base.py
Ruleset.get_selected_features
get_selected_features
Return list of selected features in order they were added.
[ "Return", "list", "of", "selected", "features", "in", "order", "they", "were", "added." ]
def get_selected_features(self): feature_list = [] feature_set = set() for rule in self.rules: for cond in rule.conds: feature = cond.feature if feature not in feature_set: feature_list.append(feature) feature_set.add(feature) return featur...
['def', 'get_selected_features(self):', 'feature_list', '=', '[]', 'feature_set', '=', 'set()', 'for', 'rule', 'in', 'self.rules:', 'for', 'cond', 'in', 'rule.conds:', 'feature', '=', 'cond.feature', 'if', 'feature', 'not', 'in', 'feature_set:', 'feature_list.append(feature)', 'feature_set.add(feature)', 'return', 'fea...
959,916
imoscovitz/wittgenstein
base_functions.py
gain_cn
gain_cn
Calculates the information gain from adding a Cond.
[ "Calculates", "the", "information", "gain", "from", "adding", "a", "Cond." ]
def gain_cn(cn, cond_step, rule_covers_pos_idx, rule_covers_neg_idx): p0count = len(rule_covers_pos_idx) p1count = len(cn.cond_covers(cond_step, subset=rule_covers_pos_idx)) n0count = len(rule_covers_neg_idx) n1count = len(cn.cond_covers(cond_step, subset=rule_covers_neg_idx)) return p1count * (math...
['def', 'gain_cn(cn,', 'cond_step,', 'rule_covers_pos_idx,', 'rule_covers_neg_idx):', 'p0count', '=', 'len(rule_covers_pos_idx)', 'p1count', '=', 'len(cn.cond_covers(cond_step,', 'subset=rule_covers_pos_idx))', 'n0count', '=', 'len(rule_covers_neg_idx)', 'n1count', '=', 'len(cn.cond_covers(cond_step,', 'subset=rule_cov...
959,927
imoscovitz/wittgenstein
base_functions.py
pos
pos
Return subset of instances that are labeled positive.
[ "Return", "subset", "of", "instances", "that", "are", "labeled", "positive." ]
def pos(df, class_feat, pos_class): return df[df[class_feat] == pos_class]
['def', 'pos(df,', 'class_feat,', 'pos_class):', 'return', 'df[df[class_feat]', '==', 'pos_class]']
959,937
imoscovitz/wittgenstein
discretize.py
BinTransformer.fit
fit
Returns a dict defining fits for numerical features A fit is an ordered list of tuples defining each bin's range (min is exclusive; max is inclusive) Returned dict allows for fitting to training data and applying the same fit to test data to avoid information leak.
[ "Returns", "a", "dict", "defining", "fits", "for", "numerical", "features", "A", "fit", "is", "an", "ordered", "list", "of", "tuples", "defining", "each", "bin's", "range", "(min", "is", "exclusive;", "max", "is", "inclusive)", "Returned", "dict", "allows", ...
def fit(self, df, output=False, ignore_feats=[]): def _fit_feat(df, feat): if len(df) == 0: return [] n_discretize_bins = min(self.n_discretize_bins, len(df[feat].unique())) bins = pd.qcut(df[feat], q=self.n_discretize_bins, precision=self.names_precision, duplicates='drop') ...
['def', 'fit(self,', 'df,', 'output=False,', 'ignore_feats=[]):', 'def', '_fit_feat(df,', 'feat):', 'if', 'len(df)', '==', '0:', 'return', '[]', 'n_discretize_bins', '=', 'min(self.n_discretize_bins,', 'len(df[feat].unique()))', 'bins', '=', 'pd.qcut(df[feat],', 'q=self.n_discretize_bins,', 'precision=self.names_precis...
959,950
imoscovitz/wittgenstein
discretize.py
BinTransformer.transform
transform
Transform DataFrame using fit bins.
[ "Transform", "DataFrame", "using", "fit", "bins." ]
def transform(self, df): def _transform_feat(df, feat): if self.bins_ is None: return df res = deepcopy(df[feat]) bins = self._strs_to_intervals(self.bins_[feat], feat) res = pd.cut(df[feat], bins=pd.IntervalIndex(bins)) res = res.map(lambda x: {i: s for (i, s) i...
['def', 'transform(self,', 'df):', 'def', '_transform_feat(df,', 'feat):', 'if', 'self.bins_', 'is', 'None:', 'return', 'df', 'res', '=', 'deepcopy(df[feat])', 'bins', '=', 'self._strs_to_intervals(self.bins_[feat],', 'feat)', 'res', '=', 'pd.cut(df[feat],', 'bins=pd.IntervalIndex(bins))', 'res', '=', 'res.map(lambda',...
959,951
vghost2008/wml1
wsummary.py
keypoints_image_summary
keypoints_image_summary
Draws bounding keypoints on batch of image tensors.
[ "Draws", "bounding", "keypoints", "on", "batch", "of", "image", "tensors." ]
def keypoints_image_summary(images, keypoints=None, lengths=None, max_instance_to_draw=20, keypoints_pair=None, name='keypoints_image_summary', max_outputs=3): assert len(keypoints.get_shape()) == 4, f'error keypoints dims {len(keypoints.get_shape())}' assert len(images.get_shape()) == 4, f'error images dims {l...
['def', 'keypoints_image_summary(images,', 'keypoints=None,', 'lengths=None,', 'max_instance_to_draw=20,', 'keypoints_pair=None,', "name='keypoints_image_summary',", 'max_outputs=3):', 'assert', 'len(keypoints.get_shape())', '==', '4,', "f'error", 'keypoints', 'dims', "{len(keypoints.get_shape())}'", 'assert', 'len(ima...
960,006
vghost2008/wml1
shufflenetv2.py
build_shufflenetv2_backbone
build_shufflenetv2_backbone
Create a ShuffleNetV2 instance from config.
[ "Create", "a", "ShuffleNetV2", "instance", "from", "config." ]
def build_shufflenetv2_backbone(cfg, *args, **kwargs): return ShuffleNetV2(cfg, *args, **kwargs)
['def', 'build_shufflenetv2_backbone(cfg,', '*args,', '**kwargs):', 'return', 'ShuffleNetV2(cfg,', '*args,', '**kwargs)']
960,140
vghost2008/wml1
meta_arch.py
MetaArch.m0v1
m0v1
Normalize the image to zero mean and unit variance.
[ "Normalize", "the", "image", "to", "zero", "mean", "and", "unit", "variance." ]
def m0v1(image): image = image / 255.0 offset = tf.constant([0.485, 0.456, 0.406]) offset = tf.expand_dims(offset, axis=0) offset = tf.expand_dims(offset, axis=0) image -= offset scale = tf.constant([0.229, 0.224, 0.225]) scale = tf.expand_dims(scale, axis=0) scale = tf.expand_dims(scale...
['def', 'm0v1(image):', 'image', '=', 'image', '/', '255.0', 'offset', '=', 'tf.constant([0.485,', '0.456,', '0.406])', 'offset', '=', 'tf.expand_dims(offset,', 'axis=0)', 'offset', '=', 'tf.expand_dims(offset,', 'axis=0)', 'image', '-=', 'offset', 'scale', '=', 'tf.constant([0.229,', '0.224,', '0.225])', 'scale', '=',...
960,147
vghost2008/wml1
config.py
CfgNode.merge_from_file
merge_from_file
Merge configs from a given yaml file.
[ "Merge", "configs", "from", "a", "given", "yaml", "file." ]
def merge_from_file(self, cfg_filename: str, allow_unsafe: bool=False): loaded_cfg = CfgNode.load_yaml_with_base(cfg_filename, allow_unsafe=allow_unsafe) loaded_cfg = type(self)(loaded_cfg) self.merge_from_other_cfg(loaded_cfg)
['def', 'merge_from_file(self,', 'cfg_filename:', 'str,', 'allow_unsafe:', 'bool=False):', 'loaded_cfg', '=', 'CfgNode.load_yaml_with_base(cfg_filename,', 'allow_unsafe=allow_unsafe)', 'loaded_cfg', '=', 'type(self)(loaded_cfg)', 'self.merge_from_other_cfg(loaded_cfg)']
960,264
vghost2008/wml1
conv_blocks.py
squeeze_excite
squeeze_excite
Squeeze excite block for Mobilenet V3.
[ "Squeeze", "excite", "block", "for", "Mobilenet", "V3." ]
def squeeze_excite(input_tensor, divisible_by=8, squeeze_factor=3, inner_activation_fn=tf.nn.relu, gating_fn=tf.sigmoid, squeeze_input_tensor=None, pool=None): with tf.variable_scope('squeeze_excite'): if squeeze_input_tensor is None: squeeze_input_tensor = input_tensor input_size = inpu...
['def', 'squeeze_excite(input_tensor,', 'divisible_by=8,', 'squeeze_factor=3,', 'inner_activation_fn=tf.nn.relu,', 'gating_fn=tf.sigmoid,', 'squeeze_input_tensor=None,', 'pool=None):', 'with', "tf.variable_scope('squeeze_excite'):", 'if', 'squeeze_input_tensor', 'is', 'None:', 'squeeze_input_tensor', '=', 'input_tensor...
960,312
vghost2008/wml1
coco_evaluation_test.py
CocoKeypointEvaluationTest.testGetOneMAPWithMatchingKeypoints
testGetOneMAPWithMatchingKeypoints
Tests that correct mAP for keypoints is calculated.
[ "Tests", "that", "correct", "mAP", "for", "keypoints", "is", "calculated." ]
def testGetOneMAPWithMatchingKeypoints(self): category_keypoint_dict = _get_category_keypoints_dict() coco_evaluator = coco_evaluation.CocoKeypointEvaluator(category_id=1, category_keypoints=category_keypoint_dict['person'], class_text='person') coco_evaluator.add_single_ground_truth_image_info(image_id='im...
['def', 'testGetOneMAPWithMatchingKeypoints(self):', 'category_keypoint_dict', '=', '_get_category_keypoints_dict()', 'coco_evaluator', '=', 'coco_evaluation.CocoKeypointEvaluator(category_id=1,', "category_keypoints=category_keypoint_dict['person'],", "class_text='person')", "coco_evaluator.add_single_ground_truth_ima...
960,334
vghost2008/wml1
ckpt_toolkit.py
convert_ndarray_to_tensor
convert_ndarray_to_tensor
In-place convert all numpy arrays in the state_dict to torch tensor.
[ "In-place", "convert", "all", "numpy", "arrays", "in", "the", "state_dict", "to", "torch", "tensor." ]
def convert_ndarray_to_tensor(state_dict) -> None: for k in list(state_dict.keys()): v = state_dict[k] if not isinstance(v, np.ndarray) and (not isinstance(v, torch.Tensor)): raise ValueError('Unsupported type found in checkpoint! {}: {}'.format(k, type(v))) if not isinstance(v, ...
['def', 'convert_ndarray_to_tensor(state_dict)', '->', 'None:', 'for', 'k', 'in', 'list(state_dict.keys()):', 'v', '=', 'state_dict[k]', 'if', 'not', 'isinstance(v,', 'np.ndarray)', 'and', '(not', 'isinstance(v,', 'torch.Tensor)):', 'raise', "ValueError('Unsupported", 'type', 'found', 'in', 'checkpoint!', '{}:', "{}'.f...
960,382
ParallelDots/WordEmbeddingAutoencoder
utils.py
gen_embedding
gen_embedding
Generates embedding of the word from the model trained.
[ "Generates", "embedding", "of", "the", "word", "from", "the", "model", "trained." ]
def gen_embedding(word): try: with open('./embeddings.pickle', 'rb') as f: embeddings = pickle.load(f) return embeddings[word] except Exception as e: print('Exception: Model file not found, please train the model first by runing train')
['def', 'gen_embedding(word):', 'try:', 'with', "open('./embeddings.pickle',", "'rb')", 'as', 'f:', 'embeddings', '=', 'pickle.load(f)', 'return', 'embeddings[word]', 'except', 'Exception', 'as', 'e:', "print('Exception:", 'Model', 'file', 'not', 'found,', 'please', 'train', 'the', 'model', 'first', 'by', 'runing', "tr...
960,472
wenjiesha/word_embedding_theano
classifier.py
NNet.F
F
The scalar output of neural network.
[ "The", "scalar", "output", "of", "neural", "network." ]
def F(self, x): input = self.embedding[x].reshape((x.shape[0], self.context_window_size * self.embedding_dimension)) activation = T.tanh(T.dot(input, self.w_input) + self.b_input) output = T.dot(activation, self.w_classifier) + self.b_classifier return output
['def', 'F(self,', 'x):', 'input', '=', 'self.embedding[x].reshape((x.shape[0],', 'self.context_window_size', '*', 'self.embedding_dimension))', 'activation', '=', 'T.tanh(T.dot(input,', 'self.w_input)', '+', 'self.b_input)', 'output', '=', 'T.dot(activation,', 'self.w_classifier)', '+', 'self.b_classifier', 'return', ...
960,474
fisadev/world_cup_learning
utils.py
apply_renames
apply_renames
Apply team renames to a team column from a dataframe.
[ "Apply", "team", "renames", "to", "a", "team", "column", "from", "a", "dataframe." ]
def apply_renames(column): with open(TEAM_RENAMES_FILE) as renames_file: renames = dict((l.strip().split(',') for l in renames_file.readlines() if l.strip())) def renamer(team): return renames.get(team, team) return column.map(renamer)
['def', 'apply_renames(column):', 'with', 'open(TEAM_RENAMES_FILE)', 'as', 'renames_file:', 'renames', '=', "dict((l.strip().split(',')", 'for', 'l', 'in', 'renames_file.readlines()', 'if', 'l.strip()))', 'def', 'renamer(team):', 'return', 'renames.get(team,', 'team)', 'return', 'column.map(renamer)']
960,482
fisadev/world_cup_learning
utils.py
get_winners
get_winners
Create a dataframe with podium positions info.
[ "Create", "a", "dataframe", "with", "podium", "positions", "info." ]
def get_winners(): winners = pd.DataFrame.from_csv(RAW_WINNERS_FILE) winners.team = apply_renames(winners.team) return winners
['def', 'get_winners():', 'winners', '=', 'pd.DataFrame.from_csv(RAW_WINNERS_FILE)', 'winners.team', '=', 'apply_renames(winners.team)', 'return', 'winners']
960,484
fisadev/world_cup_learning
utils.py
get_team_stats
get_team_stats
Create a dataframe with useful stats for each team.
[ "Create", "a", "dataframe", "with", "useful", "stats", "for", "each", "team." ]
def get_team_stats(): winners = get_winners() matches = get_matches() teams = set(matches.team1.unique()).union(matches.team2.unique()) stats = pd.DataFrame(list(teams), columns=['team']) stats = stats.set_index('team') for team in teams: team_matches = matches[(matches.team1 == team) | ...
['def', 'get_team_stats():', 'winners', '=', 'get_winners()', 'matches', '=', 'get_matches()', 'teams', '=', 'set(matches.team1.unique()).union(matches.team2.unique())', 'stats', '=', 'pd.DataFrame(list(teams),', "columns=['team'])", 'stats', '=', "stats.set_index('team')", 'for', 'team', 'in', 'teams:', 'team_matches'...
960,485
uta-smile/WSISA
WSISA_utils.py
patient_features
patient_features
Return patient-wise features given selected clusters and models It returns patient-wise features via aggregating the features of each separate patches.
[ "Return", "patient-wise", "features", "given", "selected", "clusters", "and", "models", "It", "returns", "patient-wise", "features", "via", "aggregating", "the", "features", "of", "each", "separate", "patches." ]
def patient_features(patch_df, selected_clusters, fea_dim=32): patients = patch_df['pid'].unique().tolist() pid = [] surv = [] status = [] features = [] for p in patients: pid.append(p) surv.extend(list(set(patch_df[patch_df['pid'] == p]['surv']))) status.extend(list(set(...
['def', 'patient_features(patch_df,', 'selected_clusters,', 'fea_dim=32):', 'patients', '=', "patch_df['pid'].unique().tolist()", 'pid', '=', '[]', 'surv', '=', '[]', 'status', '=', '[]', 'features', '=', '[]', 'for', 'p', 'in', 'patients:', 'pid.append(p)', "surv.extend(list(set(patch_df[patch_df['pid']", '==', "p]['s...
960,539
OOXXXXOO/WSNet
network.py
NETWORK.DefaultKeyPoint
DefaultKeyPoint
During training, the model expects both the input tensors, as well as a targets (list of dictionary), containing: boxes (FloatTensor[N, 4]): the ground-truth boxes in [x1, y1, x2, y2] format, with values between 0 and H and 0 and W labels (Int64Tensor[N]): the class label for each ground-truth box keypoints (FloatTenso...
[ "During", "training,", "the", "model", "expects", "both", "the", "input", "tensors,", "as", "well", "as", "a", "targets", "(list", "of", "dictionary),", "containing:", "boxes", "(FloatTensor[N,", "4]):", "the", "ground-truth", "boxes", "in", "[x1,", "y1,", "x2,"...
def DefaultKeyPoint(self, pretrained=False, progress=True): self.model = models.detection.keypointrcnn_resnet50_fpn(pretrained=pretrained, progress=progress, num_classes=2, num_keypoints=17, pretrained_backbone=True)
['def', 'DefaultKeyPoint(self,', 'pretrained=False,', 'progress=True):', 'self.model', '=', 'models.detection.keypointrcnn_resnet50_fpn(pretrained=pretrained,', 'progress=progress,', 'num_classes=2,', 'num_keypoints=17,', 'pretrained_backbone=True)']
960,572
googleinterns/wss
preprocess_utils.py
gaussian_blur
gaussian_blur
Blurs the image with separable convolution.
[ "Blurs", "the", "image", "with", "separable", "convolution." ]
def gaussian_blur(image, kernel_size, sigma, padding='SAME'): radius = tf.to_int32(kernel_size / 2) kernel_size = radius * 2 + 1 x = tf.to_float(tf.range(-radius, radius + 1)) blur_filter = tf.exp(-tf.pow(x, 2.0) / (2.0 * tf.pow(tf.to_float(sigma), 2.0))) blur_filter /= tf.reduce_sum(blur_filter) ...
['def', 'gaussian_blur(image,', 'kernel_size,', 'sigma,', "padding='SAME'):", 'radius', '=', 'tf.to_int32(kernel_size', '/', '2)', 'kernel_size', '=', 'radius', '*', '2', '+', '1', 'x', '=', 'tf.to_float(tf.range(-radius,', 'radius', '+', '1))', 'blur_filter', '=', 'tf.exp(-tf.pow(x,', '2.0)', '/', '(2.0', '*', 'tf.pow...
960,721
googleinterns/wss
preprocess_utils.py
random_color_jitter
random_color_jitter
Randomly do color jittering on the given image.
[ "Randomly", "do", "color", "jittering", "on", "the", "given", "image." ]
def random_color_jitter(image, prob=1.0): brightness = 0.5 contrast = 0.5 saturation = 0.5 hue = 0.25 random_value = tf.random.uniform([]) is_jittered = tf.less_equal(random_value, prob) jittered = color_jitter(image, brightness, contrast, saturation, hue) output = tf.cond(is_jittered, l...
['def', 'random_color_jitter(image,', 'prob=1.0):', 'brightness', '=', '0.5', 'contrast', '=', '0.5', 'saturation', '=', '0.5', 'hue', '=', '0.25', 'random_value', '=', 'tf.random.uniform([])', 'is_jittered', '=', 'tf.less_equal(random_value,', 'prob)', 'jittered', '=', 'color_jitter(image,', 'brightness,', 'contrast,'...
960,724
googleinterns/wss
resnet_v1_beta.py
resnet_arg_scope
resnet_arg_scope
Defines the default ResNet arg scope.
[ "Defines", "the", "default", "ResNet", "arg", "scope." ]
def resnet_arg_scope(weight_decay=0.0001, batch_norm_decay=0.997, batch_norm_epsilon=1e-05, batch_norm_scale=True, activation_fn=tf.nn.relu, use_batch_norm=True, sync_batch_norm_method='None', normalization_method='unspecified', use_weight_standardization=False): batch_norm_params = {'decay': batch_norm_decay, 'eps...
['def', 'resnet_arg_scope(weight_decay=0.0001,', 'batch_norm_decay=0.997,', 'batch_norm_epsilon=1e-05,', 'batch_norm_scale=True,', 'activation_fn=tf.nn.relu,', 'use_batch_norm=True,', "sync_batch_norm_method='None',", "normalization_method='unspecified',", 'use_weight_standardization=False):', 'batch_norm_params', '=',...
960,764
googleinterns/wss
dataset_utils.py
download_url
download_url
Downloads the tarball or zip file from url into filepath.
[ "Downloads", "the", "tarball", "or", "zip", "file", "from", "url", "into", "filepath." ]
def download_url(url, dataset_dir): filename = url.split('/')[-1] filepath = os.path.join(dataset_dir, filename) def _progress(count, block_size, total_size): sys.stdout.write('\r>> Downloading %s %.1f%%' % (filename, float(count * block_size) / float(total_size) * 100.0)) sys.stdout.flush(...
['def', 'download_url(url,', 'dataset_dir):', 'filename', '=', "url.split('/')[-1]", 'filepath', '=', 'os.path.join(dataset_dir,', 'filename)', 'def', '_progress(count,', 'block_size,', 'total_size):', "sys.stdout.write('\\r>>", 'Downloading', '%s', "%.1f%%'", '%', '(filename,', 'float(count', '*', 'block_size)', '/', ...
960,828
googleinterns/wss
download_and_convert_visualwakewords_lib.py
create_labels_file
create_labels_file
Generate visualwakewords labels file.
[ "Generate", "visualwakewords", "labels", "file." ]
def create_labels_file(foreground_class_of_interest, visualwakewords_labels_file): labels_to_class_names = {0: 'background', 1: foreground_class_of_interest} with open(visualwakewords_labels_file, 'w') as fp: for label in labels_to_class_names: fp.write(str(label) + ':' + str(labels_to_class...
['def', 'create_labels_file(foreground_class_of_interest,', 'visualwakewords_labels_file):', 'labels_to_class_names', '=', '{0:', "'background',", '1:', 'foreground_class_of_interest}', 'with', 'open(visualwakewords_labels_file,', "'w')", 'as', 'fp:', 'for', 'label', 'in', 'labels_to_class_names:', 'fp.write(str(label)...
960,840
googleinterns/wss
post_training_quantization.py
restore_model
restore_model
Restore variables from the checkpoint into the provided session.
[ "Restore", "variables", "from", "the", "checkpoint", "into", "the", "provided", "session." ]
def restore_model(sess, checkpoint_path, enable_ema=True): if enable_ema: ema = tf.train.ExponentialMovingAverage(decay=0.0) ema_vars = tf.trainable_variables() + tf.get_collection('moving_vars') for v in tf.global_variables(): if 'moving_mean' in v.name or 'moving_variance' in v...
['def', 'restore_model(sess,', 'checkpoint_path,', 'enable_ema=True):', 'if', 'enable_ema:', 'ema', '=', 'tf.train.ExponentialMovingAverage(decay=0.0)', 'ema_vars', '=', 'tf.trainable_variables()', '+', "tf.get_collection('moving_vars')", 'for', 'v', 'in', 'tf.global_variables():', 'if', "'moving_mean'", 'in', 'v.name'...
960,909
copenlu/X-MAML
deep-energy-mnist.py
test
test
Evaluate the performance on the test dataset.
[ "Evaluate", "the", "performance", "on", "the", "test", "dataset." ]
def test(model, device, test_loader): model.eval() test_loss = 0 correct = 0 for (data, target) in test_loader: (data, target) = (data.to(device), target.to(device)) output = model(data) test_loss += F.cross_entropy(output, target, reduction='sum').item() pred = output.ar...
['def', 'test(model,', 'device,', 'test_loader):', 'model.eval()', 'test_loss', '=', '0', 'correct', '=', '0', 'for', '(data,', 'target)', 'in', 'test_loader:', '(data,', 'target)', '=', '(data.to(device),', 'target.to(device))', 'output', '=', 'model(data)', 'test_loss', '+=', 'F.cross_entropy(output,', 'target,', "re...
961,486
copenlu/X-MAML
utils.py
flatten
flatten
Returns a flattened list of objects from a nested structure.
[ "Returns", "a", "flattened", "list", "of", "objects", "from", "a", "nested", "structure." ]
def flatten(x: _typing.Any) -> _typing.List[_typing.Any]: l: _typing.List[_typing.Any] = [] if isinstance(x, dict): for y in x.values(): l.extend(flatten(y)) elif isinstance(x, list) or isinstance(x, set) or isinstance(x, tuple): for y in x: l.extend(flatten(y)) e...
['def', 'flatten(x:', '_typing.Any)', '->', '_typing.List[_typing.Any]:', 'l:', '_typing.List[_typing.Any]', '=', '[]', 'if', 'isinstance(x,', 'dict):', 'for', 'y', 'in', 'x.values():', 'l.extend(flatten(y))', 'elif', 'isinstance(x,', 'list)', 'or', 'isinstance(x,', 'set)', 'or', 'isinstance(x,', 'tuple):', 'for', 'y',...
961,490
copenlu/X-MAML
utils.py
get_func_params
get_func_params
Returns a detached copy of module parameters which requires gradient.
[ "Returns", "a", "detached", "copy", "of", "module", "parameters", "which", "requires", "gradient." ]
def get_func_params(module: _torch.nn.Module, device: _typing.Optional[_torch.device]=None, safe_copy: bool=True) -> _typing.List[_torch.Tensor]: params = [_copy_tensor(p, safe_copy, device) for p in module.parameters()] return params
['def', 'get_func_params(module:', '_torch.nn.Module,', 'device:', '_typing.Optional[_torch.device]=None,', 'safe_copy:', 'bool=True)', '->', '_typing.List[_torch.Tensor]:', 'params', '=', '[_copy_tensor(p,', 'safe_copy,', 'device)', 'for', 'p', 'in', 'module.parameters()]', 'return', 'params']
961,491
copenlu/X-MAML
test_higher.py
TestCorrectness.testSameInitialWeightsPostPatch
testSameInitialWeightsPostPatch
Verify fast weight alignment/equality after monkey patching.
[ "Verify", "fast", "weight", "alignment/equality", "after", "monkey", "patching." ]
def testSameInitialWeightsPostPatch(self): ref_named_params = list(self.reference_net.get_fast_weights().items()) ref_params = [p for (_, p) in ref_named_params] with higher.innerloop_ctx(self.target_net, self.opt) as (fnet, _): target_named_params = list(fnet.named_parameters()) target_para...
['def', 'testSameInitialWeightsPostPatch(self):', 'ref_named_params', '=', 'list(self.reference_net.get_fast_weights().items())', 'ref_params', '=', '[p', 'for', '(_,', 'p)', 'in', 'ref_named_params]', 'with', 'higher.innerloop_ctx(self.target_net,', 'self.opt)', 'as', '(fnet,', '_):', 'target_named_params', '=', 'list...
961,493
copenlu/X-MAML
test_higher.py
TestCorrectness.testUnrollEqualityForward
testUnrollEqualityForward
Check if unrolled patched and reference nets produce same meta loss.
[ "Check", "if", "unrolled", "patched", "and", "reference", "nets", "produce", "same", "meta", "loss." ]
def testUnrollEqualityForward(self): for test_it in range(5): with higher.innerloop_ctx(self.target_net, self.opt) as (fnet, diffopt): (ref_out, target_out) = self._joint_inner_loop(fnet, diffopt=diffopt, num_steps=10) ref_meta_loss = ref_out[0] ref_fast_weights = ref_out...
['def', 'testUnrollEqualityForward(self):', 'for', 'test_it', 'in', 'range(5):', 'with', 'higher.innerloop_ctx(self.target_net,', 'self.opt)', 'as', '(fnet,', 'diffopt):', '(ref_out,', 'target_out)', '=', 'self._joint_inner_loop(fnet,', 'diffopt=diffopt,', 'num_steps=10)', 'ref_meta_loss', '=', 'ref_out[0]', 'ref_fast_...
961,495
copenlu/X-MAML
utils.py
train
train
Train a model for one epoch on some input data with a given optimizer and criterion.
[ "Train", "a", "model", "for", "one", "epoch", "on", "some", "input", "data", "with", "a", "given", "optimizer", "and", "criterion." ]
def train(model, dataloader, optimizer, epoch_number, max_gradient_norm): model.train() device = model.device epoch_start = time.time() batch_time_avg = 0.0 running_loss = 0.0 correct_preds = 0 tqdm_batch_iterator = tqdm(dataloader) for (batch_index, batch) in tqdm(enumerate(tqdm_batch_i...
['def', 'train(model,', 'dataloader,', 'optimizer,', 'epoch_number,', 'max_gradient_norm):', 'model.train()', 'device', '=', 'model.device', 'epoch_start', '=', 'time.time()', 'batch_time_avg', '=', '0.0', 'running_loss', '=', '0.0', 'correct_preds', '=', '0', 'tqdm_batch_iterator', '=', 'tqdm(dataloader)', 'for', '(ba...
961,499
MaxHalford/xam
utils.py
find_skyline
find_skyline
Finds the skyline of a dataframe using a block-nested loop algorithm.
[ "Finds", "the", "skyline", "of", "a", "dataframe", "using", "a", "block-nested", "loop", "algorithm." ]
def find_skyline(df, to_min, to_max): def count_diffs(a, b, to_min, to_max): n_better = 0 n_worse = 0 for f in to_min: n_better += a[f] < b[f] n_worse += a[f] > b[f] for f in to_max: n_better += a[f] > b[f] n_worse += a[f] < b[f] ...
['def', 'find_skyline(df,', 'to_min,', 'to_max):', 'def', 'count_diffs(a,', 'b,', 'to_min,', 'to_max):', 'n_better', '=', '0', 'n_worse', '=', '0', 'for', 'f', 'in', 'to_min:', 'n_better', '+=', 'a[f]', '<', 'b[f]', 'n_worse', '+=', 'a[f]', '>', 'b[f]', 'for', 'f', 'in', 'to_max:', 'n_better', '+=', 'a[f]', '>', 'b[f]'...
961,839
MaxHalford/xam
utils.py
datetime_range
datetime_range
Generates datetimes in range [since, until] with a given step.
[ "Generates", "datetimes", "in", "range", "[since,", "until]", "with", "a", "given", "step." ]
def datetime_range(since, until, step=dt.timedelta(days=1)): for i in range((until - since) // step + 1): yield (since + step * i)
['def', 'datetime_range(since,', 'until,', 'step=dt.timedelta(days=1)):', 'for', 'i', 'in', 'range((until', '-', 'since)', '//', 'step', '+', '1):', 'yield', '(since', '+', 'step', '*', 'i)']
961,841
MaxHalford/xam
utils.py
subsequence_lengths
subsequence_lengths
Calculate the lengths of each subsequence in a sequence.
[ "Calculate", "the", "lengths", "of", "each", "subsequence", "in", "a", "sequence." ]
def subsequence_lengths(sequence): lengths = defaultdict(list) i = 1 for (pre, post) in zip(sequence, sequence[1:]): if pre == post: i += 1 else: lengths[pre].append(i) i = 1 if sequence[-1] == sequence[-2]: lengths[sequence[-1]].append(i) ...
['def', 'subsequence_lengths(sequence):', 'lengths', '=', 'defaultdict(list)', 'i', '=', '1', 'for', '(pre,', 'post)', 'in', 'zip(sequence,', 'sequence[1:]):', 'if', 'pre', '==', 'post:', 'i', '+=', '1', 'else:', 'lengths[pre].append(i)', 'i', '=', '1', 'if', 'sequence[-1]', '==', 'sequence[-2]:', 'lengths[sequence[-1]...
961,843
MaxHalford/xam
spell_correct.py
NorvigSpellingCorrector.correct_word
correct_word
Most probable spelling correction for a word.
[ "Most", "probable", "spelling", "correction", "for", "a", "word." ]
def correct_word(self, word): return max(self._candidates(word), key=self._p)
['def', 'correct_word(self,', 'word):', 'return', 'max(self._candidates(word),', 'key=self._p)']
961,852
MaxHalford/xam
spell_correct.py
NorvigSpellingCorrector.correct_sentence
correct_sentence
Most probable spelling correction for a sentence.
[ "Most", "probable", "spelling", "correction", "for", "a", "sentence." ]
def correct_sentence(self, sentence): return ' '.join((self.correct_word(word) for word in self.tokenize(sentence)))
['def', 'correct_sentence(self,', 'sentence):', 'return', "'", "'.join((self.correct_word(word)", 'for', 'word', 'in', 'self.tokenize(sentence)))']
961,853
MaxHalford/xam
spell_correct.py
NorvigSpellingCorrector.count_sentence_mistakes
count_sentence_mistakes
Count number of spelling mistakes in a sentence.
[ "Count", "number", "of", "spelling", "mistakes", "in", "a", "sentence." ]
def count_sentence_mistakes(self, sentence): return sum((word != self.correct_word(word) for word in self.tokenize(sentence)))
['def', 'count_sentence_mistakes(self,', 'sentence):', 'return', 'sum((word', '!=', 'self.correct_word(word)', 'for', 'word', 'in', 'self.tokenize(sentence)))']
961,854
MaxHalford/xam
base.py
BaseBinner.transform
transform
Binarize X based on the fitted cut points.
[ "Binarize", "X", "based", "on", "the", "fitted", "cut", "points." ]
def transform(self, X, y=None): X = check_array(X) if self.cut_points is None: raise NotFittedError('Estimator not fitted, call `fit` before exploiting the model.') if X.shape[1] != len(self.cut_points): raise ValueError("Provided array's dimensions do not match with the ones from the array ...
['def', 'transform(self,', 'X,', 'y=None):', 'X', '=', 'check_array(X)', 'if', 'self.cut_points', 'is', 'None:', 'raise', "NotFittedError('Estimator", 'not', 'fitted,', 'call', '`fit`', 'before', 'exploiting', 'the', "model.')", 'if', 'X.shape[1]', '!=', 'len(self.cut_points):', 'raise', 'ValueError("Provided', "array'...
961,855
MaxHalford/xam
mdlp.py
MDLPBinner.fit
fit
Determine which are the best cut points for each column in X based on y.
[ "Determine", "which", "are", "the", "best", "cut", "points", "for", "each", "column", "in", "X", "based", "on", "y." ]
def fit(self, X, y, **fit_params): (X, y) = check_X_y(X, y, y_numeric=True) self.cut_points_ = [mdlp_cut(x, y, []) for x in X.T] return self
['def', 'fit(self,', 'X,', 'y,', '**fit_params):', '(X,', 'y)', '=', 'check_X_y(X,', 'y,', 'y_numeric=True)', 'self.cut_points_', '=', '[mdlp_cut(x,', 'y,', '[])', 'for', 'x', 'in', 'X.T]', 'return', 'self']
961,858
MaxHalford/xam
base.py
BaseForecaster.predict
predict
Make forecasts from a list of timestamps.
[ "Make", "forecasts", "from", "a", "list", "of", "timestamps." ]
def predict(self, timestamps): raise NotImplementedError
['def', 'predict(self,', 'timestamps):', 'raise', 'NotImplementedError']
961,859
amzn/xfer
metalogger.py
MetaLogger.plot_losses
plot_losses
Plot the logged losses.
[ "Plot", "the", "logged", "losses." ]
def plot_losses(self, add_label=True, figsize=(20, 4)): if self._losses == {}: raise ValueError('No losses logged.') (fig, axes) = plt.subplots(ncols=self.num_tasks, figsize=figsize) fig.suptitle('Losses', fontsize=30, y=1.08) for task in range(self.num_tasks): axes[task].set_title('Task...
['def', 'plot_losses(self,', 'add_label=True,', 'figsize=(20,', '4)):', 'if', 'self._losses', '==', '{}:', 'raise', "ValueError('No", 'losses', "logged.')", '(fig,', 'axes)', '=', 'plt.subplots(ncols=self.num_tasks,', 'figsize=figsize)', "fig.suptitle('Losses',", 'fontsize=30,', 'y=1.08)', 'for', 'task', 'in', 'range(s...
961,930
amzn/xfer
onmiglot.py
MetaTaskOmniglot.plot_sample
plot_sample
Plot N images from each alphabet and store the images in root.
[ "Plot", "N", "images", "from", "each", "alphabet", "and", "store", "the", "images", "in", "root." ]
def plot_sample(self, num_samples, root='./sample_onmiglot'): if not os.path.exists(root): os.makedirs(root) fig_train = self._plot(num_samples, [dd._train_dataset for dd in self.train_tasks], 'Training Samples for Training Tasks') fig_train.savefig(os.path.join(root, 'sample_train_train_tasks.png')...
['def', 'plot_sample(self,', 'num_samples,', "root='./sample_onmiglot'):", 'if', 'not', 'os.path.exists(root):', 'os.makedirs(root)', 'fig_train', '=', 'self._plot(num_samples,', '[dd._train_dataset', 'for', 'dd', 'in', 'self.train_tasks],', "'Training", 'Samples', 'for', 'Training', "Tasks')", 'fig_train.savefig(os.pa...
961,934
amzn/xfer
algorithm.py
Algorithm.compute_grad_loss
compute_grad_loss
Compute the loss between true gradients and synthetic gradients.
[ "Compute", "the", "loss", "between", "true", "gradients", "and", "synthetic", "gradients." ]
def compute_grad_loss(self, clsScore, QueryLabel): def require_nonleaf_grad(v): def hook(g): v.grad_nonleaf = g h = v.register_hook(hook) return h handle = require_nonleaf_grad(clsScore) loss = self.criterion(clsScore, QueryLabel) loss.backward(retain_graph=True) ...
['def', 'compute_grad_loss(self,', 'clsScore,', 'QueryLabel):', 'def', 'require_nonleaf_grad(v):', 'def', 'hook(g):', 'v.grad_nonleaf', '=', 'g', 'h', '=', 'v.register_hook(hook)', 'return', 'h', 'handle', '=', 'require_nonleaf_grad(clsScore)', 'loss', '=', 'self.criterion(clsScore,', 'QueryLabel)', 'loss.backward(reta...
961,952
amzn/xfer
meta_model_repurposer.py
MetaModelRepurposer.source_model
source_model
Model to extract features from.
[ "Model", "to", "extract", "features", "from." ]
def source_model(self): return self._source_model
['def', 'source_model(self):', 'return', 'self._source_model']
961,987
gintautasp12/xgan
api.py
face_to_cartoon
face_to_cartoon
Converts face image into cartoon.
[ "Converts", "face", "image", "into", "cartoon." ]
def face_to_cartoon(DOC_FILE, face): document_name = DOC_FILE.split('.')[0] extension = DOC_FILE.split('.')[-1].lower() document = Image.open(io.BytesIO(face)) if not os.path.exists(DOWNLOAD_DIRECTORY): os.makedirs(DOWNLOAD_DIRECTORY) if extension == 'png': format_image = 'PNG' e...
['def', 'face_to_cartoon(DOC_FILE,', 'face):', 'document_name', '=', "DOC_FILE.split('.')[0]", 'extension', '=', "DOC_FILE.split('.')[-1].lower()", 'document', '=', 'Image.open(io.BytesIO(face))', 'if', 'not', 'os.path.exists(DOWNLOAD_DIRECTORY):', 'os.makedirs(DOWNLOAD_DIRECTORY)', 'if', 'extension', '==', "'png':", '...
962,002
gintautasp12/xgan
__init__.py
parse_configuration
parse_configuration
Loads config file if a string was passed and returns the input if a dictionary was passed.
[ "Loads", "config", "file", "if", "a", "string", "was", "passed", "and", "returns", "the", "input", "if", "a", "dictionary", "was", "passed." ]
def parse_configuration(config_file): if isinstance(config_file, str): with open(config_file, 'r') as json_file: return json.load(json_file) else: return config_file
['def', 'parse_configuration(config_file):', 'if', 'isinstance(config_file,', 'str):', 'with', 'open(config_file,', "'r')", 'as', 'json_file:', 'return', 'json.load(json_file)', 'else:', 'return', 'config_file']
962,014
huawei-noah/xingtian
benchmark_within_ci.py
get_bm_fix_path
get_bm_fix_path
Get model path of benchmark yaml.
[ "Get", "model", "path", "of", "benchmark", "yaml." ]
def get_bm_fix_path(bm_info, key_seq, last_path=None): _bm_path_seq = [bm_info[_key] for _key in key_seq] if last_path: _bm_path_seq += [last_path] target_path = os.path.join(*_bm_path_seq) return target_path
['def', 'get_bm_fix_path(bm_info,', 'key_seq,', 'last_path=None):', '_bm_path_seq', '=', '[bm_info[_key]', 'for', '_key', 'in', 'key_seq]', 'if', 'last_path:', '_bm_path_seq', '+=', '[last_path]', 'target_path', '=', 'os.path.join(*_bm_path_seq)', 'return', 'target_path']
962,015
huawei-noah/xingtian
benchmark_within_ci.py
assemble_config_file
assemble_config_file
Add timestamp into benchmark id.
[ "Add", "timestamp", "into", "benchmark", "id." ]
def assemble_config_file(config_info, total_steps): target_info = config_info.copy() _bm = config_info['benchmark'] target_info['benchmark'].update({'id': '+'.join([_bm['id'], datetime.now().strftime('%Y%m%d%H%M%S')])}) if 'agent_config' not in target_info['agent_para']: target_info['agent_para'...
['def', 'assemble_config_file(config_info,', 'total_steps):', 'target_info', '=', 'config_info.copy()', '_bm', '=', "config_info['benchmark']", "target_info['benchmark'].update({'id':", "'+'.join([_bm['id'],", "datetime.now().strftime('%Y%m%d%H%M%S')])})", 'if', "'agent_config'", 'not', 'in', "target_info['agent_para']...
962,016
huawei-noah/xingtian
guard_with_train.py
parallel_case_check
parallel_case_check
check one case in Parallel, vary node, env.
[ "check", "one", "case", "in", "Parallel,", "vary", "node,", "env." ]
def parallel_case_check(processes): while True: exitcodes = [] for process in processes: exitcodes.append(process.exitcode) if process.exitcode is not None and process.exitcode != 0: print('process.exitcode: ', process.exitcode) return 1 ...
['def', 'parallel_case_check(processes):', 'while', 'True:', 'exitcodes', '=', '[]', 'for', 'process', 'in', 'processes:', 'exitcodes.append(process.exitcode)', 'if', 'process.exitcode', 'is', 'not', 'None', 'and', 'process.exitcode', '!=', '0:', "print('process.exitcode:", "',", 'process.exitcode)', 'return', '1', 'ex...
962,017
huawei-noah/xingtian
train.py
setup_broker_stats
setup_broker_stats
Setup stats for each task.
[ "Setup", "stats", "for", "each", "task." ]
def setup_broker_stats(task_stub, to_broker): stats_obj = StatsRecorder(msg_deliver=task_stub.stats_deliver, bm_args=task_stub.bm_args, workspace=task_stub.workspace, bm_board=task_stub.bm_board, name=task_stub.name) to_broker.stats.add_stats_recorder(task_stub.name, stats_obj)
['def', 'setup_broker_stats(task_stub,', 'to_broker):', 'stats_obj', '=', 'StatsRecorder(msg_deliver=task_stub.stats_deliver,', 'bm_args=task_stub.bm_args,', 'workspace=task_stub.workspace,', 'bm_board=task_stub.bm_board,', 'name=task_stub.name)', 'to_broker.stats.add_stats_recorder(task_stub.name,', 'stats_obj)']
962,027
huawei-noah/xingtian
train.py
handle_multi_case
handle_multi_case
Catch <ctrl+c> signal for clean stop.
[ "Catch", "<ctrl+c>", "signal", "for", "clean", "stop." ]
def handle_multi_case(sig, frame): global TRAIN_PROCESS_LIST for p in TRAIN_PROCESS_LIST: p.send_signal(signal.SIGINT) time.sleep(1) os._exit(0)
['def', 'handle_multi_case(sig,', 'frame):', 'global', 'TRAIN_PROCESS_LIST', 'for', 'p', 'in', 'TRAIN_PROCESS_LIST:', 'p.send_signal(signal.SIGINT)', 'time.sleep(1)', 'os._exit(0)']
962,028
huawei-noah/xingtian
train.py
write_conf_file
write_conf_file
Write config to file.
[ "Write", "config", "to", "file." ]
def write_conf_file(config_folder, config): with open(config_folder, 'w') as f: yaml.dump(config, f)
['def', 'write_conf_file(config_folder,', 'config):', 'with', 'open(config_folder,', "'w')", 'as', 'f:', 'yaml.dump(config,', 'f)']
962,029
huawei-noah/xingtian
agent.py
Agent.sum_trajectory_reward
sum_trajectory_reward
Return the sum of trajectory reward.
[ "Return", "the", "sum", "of", "trajectory", "reward." ]
def sum_trajectory_reward(self): return {self.id: {'epi_reward': np.sum(self.trajectory['reward']), 'step_reward': np.mean(self.trajectory['reward'])}}
['def', 'sum_trajectory_reward(self):', 'return', '{self.id:', "{'epi_reward':", "np.sum(self.trajectory['reward']),", "'step_reward':", "np.mean(self.trajectory['reward'])}}"]
962,033
huawei-noah/xingtian
agent.py
Agent.get_perf_stats
get_perf_stats
Get status after run once episode.
[ "Get", "status", "after", "run", "once", "episode." ]
def get_perf_stats(self): _stats_info = self._stats.get() mean_reward = getattr(self, 'get_explore_mean_reward', None) if mean_reward and callable(mean_reward): explore_reward = mean_reward() _stats_info.update({'mean_explore_reward': explore_reward}) return _stats_info
['def', 'get_perf_stats(self):', '_stats_info', '=', 'self._stats.get()', 'mean_reward', '=', 'getattr(self,', "'get_explore_mean_reward',", 'None)', 'if', 'mean_reward', 'and', 'callable(mean_reward):', 'explore_reward', '=', 'mean_reward()', "_stats_info.update({'mean_explore_reward':", 'explore_reward})', 'return', ...
962,039
huawei-noah/xingtian
atari_impala_opt.py
AtariImpalaOpt.get_explore_mean_reward
get_explore_mean_reward
Calculate explore reward among limited trajectory.
[ "Calculate", "explore", "reward", "among", "limited", "trajectory." ]
def get_explore_mean_reward(self): return np.nan if not self.reward_track else np.nanmean(self.reward_track)
['def', 'get_explore_mean_reward(self):', 'return', 'np.nan', 'if', 'not', 'self.reward_track', 'else', 'np.nanmean(self.reward_track)']
962,045
huawei-noah/xingtian
atari_impala_opt.py
AtariImpalaOpt.sync_model
sync_model
Block wait one [new] model when sync need.
[ "Block", "wait", "one", "[new]", "model", "when", "sync", "need." ]
def sync_model(self): model_name = None self.sync_weights_count += 1 if self.sync_weights_count >= self.broadcast_weights_interval: model_name = self.recv_explorer.recv(block=True) self.sync_weights_count = 0 model_successor = self.recv_explorer.recv(block=False) while model_...
['def', 'sync_model(self):', 'model_name', '=', 'None', 'self.sync_weights_count', '+=', '1', 'if', 'self.sync_weights_count', '>=', 'self.broadcast_weights_interval:', 'model_name', '=', 'self.recv_explorer.recv(block=True)', 'self.sync_weights_count', '=', '0', 'model_successor', '=', 'self.recv_explorer.recv(block=F...
962,048
huawei-noah/xingtian
mcts.py
Mcts.get_info
get_info
Get train info from mcts tree.
[ "Get", "train", "info", "from", "mcts", "tree." ]
def get_info(self): child_visits = [self.root.children[a].visit_count for a in self.actions] sum_visits = sum(child_visits) child_visits = [visits / sum_visits for visits in child_visits] return {'child_visits': child_visits, 'root_value': self.root.value()}
['def', 'get_info(self):', 'child_visits', '=', '[self.root.children[a].visit_count', 'for', 'a', 'in', 'self.actions]', 'sum_visits', '=', 'sum(child_visits)', 'child_visits', '=', '[visits', '/', 'sum_visits', 'for', 'visits', 'in', 'child_visits]', 'return', "{'child_visits':", 'child_visits,', "'root_value':", 'sel...
962,058
huawei-noah/xingtian
muzero_atari.py
MuzeroAtari.infer_action
infer_action
We then run a Monte Carlo Tree Search using only action sequences and the model learned by the networks.
[ "We", "then", "run", "a", "Monte", "Carlo", "Tree", "Search", "using", "only", "action", "sequences", "and", "the", "model", "learned", "by", "the", "networks." ]
def infer_action(self, state, use_explore): state = state.astype('uint8') action = super().infer_action(state, use_explore) return action
['def', 'infer_action(self,', 'state,', 'use_explore):', 'state', '=', "state.astype('uint8')", 'action', '=', 'super().infer_action(state,', 'use_explore)', 'return', 'action']
962,062
huawei-noah/xingtian
starcraft_qmix.py
StarCraftQMix.calc_custom_evaluate
calc_custom_evaluate
Calculate the win rate.
[ "Calculate", "the", "win", "rate." ]
def calc_custom_evaluate(self): return {self.id: self._info.copy()}
['def', 'calc_custom_evaluate(self):', 'return', '{self.id:', 'self._info.copy()}']
962,068
huawei-noah/xingtian
algorithm.py
Algorithm.prepare_data_times
prepare_data_times
Unify the prepare data time for each train operation.
[ "Unify", "the", "prepare", "data", "time", "for", "each", "train", "operation." ]
def prepare_data_times(self): return self._prepare_times_per_train
['def', 'prepare_data_times(self):', 'return', 'self._prepare_times_per_train']
962,074
huawei-noah/xingtian
algorithm.py
Algorithm.checkpoint_ready
checkpoint_ready
Support custom checkpoint logic after training.
[ "Support", "custom", "checkpoint", "logic", "after", "training." ]
def checkpoint_ready(self, train_count, **kwargs): self._train_ready = False if train_count % self.train_per_checkpoint == 0: return True return False
['def', 'checkpoint_ready(self,', 'train_count,', '**kwargs):', 'self._train_ready', '=', 'False', 'if', 'train_count', '%', 'self.train_per_checkpoint', '==', '0:', 'return', 'True', 'return', 'False']
962,078
huawei-noah/xingtian
pbt.py
PbtAid.meet_stop
meet_stop
Need stop the population.
[ "Need", "stop", "the", "population." ]
def meet_stop(self, cur_episode_index): if self._max_episode and self._previous_acc_episode + cur_episode_index > self._max_episode: return True return False
['def', 'meet_stop(self,', 'cur_episode_index):', 'if', 'self._max_episode', 'and', 'self._previous_acc_episode', '+', 'cur_episode_index', '>', 'self._max_episode:', 'return', 'True', 'return', 'False']
962,084
huawei-noah/xingtian
pbt.py
PbtAid.update_self_metric
update_self_metric
Update self info into population.
[ "Update", "self", "info", "into", "population." ]
def update_self_metric(self, metric): metric_handler = self.metric_stub[self._lid] metric_handler.update(metric) self.metric_stub[self._lid] = metric_handler
['def', 'update_self_metric(self,', 'metric):', 'metric_handler', '=', 'self.metric_stub[self._lid]', 'metric_handler.update(metric)', 'self.metric_stub[self._lid]', '=', 'metric_handler']
962,085
huawei-noah/xingtian
pbt.py
PbtAid.fetch_population_metric
fetch_population_metric
Fetch population newest info.
[ "Fetch", "population", "newest", "info." ]
def fetch_population_metric(self): return self.metric_stub
['def', 'fetch_population_metric(self):', 'return', 'self.metric_stub']
962,087
huawei-noah/xingtian
muzero.py
Muzero.make_target
make_target
Generate targets to learn from during the network training.
[ "Generate", "targets", "to", "learn", "from", "during", "the", "network", "training." ]
def make_target(self, state_index, traj): targets = [] root_values = traj['root_value'] rewards = traj['reward'] child_visits = traj['child_visits'] target_value = traj['target_value'] obs = traj['cur_state'] for current_index in range(state_index, state_index + self.unroll_step + 1): ...
['def', 'make_target(self,', 'state_index,', 'traj):', 'targets', '=', '[]', 'root_values', '=', "traj['root_value']", 'rewards', '=', "traj['reward']", 'child_visits', '=', "traj['child_visits']", 'target_value', '=', "traj['target_value']", 'obs', '=', "traj['cur_state']", 'for', 'current_index', 'in', 'range(state_i...
962,114
huawei-noah/xingtian
ppo.py
PPO.predict
predict
Overwrite the predict function, owing to the special input.
[ "Overwrite", "the", "predict", "function,", "owing", "to", "the", "special", "input." ]
def predict(self, state): if not isinstance(state, (list, tuple)): state = state.reshape((1,) + state.shape) else: state = list(map(lambda x: x.reshape((1,) + x.shape), state)) state = np.vstack(state) pred = self.actor.predict(state) return pred
['def', 'predict(self,', 'state):', 'if', 'not', 'isinstance(state,', '(list,', 'tuple)):', 'state', '=', 'state.reshape((1,)', '+', 'state.shape)', 'else:', 'state', '=', 'list(map(lambda', 'x:', 'x.reshape((1,)', '+', 'x.shape),', 'state))', 'state', '=', 'np.vstack(state)', 'pred', '=', 'self.actor.predict(state)', ...
962,115
huawei-noah/xingtian
qmix.py
QMixAlgorithm.build_agent_net
build_agent_net
Build default init_state for rnn.
[ "Build", "default", "init_state", "for", "rnn." ]
def build_agent_net(self, inputs_obs, seq_max, obs_lengths, hidden_state_in=None): fc1 = tf.layers.dense(inputs=inputs_obs, units=self.args.rnn_hidden_dim, activation=tf.nn.relu) fc1 = tf.transpose(fc1, perm=[0, 2, 1, 3]) print('\n fc1 before reshape: ', fc1) fc1 = tf.reshape(fc1, [-1, seq_max, self.arg...
['def', 'build_agent_net(self,', 'inputs_obs,', 'seq_max,', 'obs_lengths,', 'hidden_state_in=None):', 'fc1', '=', 'tf.layers.dense(inputs=inputs_obs,', 'units=self.args.rnn_hidden_dim,', 'activation=tf.nn.relu)', 'fc1', '=', 'tf.transpose(fc1,', 'perm=[0,', '2,', '1,', '3])', "print('\\n", 'fc1', 'before', 'reshape:', ...
962,116
huawei-noah/xingtian
qmix.py
QMixAlgorithm.build_actor_graph
build_actor_graph
Build an actor graph used by the explorer.
[ "Build", "an", "actor", "graph", "used", "by", "the", "explorer." ]
def build_actor_graph(self): with self.graph.as_default(): self.ph_obs = tf.placeholder(tf.float32, shape=(1, 1, self.n_agents, self.obs_shape), name='obs') self.ph_hidden_states_in = tf.placeholder(tf.float32, shape=(None, self.args.rnn_hidden_dim), name='hidden_in') with tf.variable_scope(...
['def', 'build_actor_graph(self):', 'with', 'self.graph.as_default():', 'self.ph_obs', '=', 'tf.placeholder(tf.float32,', 'shape=(1,', '1,', 'self.n_agents,', 'self.obs_shape),', "name='obs')", 'self.ph_hidden_states_in', '=', 'tf.placeholder(tf.float32,', 'shape=(None,', 'self.args.rnn_hidden_dim),', "name='hidden_in'...
962,118
huawei-noah/xingtian
qmix.py
QMixAlgorithm.reset_hidden_state
reset_hidden_state
Reset hidden before start each episode.
[ "Reset", "hidden", "before", "start", "each", "episode." ]
def reset_hidden_state(self): self.hi_out_val = self.hi_out_val_default
['def', 'reset_hidden_state(self):', 'self.hi_out_val', '=', 'self.hi_out_val_default']
962,119
huawei-noah/xingtian
qmix.py
QMixAlgorithm.get_explore_actions
get_explore_actions
Get explore action with numpy.
[ "Get", "explore", "action", "with", "numpy." ]
def get_explore_actions(self, ep_batch, t_ep, t_env, test_mode): avail_actions = ep_batch['avail_actions'][:, t_ep] agent_inputs = self.build_inputs(ep_batch, t_ep) out_val = self.infer_actions(agent_inputs) select_actions = self.selector.select_action(out_val, avail_actions, t_env, test_mode=test_mode)...
['def', 'get_explore_actions(self,', 'ep_batch,', 't_ep,', 't_env,', 'test_mode):', 'avail_actions', '=', "ep_batch['avail_actions'][:,", 't_ep]', 'agent_inputs', '=', 'self.build_inputs(ep_batch,', 't_ep)', 'out_val', '=', 'self.infer_actions(agent_inputs)', 'select_actions', '=', 'self.selector.select_action(out_val,...
962,120
huawei-noah/xingtian
qmix.py
QMixAlgorithm.save_explore_agent_weights
save_explore_agent_weights
Save explore agent weight for explorer.
[ "Save", "explore", "agent", "weight", "for", "explorer." ]
def save_explore_agent_weights(self, save_path): explore_saver = tf.train.Saver({t.name: t for t in self._explore_paras}) explore_saver.save(self.sess, save_path=save_path, write_meta_graph=False)
['def', 'save_explore_agent_weights(self,', 'save_path):', 'explore_saver', '=', 'tf.train.Saver({t.name:', 't', 'for', 't', 'in', 'self._explore_paras})', 'explore_saver.save(self.sess,', 'save_path=save_path,', 'write_meta_graph=False)']
962,122