本文整理汇总了Python中tqdm.trange函数的典型用法代码示例。如果您正苦于以下问题:Python trange函数的具体用法?Python trange怎么用?Python trange使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了trange函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main():
"""Main program."""
answer = 0
start = time.time()
max_period = 0
for index in tqdm.trange(1, 1000):
period = calculate_period_length(index)
if period > max_period:
max_period = period
answer = index
end = time.time()
print("The answer is %d" % answer)
print("%f seconds elapsed" % (end - start))
start = time.time()
max_period = 0
for index in tqdm.trange(1, 1000):
period = lambda_decimal_period(index)
if period > max_period:
max_period = period
answer = index
end = time.time()
print("The answer is %d" % answer)
print("%f seconds elapsed" % (end - start))
import pyperclip
pyperclip.copy(str(answer))
print("The answer has been placed in the clipboard.")
示例2: trees_are_random
def trees_are_random(filename):
res_file = filename.replace('_0', '_processed')
with np.load(filename) as f:
res, gold = f['res'], f['gold']
num_trees, num_order, _ = res.shape
all_trees = list(range(num_trees))
all_order = list(range(num_order))
all_pred = np.arange(len(gold))
nrep = 100
rate = np.zeros((num_trees//2+1, [j//13-1 for j in range(13, num_order, 13)][-1]+1, 2))
frac = 1.3
dropped = []
for i in trange(1, num_trees+1, 2):
for j in trange(13, num_order, 13):
tmp_res = []
for k in range(nrep):
trees = random.sample(all_trees, i)
orders = random.sample(all_order, j-1 if j % 2 == 0 else j)
if i == 1:
vals = res[trees, orders, :]
else:
vals = res[np.ix_(trees, orders, all_pred)].sum(0)
tmp_res.append(mistakes(vals))
thre = frac*np.median(tmp_res)
good = tmp_res < thre
bad = np.logical_not(good)
dropped.append((i, j, bad.sum()/nrep))
rate[(i-1)//2, j//13-1, :] = np.mean(tmp_res), np.std(tmp_res)
np.savez_compressed(res_file, rate=rate)
示例3: download
def download(left, right, top, bottom, zoom, filename, maptype="default"):
for x in trange(left, right + 1):
for y in trange(top, bottom + 1):
path = './tiles/%s/%i/%i/%i.png' % (filename, zoom, x, y)
if not os.path.exists(path):
_download(x, y, zoom,filename,maptype)
示例4: main
def main():
bar = trange(60*25)
bar.write("Working time...")
for t in bar:
time.sleep(1)
bar = trange(60*5)
bar.write("Break time...")
for t in bar:
time.sleep(1)
示例5: process_tilenum
def process_tilenum(left, right, top, bottom, zoom, output='output/mosaic.png'):
"""
download and mosaic by tile number
"""
for x in trange(left, right + 1):
for y in trange(top, bottom + 1):
path = './tiles/%i/%i/%i.png' % (zoom, x, y)
if not os.path.exists(path):
_download(x, y, zoom)
_mosaic(left, right, top, bottom, zoom, output)
示例6: test_trange
def test_trange():
""" Test trange """
with closing(StringIO()) as our_file:
for _ in trange(3, file=our_file, leave=True):
pass
our_file.seek(0)
assert '| 3/3 ' in our_file.read()
with closing(StringIO()) as our_file2:
for _ in trange(3, file=our_file2, leave=False):
pass
our_file2.seek(0)
assert '| 3/3 ' not in our_file2.read()
示例7: ensemble
def ensemble(validation_base_path, validation_folder, validation_predicted_folder):
pkl_files = []
weights = []
#weight_file = './file_weight_128.csv'
#weight_file = './file_weight_128_144models.csv'
#weight_file = './file_weight_128_144_updated models.csv'
#weight_file = './file_weight_128_144_3rd version models.csv'
weight_file = './10 best models weights for task 1.csv'
#weight_file = './5 best models weights for task 1.csv'
#weight_file = './20 best models weights for task 1.csv'
with open(weight_file, 'rb') as f:
rows = csv.reader(f, delimiter=',')
#next(rows, None)
for row in rows:
if '.pkl' in row[0]:
pkl_files.append(validation_base_path + row[0])
else:
pkl_files.append(validation_base_path + row[0] + '.pkl')
weights.append(float(row[1]))
print (len(pkl_files))
print weights
print np.sum(weights)
mask_pred_challenge_list = []
for i in trange(len(pkl_files)):
mask_pred_challenge = pkl.load(open(pkl_files[i], 'rb'))
mask_pred_challenge_list.append(mask_pred_challenge)
mask_pred_challenge_list = np.array(mask_pred_challenge_list)
print mask_pred_challenge_list.shape
weights = np.array(weights)
mask_pred_challenge = np.dot(mask_pred_challenge_list.transpose(1,2,3,0), weights)
print mask_pred_challenge.shape
if not os.path.exists(validation_predicted_folder):
os.makedirs(validation_predicted_folder)
cutoff = 0.5
mask_pred_challenge_b = (np.where(mask_pred_challenge>=cutoff, 1, 0) * 255).astype(np.uint8)
challenge_list = ISIC.list_from_folder(validation_folder)
for i in trange(len(challenge_list)):
_, _ = ISIC.show_images_full_sized(challenge_list,
img_mask_pred_array=mask_pred_challenge_b,
image_folder=validation_folder,
mask_folder=None,
index=i,
output_folder=validation_predicted_folder,
plot=False)
示例8: test_trange
def test_trange():
our_file = StringIO()
for i in trange(3, file=our_file, leave=True):
pass
our_file.seek(0)
assert '| 3/3 ' in our_file.read()
our_file.close()
our_file2 = StringIO()
for i in trange(3, file=our_file2, leave=False):
pass
our_file2.seek(0)
assert '| 3/3 ' not in our_file2.read()
our_file2.close()
示例9: _mosaic
def _mosaic(left, right, top, bottom, zoom, output='output/mosaic.png'):
size_x = (right - left + 1) * 256
size_y = (bottom - top + 1) * 256
output_im = Image.new("RGBA", (size_x, size_y))
for x in trange(left, right + 1):
for y in trange(top, bottom + 1):
path = './tiles/%i/%i/%i.png' % (zoom, x, y)
target_im = Image.open(path)
output_im.paste(target_im, (256 * (x - left), 256 * (y - top)))
output_path = os.path.split(output)
if len(output_path) > 1 and len(output_path) != 0:
if not os.path.isdir(output_path[0]):
os.makedirs(output_path[0])
output_im.save(output)
示例10: test_iter_overhead_simplebar_hard
def test_iter_overhead_simplebar_hard():
"""Test overhead of iteration based tqdm vs simple progress bar (hard)"""
total = int(1e4)
with closing(MockIO()) as our_file:
a = 0
with trange(total, file=our_file, leave=True, miniters=1,
mininterval=0, maxinterval=0) as t:
with relative_timer() as time_tqdm:
for i in t:
a += i
assert a == (total * total - total) / 2.0
a = 0
s = simple_progress(_range(total), file=our_file, leave=True,
miniters=1, mininterval=0)
with relative_timer() as time_bench:
for i in s:
a += i
# Compute relative overhead of tqdm against native range()
try:
assert time_tqdm() < 2.5 * time_bench()
except AssertionError:
raise AssertionError('trange(%g): %f, simple_progress(%g): %f' %
(total, time_tqdm(), total, time_bench()))
示例11: test_iter_overhead_hard
def test_iter_overhead_hard():
"""Test overhead of iteration based tqdm (hard)"""
total = int(1e5)
with closing(MockIO()) as our_file:
a = 0
with trange(total, file=our_file, leave=True, miniters=1,
mininterval=0, maxinterval=0) as t:
with relative_timer() as time_tqdm:
for i in t:
a += i
assert a == (total * total - total) / 2.0
a = 0
with relative_timer() as time_bench:
for i in _range(total):
a += i
our_file.write(("%i" % a) * 40)
# Compute relative overhead of tqdm against native range()
try:
assert time_tqdm() < 60 * time_bench()
except AssertionError:
raise AssertionError('trange(%g): %f, range(%g): %f' %
(total, time_tqdm(), total, time_bench()))
示例12: _maybe_generate_and_save
def _maybe_generate_and_save(self, except_list=[]):
self.data = {}
for name, num in self.data_num.items():
if name in except_list:
tf.logging.info("Skip creating {} because of given except_list {}".format(name, except_list))
continue
path = self.get_path(name)
if not os.path.exists(path):
tf.logging.info("Creating {} for [{}]".format(path, self.task))
x = np.zeros([num, self.max_length, 2], dtype=np.float32)
y = np.zeros([num, self.max_length], dtype=np.int32)
for idx in trange(num, desc="Create {} data".format(name)):
n_nodes = self.rng.randint(self.min_length, self.max_length+ 1)
nodes, res = generate_one_example(n_nodes, self.rng)
x[idx,:len(nodes)] = nodes
y[idx,:len(res)] = res
np.savez(path, x=x, y=y)
self.data[name] = TSP(x=x, y=y, name=name)
else:
tf.logging.info("Skip creating {} for [{}]".format(path, self.task))
tmp = np.load(path)
self.data[name] = TSP(x=tmp['x'], y=tmp['y'], name=name)
示例13: __init__
def __init__(self, cache=None, **kwargs):
super(GTZAN, self).__init__(**kwargs)
if kwargs.get('conf') is not None:
conf = kwargs['conf']
cache = conf.get('cache', None)
data_set_path = osp.join(DEFAULT_IMAGEST_BASE, self.data_set)
self.data_set_path = data_set_path
self.cache = cache
X, y = parse_anno_file(data_set_path)
if cache == 'raw':
import librosa
from tqdm import trange
X_new = np.zeros((len(X), 1, 661500, 1))
for i in trange(len(X)):
x,_ = librosa.load(osp.join(DEFAULT_DATA_BASE, X[i]))
x_len = min(661500, len(x))
X_new[i,:,:x_len,0] = x[:x_len]
if cache is not None and cache != 'raw':
X = self.load_cache_X(X, cache)
if cache == 'mfcc':
X_new = np.zeros((len(X), X[0].shape[0], 1280, 1))
for i, x in enumerate(X):
x_len = min(x.shape[1], 1280)
X_new[i,:,:x_len,0] = x[:,:x_len]
X = X_new
# layout_X
if self.layout_x == 'rel_path':
self.X = X
else:
self.X = self.init_layout_X(X)
# layout_y
self.y = self.init_layout_y(y)
示例14: main
def main():
"""Main program."""
answer = 0
start_time = time.time()
# Find next sequence after 1487, 4817, 8147
for number_1 in tqdm.trange(1488, 9998):
for index in range(1, (9999 - number_1) / 2):
number_2 = number_1 + index
number_3 = number_1 + (2 * index)
if all([sorted(str(n)) == sorted(str(number_1)) \
for n in [number_2, number_3]]) \
and all([sympy.ntheory.primetest.isprime(n) \
for n in [number_1, number_2, number_3]]):
answer = int(str(number_1) + str(number_2) + str(number_3))
break
if answer > 0:
break
end_time = time.time()
print("The answer is %d" % answer)
print("%f seconds elapsed." % (end_time - start_time))
import pyperclip
pyperclip.copy(str(answer))
print("The answer has been placed in the clipboard.")
示例15: adev_at_tau_wrapper
def adev_at_tau_wrapper(idxs):
if idxs[0] == 0:
for i in trange(len(idxs)):
adev_at_tau(idxs[i])
else:
for i in idxs:
adev_at_tau(i)