Skip to content

Commit

Permalink
Refactoring about None, spacing and indent. (apache#5477)
Browse files Browse the repository at this point in the history
  • Loading branch information
fukatani authored and piiswrong committed Mar 19, 2017
1 parent 47b3b7a commit d2fc1e6
Show file tree
Hide file tree
Showing 18 changed files with 213 additions and 213 deletions.
2 changes: 1 addition & 1 deletion example/bayesian-methods/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def get_executor(sym, ctx, data_inputs, initializer=None):
exe = sym.bind(ctx=ctx, args=dict(params, **data_inputs),
args_grad=params_grad,
aux_states=aux_states)
if initializer != None:
if initializer is not None:
for k, v in params.items():
initializer(k, v)
return exe, params, params_grad, aux_states
Expand Down
4 changes: 2 additions & 2 deletions example/bi-lstm-sort/sort_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,11 @@ def __init__(self, path, vocab, buckets, batch_size,
seperate_char=' <eos> ', text2id=None, read_content=None):
super(BucketSentenceIter, self).__init__()

if text2id == None:
if text2id is None:
self.text2id = default_text2id
else:
self.text2id = text2id
if read_content == None:
if read_content is None:
self.read_content = default_read_content
else:
self.read_content = read_content
Expand Down
4 changes: 2 additions & 2 deletions example/caffe/train_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,11 @@ def fit(args, network, data_loader, eval_metrics=None, batch_end_callback=None):
initializer = mx.init.Xavier(factor_type="in", magnitude=2.34),
**model_args)

if eval_metrics == None:
if eval_metrics is None:
eval_metrics = ['accuracy']
## TopKAccuracy only allows top_k > 1
for top_k in [5, 10, 20]:
eval_metrics.append(mx.metric.create('top_k_accuracy', top_k = top_k))
eval_metrics.append(mx.metric.create('top_k_accuracy', top_k=top_k))

if batch_end_callback is not None:
if not isinstance(batch_end_callback, list):
Expand Down
2 changes: 1 addition & 1 deletion example/fcn-xs/solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def fit(self, train_data, eval_data=None,
self.exector.outputs[0].wait_to_read()
batch_end_params = BatchEndParam(epoch=epoch, nbatch=nbatch, eval_metric=eval_metric)
batch_end_callback(batch_end_params)
if epoch_end_callback != None:
if epoch_end_callback is not None:
epoch_end_callback(epoch, self.symbol, self.arg_params, self.aux_params)
name, value = eval_metric.get()
logger.info(" --->Epoch[%d] Train-%s=%f", epoch, name, value)
Expand Down
4 changes: 2 additions & 2 deletions example/kaggle-ndsb2/Preprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def write_label_csv(fname, frames, label_map):
fo = open(fname, "w")
for lst in frames:
index = int(lst[0].split("/")[3])
if label_map != None:
if label_map is not None:
fo.write(label_map[index])
else:
fo.write("%d,0,0\n" % index)
Expand All @@ -69,7 +69,7 @@ def get_data(lst,preproc):
data.append(img)
data = np.array(data, dtype=np.uint8)
data = data.reshape(data.size)
data = np.array(data,dtype=np.str_)
data = np.array(data, dtype=np.str_)
data = data.reshape(data.size)
return [data,result]

Expand Down
2 changes: 1 addition & 1 deletion example/model-parallel-lstm/lstm.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ def setup_rnn_model(default_ctx,
grad_req="add", group2ctx=group2ctx)
max_rnn_exec = rnn_exec
else:
assert max_rnn_exec != None
assert max_rnn_exec is not None
rnn_exec = rnn_sym.bind(default_ctx, args=arg_arrays,
args_grad=args_grad,
grad_req="add", group2ctx=group2ctx,
Expand Down
2 changes: 1 addition & 1 deletion example/model-parallel-lstm/lstm_ptb.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def load_data(path, dic=None):
content = content.split(' ')
print("Loading %s, size of data = %d" % (path, len(content)))
x = np.zeros(len(content))
if dic == None:
if dic is None:
dic = {}
idx = 0
for i in range(len(content)):
Expand Down
4 changes: 2 additions & 2 deletions example/multi-task/example_multi_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def __init__(self, num=None):
def update(self, labels, preds):
mx.metric.check_label_shapes(labels, preds)

if self.num != None:
if self.num is not None:
assert len(labels) == self.num

for i in range(len(labels)):
Expand All @@ -73,7 +73,7 @@ def update(self, labels, preds):

mx.metric.check_label_shapes(label, pred_label)

if i == None:
if i is None:
self.sum_metric += (pred_label.flat == label.flat).sum()
self.num_inst += len(pred_label.flat)
else:
Expand Down
2 changes: 1 addition & 1 deletion example/neural-style/end_to_end/data_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def PreprocessContentImage(path, short_edge, dshape=None):
new_size = (int(img.shape[0] * factor), int(img.shape[1] * factor))
resized_img = transform.resize(img, new_size)
sample = np.asarray(resized_img) * 256
if dshape != None:
if dshape is not None:
# random crop
xx = int((sample.shape[0] - dshape[2]))
yy = int((sample.shape[1] - dshape[3]))
Expand Down
6 changes: 3 additions & 3 deletions example/rcnn/rcnn/pycocotools/coco.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def __init__(self, annotation_file=None):
self.catToImgs = {}
self.imgs = {}
self.cats = {}
if not annotation_file == None:
if annotation_file is not None:
print 'loading annotations into memory...'
tic = time.time()
dataset = json.load(open(annotation_file, 'r'))
Expand Down Expand Up @@ -149,7 +149,7 @@ def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None):
anns = self.dataset['annotations']
anns = anns if len(catIds) == 0 else [ann for ann in anns if ann['category_id'] in catIds]
anns = anns if len(areaRng) == 0 else [ann for ann in anns if ann['area'] > areaRng[0] and ann['area'] < areaRng[1]]
if not iscrowd == None:
if iscrowd is not None:
ids = [ann['id'] for ann in anns if ann['iscrowd'] == iscrowd]
else:
ids = [ann['id'] for ann in anns]
Expand Down Expand Up @@ -325,7 +325,7 @@ def loadRes(self, resFile):
res.createIndex()
return res

def download( self, tarDir = None, imgIds = [] ):
def download(self, tarDir=None, imgIds=[]):
'''
Download COCO images from mscoco.org server.
:param tarDir (str): COCO results directory name
Expand Down
4 changes: 2 additions & 2 deletions example/rnn-time-major/bucket_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ def __init__(self, path, vocab, buckets, batch_size,
time_major=True):
super(BucketSentenceIter, self).__init__()

if text2id == None:
if text2id is None:
self.text2id = default_text2id
else:
self.text2id = text2id
if read_content == None:
if read_content is None:
self.read_content = default_read_content
else:
self.read_content = read_content
Expand Down
4 changes: 2 additions & 2 deletions example/rnn/old/bucket_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,11 @@ def __init__(self, path, vocab, buckets, batch_size,
seperate_char=' <eos> ', text2id=None, read_content=None, model_parallel=False):
super(BucketSentenceIter, self).__init__()

if text2id == None:
if text2id is None:
self.text2id = default_text2id
else:
self.text2id = text2id
if read_content == None:
if read_content is None:
self.read_content = default_read_content
else:
self.read_content = read_content
Expand Down
12 changes: 6 additions & 6 deletions example/speech-demo/io_func/feat_readers/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def GetMean(self):
return self.mean

def GetVariance(self):
return numpy.power(self.GetStd(),2)
return numpy.power(self.GetStd(), 2)

def GetStd(self):
return 1.0/self.invStd
Expand All @@ -64,7 +64,7 @@ def GetStatsFromList(self,fileList,featureFileHandler):
stats = None
for featureFile,label in featureList.FeatureList(fileList):
if stats == None:
if stats is None:
self.dim = self.getDimFromFile(featureFile,featureFileHandler)
stats = _StreamVariance(self.dim)
Expand Down Expand Up @@ -117,9 +117,9 @@ def Save(self,filename):
with open(filename,'wb') as f:
dt = numpy.dtype([('magicNumber',(numpy.int32,1)),('numSamples',(numpy.int32,1)),('dim',(numpy.int32,1))])
header=numpy.zeros((1,),dtype=dt)
header[0]['magicNumber']=21812
header[0]['numSamples']=self.populationSize
header[0]['dim']=self.mean.shape[0]
header[0]['magicNumber'] = 21812
header[0]['numSamples'] = self.populationSize
header[0]['dim'] = self.mean.shape[0]
header.tofile(f)

self.mean.astype(numpy.float32).tofile(f)
Expand All @@ -130,7 +130,7 @@ def Save(self,filename):
import argparse

parser = argparse.ArgumentParser(description='Print the mean and standard deviation from a stat file',formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('filename',help="Name of the stat file")
parser.add_argument('filename', help="Name of the stat file")
args = parser.parse_args()
featureStats = FeatureStats()
featureStats.Load(args.filename)
Expand Down
12 changes: 6 additions & 6 deletions example/speech-demo/io_func/feat_readers/writer_kaldi.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,21 @@ def __init__(self, scp_path, ark_path):
raise Exception("output file needs to be little endian")

def open(self):
self.out_ark = open(self.ark_path,"w")
self.out_scp = open(self.scp_path,"w")
self.out_ark = open(self.ark_path, "w")
self.out_scp = open(self.scp_path, "w")

def open_or_fd(self):
offset = None
if self.ark_path[0] == '|':
#self.out_ark = os.popen(sys.stdout, 'wb')
self.out_ark = sys.stdout
else:
self.out_ark = open(self.ark_path,"w")
self.out_ark = open(self.ark_path, "w")
def write(self, uttID, data):
assert data.dtype == numpy.float32

self.out_ark.write(uttID + ' ')
if self.out_scp != None:
if self.out_scp is not None:
start_offset = self.out_ark.tell()

# write out ark
Expand All @@ -47,11 +47,11 @@ def write(self, uttID, data):
self.out_ark.flush()

# write out scp
if self.out_scp != None:
if self.out_scp is not None:
scp_out = uttID + ' ' + self.ark_path + ':' + str(start_offset)
self.out_scp.write(scp_out + '\n')

def close(self):
self.out_ark.close()
if self.out_scp != None:
if self.out_scp is not None:
self.out_scp.close()
Loading

0 comments on commit d2fc1e6

Please sign in to comment.