Skip to content

Commit 44e5ba6

Browse files
authored
Merge pull request #351 from tensorlayer/codacy2
fix pylint issues.
2 parents cb33980 + e5629ca commit 44e5ba6

26 files changed

+527
-425
lines changed

example/tutorial_bipedalwalker_a3c_continuous_action.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ def work(self):
210210
self.AC.v_target: buffer_v_target,
211211
}
212212
# update gradients on global network
213-
test = self.AC.update_global(feed_dict)
213+
self.AC.update_global(feed_dict)
214214
buffer_s, buffer_a, buffer_r = [], [], []
215215

216216
# update local network from global network

example/tutorial_cifar10_tfrecord.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ def read_and_decode(filename, is_train=None):
121121
# 5. Subtract off the mean and divide by the variance of the pixels.
122122
try: # TF 0.12+
123123
img = tf.image.per_image_standardization(img)
124-
except: # earlier TF versions
124+
except Exception: # earlier TF versions
125125
img = tf.image.per_image_whitening(img)
126126

127127
elif is_train == False:
@@ -130,7 +130,7 @@ def read_and_decode(filename, is_train=None):
130130
# 2. Subtract off the mean and divide by the variance of the pixels.
131131
try: # TF 0.12+
132132
img = tf.image.per_image_standardization(img)
133-
except: # earlier TF versions
133+
except Exception: # earlier TF versions
134134
img = tf.image.per_image_whitening(img)
135135
elif is_train == None:
136136
img = img

example/tutorial_imagenet_inceptionV3_distributed.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -288,12 +288,12 @@ def calculate_metrics(predicted_batch, real_batch, threshold=0.5, is_training=Fa
288288
def run_evaluator(task_spec, checkpoints_path, batch_size=32):
289289
with tf.Graph().as_default():
290290
# load dataset
291-
images_input, one_hot_classes, num_classes, dataset_size = \
291+
images_input, one_hot_classes, num_classes, _dataset_size = \
292292
load_data(file=VAL_FILE,
293293
task_spec=task_spec,
294294
batch_size=batch_size,
295295
epochs=1)
296-
network, predictions = build_network(images_input, num_classes=num_classes, is_training=False)
296+
_network, predictions = build_network(images_input, num_classes=num_classes, is_training=False)
297297
saver = tf.train.Saver()
298298
# metrics
299299
metrics_init_ops, _, metrics_ops = \

example/tutorial_inceptionV3_tfslim.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def print_prob(prob):
123123
exit()
124124
try: # TF12+
125125
saver.restore(sess, "./inception_v3.ckpt")
126-
except: # TF11
126+
except Exception: # TF11
127127
saver.restore(sess, "inception_v3.ckpt")
128128
print("Model Restored")
129129

example/tutorial_vgg16.py

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,6 @@
3737
"""
3838

3939
import os
40-
import sys
41-
import time
42-
import numpy as np
43-
import tensorflow as tf
4440
import tensorlayer as tl
4541
from scipy.misc import imread, imresize
4642
from tensorlayer.layers import *
@@ -52,15 +48,16 @@
5248

5349

5450
def conv_layers(net_in):
55-
with tf.name_scope('preprocess') as scope:
51+
with tf.name_scope('preprocess'):
5652
"""
5753
Notice that we include a preprocessing layer that takes the RGB image
5854
with pixels values in the range of 0-255 and subtracts the mean image
5955
values (calculated over the entire ImageNet training set).
6056
"""
6157
mean = tf.constant([123.68, 116.779, 103.939], dtype=tf.float32, shape=[1, 1, 1, 3], name='img_mean')
6258
net_in.outputs = net_in.outputs - mean
63-
""" conv1 """
59+
60+
# conv1
6461
network = Conv2dLayer(
6562
net_in,
6663
act=tf.nn.relu,
@@ -76,7 +73,8 @@ def conv_layers(net_in):
7673
padding='SAME',
7774
name='conv1_2')
7875
network = PoolLayer(network, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', pool=tf.nn.max_pool, name='pool1')
79-
""" conv2 """
76+
77+
# conv2
8078
network = Conv2dLayer(
8179
network,
8280
act=tf.nn.relu,
@@ -92,7 +90,8 @@ def conv_layers(net_in):
9290
padding='SAME',
9391
name='conv2_2')
9492
network = PoolLayer(network, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', pool=tf.nn.max_pool, name='pool2')
95-
""" conv3 """
93+
94+
# conv3
9695
network = Conv2dLayer(
9796
network,
9897
act=tf.nn.relu,
@@ -115,7 +114,8 @@ def conv_layers(net_in):
115114
padding='SAME',
116115
name='conv3_3')
117116
network = PoolLayer(network, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', pool=tf.nn.max_pool, name='pool3')
118-
""" conv4 """
117+
118+
# conv4
119119
network = Conv2dLayer(
120120
network,
121121
act=tf.nn.relu,
@@ -138,7 +138,8 @@ def conv_layers(net_in):
138138
padding='SAME',
139139
name='conv4_3')
140140
network = PoolLayer(network, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', pool=tf.nn.max_pool, name='pool4')
141-
""" conv5 """
141+
142+
# conv5
142143
network = Conv2dLayer(
143144
network,
144145
act=tf.nn.relu,
@@ -173,25 +174,30 @@ def conv_layers_simple_api(net_in):
173174
"""
174175
mean = tf.constant([123.68, 116.779, 103.939], dtype=tf.float32, shape=[1, 1, 1, 3], name='img_mean')
175176
net_in.outputs = net_in.outputs - mean
176-
""" conv1 """
177+
178+
# conv1
177179
network = Conv2d(net_in, n_filter=64, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu, padding='SAME', name='conv1_1')
178180
network = Conv2d(network, n_filter=64, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu, padding='SAME', name='conv1_2')
179181
network = MaxPool2d(network, filter_size=(2, 2), strides=(2, 2), padding='SAME', name='pool1')
180-
""" conv2 """
182+
183+
# conv2
181184
network = Conv2d(network, n_filter=128, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu, padding='SAME', name='conv2_1')
182185
network = Conv2d(network, n_filter=128, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu, padding='SAME', name='conv2_2')
183186
network = MaxPool2d(network, filter_size=(2, 2), strides=(2, 2), padding='SAME', name='pool2')
184-
""" conv3 """
187+
188+
# conv3
185189
network = Conv2d(network, n_filter=256, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu, padding='SAME', name='conv3_1')
186190
network = Conv2d(network, n_filter=256, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu, padding='SAME', name='conv3_2')
187191
network = Conv2d(network, n_filter=256, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu, padding='SAME', name='conv3_3')
188192
network = MaxPool2d(network, filter_size=(2, 2), strides=(2, 2), padding='SAME', name='pool3')
189-
""" conv4 """
193+
194+
# conv4
190195
network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu, padding='SAME', name='conv4_1')
191196
network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu, padding='SAME', name='conv4_2')
192197
network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu, padding='SAME', name='conv4_3')
193198
network = MaxPool2d(network, filter_size=(2, 2), strides=(2, 2), padding='SAME', name='pool4')
194-
""" conv5 """
199+
200+
# conv5
195201
network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu, padding='SAME', name='conv5_1')
196202
network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu, padding='SAME', name='conv5_2')
197203
network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu, padding='SAME', name='conv5_3')
@@ -249,5 +255,3 @@ def fc_layers(net):
249255
preds = (np.argsort(prob)[::-1])[0:5]
250256
for p in preds:
251257
print(class_names[p], prob[p])
252-
253-
#

example/tutorial_word2vec_basic.py

Lines changed: 21 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,6 @@
3737
3838
"""
3939

40-
import collections
41-
import math
42-
import os
43-
import random
4440
import time
4541

4642
import numpy as np
@@ -56,10 +52,9 @@
5652
def main_word2vec_basic():
5753
# sess = tf.InteractiveSession()
5854
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
59-
""" Step 1: Download the data, read the context into a list of strings.
60-
Set hyperparameters.
61-
"""
6255

56+
# Step 1: Download the data, read the context into a list of strings.
57+
# Set hyperparameters.
6358
words = tl.files.load_matt_mahoney_text8_dataset()
6459
data_size = len(words)
6560
print(data_size) # 17005207
@@ -126,8 +121,8 @@ def main_word2vec_basic():
126121
print('%d Steps in a Epoch, total Epochs %d' % (int(data_size / batch_size), n_epoch))
127122
print(' learning_rate: %f' % learning_rate)
128123
print(' batch_size: %d' % batch_size)
129-
""" Step 2: Build the dictionary and replace rare words with 'UNK' token.
130-
"""
124+
125+
# Step 2: Build the dictionary and replace rare words with 'UNK' token.
131126
print()
132127
if resume:
133128
print("Load existing data and dictionaries" + "!" * 10)
@@ -146,21 +141,21 @@ def main_word2vec_basic():
146141
]) # [5243, 3081, 12, 6, 195, 2, 3135, 46, 59, 156] [b'anarchism', b'originated', b'as', b'a', b'term', b'of', b'abuse', b'first', b'used', b'against']
147142

148143
del words # Hint to reduce memory.
149-
""" Step 3: Function to generate a training batch for the Skip-Gram model.
150-
"""
144+
145+
# Step 3: Function to generate a training batch for the Skip-Gram model.
151146
print()
152-
data_index = 0
147+
153148
batch, labels, data_index = tl.nlp.generate_skip_gram_batch(data=data, batch_size=8, num_skips=4, skip_window=2, data_index=0)
154149
for i in range(8):
155150
print(batch[i], reverse_dictionary[batch[i]], '->', labels[i, 0], reverse_dictionary[labels[i, 0]])
156151

157152
batch, labels, data_index = tl.nlp.generate_skip_gram_batch(data=data, batch_size=8, num_skips=2, skip_window=1, data_index=0)
158153
for i in range(8):
159154
print(batch[i], reverse_dictionary[batch[i]], '->', labels[i, 0], reverse_dictionary[labels[i, 0]])
160-
# exit()
161-
""" Step 4: Build a Skip-Gram model.
162-
"""
155+
156+
# Step 4: Build a Skip-Gram model.
163157
print()
158+
164159
# We pick a random validation set to sample nearest neighbors. Here we limit the
165160
# validation samples to the words that have a low numeric ID, which by
166161
# construction are also the most frequent.
@@ -208,9 +203,10 @@ def main_word2vec_basic():
208203
similarity = tf.matmul(valid_embed, normalized_embeddings, transpose_b=True)
209204
# multiply all valid word vector with all word vector.
210205
# transpose_b=True, normalized_embeddings is transposed before multiplication.
211-
""" Step 5: Start training.
212-
"""
206+
207+
# Step 5: Start training.
213208
print()
209+
214210
tl.layers.initialize_global_variables(sess)
215211
if resume:
216212
print("Load existing model" + "!" * 10)
@@ -229,7 +225,7 @@ def main_word2vec_basic():
229225
average_loss = 0
230226
step = 0
231227
print_freq = 2000
232-
while (step < num_steps):
228+
while step < num_steps:
233229
start_time = time.time()
234230
batch_inputs, batch_labels, data_index = tl.nlp.generate_skip_gram_batch(
235231
data=data, batch_size=batch_size, num_skips=num_skips, skip_window=skip_window, data_index=data_index)
@@ -279,16 +275,17 @@ def main_word2vec_basic():
279275
# learning_rate = float(input("Input new learning rate: "))
280276
# train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
281277
step += 1
282-
""" Step 6: Visualize the normalized embedding matrix by t-SNE.
283-
"""
278+
279+
# Step 6: Visualize the normalized embedding matrix by t-SNE.
284280
print()
281+
285282
final_embeddings = sess.run(normalized_embeddings) #.eval()
286283
tl.visualize.tsne_embedding(final_embeddings, reverse_dictionary, plot_only=500, second=5, saveable=False, name='word2vec_basic')
287-
""" Step 7: Evaluate by analogy questions.
288-
see tensorflow/models/embedding/word2vec_optimized.py
289-
"""
284+
285+
# Step 7: Evaluate by analogy questions. see tensorflow/models/embedding/word2vec_optimized.py
290286
print()
291-
# from tensorflow/models/embedding/word2vec.py
287+
288+
# from tensorflow/models/embedding/word2vec.py
292289
analogy_questions = tl.nlp.read_analogies_file( \
293290
eval_file='questions-words.txt', word2id=dictionary)
294291
# The eval feeds three vectors of word ids for a, b, c, each of
@@ -352,5 +349,3 @@ def predict(analogy):
352349

353350
if __name__ == '__main__':
354351
main_word2vec_basic()
355-
356-
#

tensorlayer/_logging.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,7 @@
55

66
def info(fmt, *args):
77
logging.info(fmt, *args)
8+
9+
10+
def warning(fmt, *args):
11+
logging.warning(fmt, *args)

tensorlayer/cli/train.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,25 @@
77
(Alpha release - usage might change later)
88
99
The tensorlayer.cli.train module provides the ``tl train`` subcommand.
10-
It helps the user bootstrap a TensorFlow/TensorLayer program for distributed training
10+
It helps the user bootstrap a TensorFlow/TensorLayer program for distributed training
1111
using multiple GPU cards or CPUs on a computer.
1212
13-
You need to first setup the `CUDA_VISIBLE_DEVICES <http://acceleware.com/blog/cudavisibledevices-masking-gpus>`_
13+
You need to first setup the `CUDA_VISIBLE_DEVICES <http://acceleware.com/blog/cudavisibledevices-masking-gpus>`_
1414
to tell ``tl train`` which GPUs are available. If the CUDA_VISIBLE_DEVICES is not given,
15-
``tl train`` would try best to discover all available GPUs.
15+
``tl train`` would try best to discover all available GPUs.
1616
1717
In distribute training, each TensorFlow program needs a TF_CONFIG environment variable to describe
18-
the cluster. It also needs a master daemon to
18+
the cluster. It also needs a master daemon to
1919
monitor all trainers. ``tl train`` is responsible
20-
for automatically managing these two tasks.
20+
for automatically managing these two tasks.
2121
2222
Usage
2323
-----
2424
2525
tl train [-h] [-p NUM_PSS] [-c CPU_TRAINERS] <file> [args [args ...]]
2626
2727
.. code-block:: bash
28-
28+
2929
# example of using GPU 0 and 1 for training mnist
3030
CUDA_VISIBLE_DEVICES="0,1"
3131
tl train example/tutorial_mnist_distributed.py
@@ -56,13 +56,13 @@
5656
-----
5757
A parallel training program would require multiple parameter servers
5858
to help parallel trainers to exchange intermediate gradients.
59-
The best number of parameter servers is often proportional to the
59+
The best number of parameter servers is often proportional to the
6060
size of your model as well as the number of CPUs available.
6161
You can control the number of parameter servers using the ``-p`` parameter.
6262
6363
If you have a single computer with massive CPUs, you can use the ``-c`` parameter
6464
to enable CPU-only parallel training.
65-
The reason we are not supporting GPU-CPU co-training is because GPU and
65+
The reason we are not supporting GPU-CPU co-training is because GPU and
6666
CPU are running at different speeds. Using them together in training would
6767
incur stragglers.
6868

0 commit comments

Comments
 (0)