Skip to content
5 changes: 1 addition & 4 deletions example/tutorial_bipedalwalker_a3c_continuous_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,6 @@
"""

import multiprocessing
import os
import shutil
import threading

import gym
Expand Down Expand Up @@ -257,8 +255,7 @@ def work(self):
# start TF threading
worker_threads = []
for worker in workers:
job = lambda: worker.work()
t = threading.Thread(target=job)
t = threading.Thread(target=worker.work)
t.start()
worker_threads.append(t)
COORD.join(worker_threads)
Expand Down
2 changes: 1 addition & 1 deletion example/tutorial_cifar10_tfrecord.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
import io
import os
import time
import numpy as np
# import numpy as np
import tensorflow as tf
import tensorlayer as tl
from PIL import Image
Expand Down
9 changes: 4 additions & 5 deletions example/tutorial_imdb_fasttext.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
#!/usr/bin/env python
"""
This demo implements FastText[1] for sentence classification.

__doc__ = """

This demo implements FastText[1] for sentence classification. FastText is a
simple model for text classification with performance often close to
state-of-the-art, and is useful as a solid baseline.
FastText is a simple model for text classification with performance often close
to state-of-the-art, and is useful as a solid baseline.

There are some important differences between this implementation and what
is described in the paper. Instead of Hogwild! SGD[2], we use Adam optimizer
Expand Down
3 changes: 2 additions & 1 deletion example/tutorial_inceptionV3_tfslim.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ def load_image(path):
# load image
img = skimage.io.imread(path)
img = img / 255.0
assert (0 <= img).all() and (img <= 1.0).all()
if ((0 <= img).all() and (img <= 1.0).all()) is False:
raise Exception("image value should be [0, 1]")
# print "Original Image Shape: ", img.shape
# we crop image from center
short_edge = min(img.shape[:2])
Expand Down
1 change: 0 additions & 1 deletion example/tutorial_matrix.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import tensorflow as tf
import tensorlayer as tl

sess = tf.InteractiveSession()

Expand Down
1 change: 0 additions & 1 deletion example/tutorial_ptb_lstm.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@
import numpy as np
import tensorflow as tf
import tensorlayer as tl
from tensorlayer.layers import set_keep

flags = tf.flags
flags.DEFINE_string("model", "small", "A type of model. Possible options are: small, medium, large.")
Expand Down
2 changes: 1 addition & 1 deletion example/tutorial_vgg16.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def conv_layers(net_in):


def conv_layers_simple_api(net_in):
with tf.name_scope('preprocess') as scope:
with tf.name_scope('preprocess'):
"""
Notice that we include a preprocessing layer that takes the RGB image
with pixels values in the range of 0-255 and subtracts the mean image
Expand Down
18 changes: 13 additions & 5 deletions tensorlayer/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,16 @@ def __init__(self, ip='localhost', port=27017, db_name='db_name', user_name=None
self.db_name = db_name
self.user_name = user_name

@classmethod
def __autofill(self, args):
return args.update({'studyID': self.studyID})

def __serialization(self, ps):
@staticmethod
def __serialization(ps):
return pickle.dumps(ps, protocol=2)

def __deserialization(self, ps):
@staticmethod
def __deserialization(ps):
return pickle.loads(ps)

def save_params(self, params=None, args=None): #, file_name='parameters'):
Expand Down Expand Up @@ -298,20 +301,25 @@ def test_log(self, args=None):
return _result

@AutoFill
def del_test_log(self, args={}):
def del_test_log(self, args=None):
""" Delete test log.

Parameters
-----------
args : dictionary, find items to delete, leave it empty to delete all log.
"""
if args is None:
args = {}

self.db.TestLog.delete_many(args)
print("[TensorDB] Delete TestLog SUCCESS")

## =========================== Network Architecture ================== ##
# =========================== Network Architecture ================== ##
@AutoFill
def save_model_architecture(self, s, args={}):
def save_model_architecture(self, s, args=None):
if args is None:
args = {}

self.__autofill(args)
fid = self.archfs.put(s, filename="modelarchitecture")
args.update({"fid": fid})
Expand Down
18 changes: 17 additions & 1 deletion tensorlayer/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ def load_flickr25k_dataset(tag='sky', path="data", n_threads=50, printable=False
else:
logging.info("[Flickr25k] reading images with tag: {}".format(tag))
images_list = []
for idx in range(0, len(path_tags)):
for idx, _v in enumerate(path_tags):
tags = read_file(folder_tags + '/' + path_tags[idx]).split('\n')
# logging.info(idx+1, tags)
if tag is None or tag in tags:
Expand Down Expand Up @@ -1459,6 +1459,13 @@ def load_ckpt(sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list
def save_any_to_npy(save_dict={}, name='file.npy'):
"""Save variables to `.npy` file.

Parameters
------------
save_dict : directory
The variables to be saved.
name : str
File name.

Examples
---------
>>> tl.files.save_any_to_npy(save_dict={'data': ['a','b']}, name='test.npy')
Expand All @@ -1467,12 +1474,21 @@ def save_any_to_npy(save_dict={}, name='file.npy'):
... {'data': ['a','b']}

"""
if save_dict is None:
save_dict = {}
np.save(name, save_dict)


def load_npy_to_any(path='', name='file.npy'):
"""Load `.npy` file.

Parameters
------------
path : str
Path to the file (optional).
name : str
File name.

Examples
---------
- see tl.files.save_any_to_npy()
Expand Down
2 changes: 1 addition & 1 deletion tensorlayer/layers/convolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ def __init__(
logging.info("DeConv2dLayer %s: shape:%s out_shape:%s strides:%s pad:%s act:%s" % (self.name, str(shape), str(output_shape), str(strides), padding,
act.__name__))
# logging.info(" DeConv2dLayer: Untested")
with tf.variable_scope(name) as vs:
with tf.variable_scope(name):
W = tf.get_variable(name='W_deconv2d', shape=shape, initializer=W_init, dtype=D_TYPE, **W_init_args)
if b_init:
b = tf.get_variable(name='b_deconv2d', shape=(shape[-2]), initializer=b_init, dtype=D_TYPE, **b_init_args)
Expand Down
12 changes: 8 additions & 4 deletions tensorlayer/layers/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import tensorflow as tf

from .. import _logging as logging
from .. import cost, files, iterate, utils, visualize
from .. import files, iterate, utils, visualize

# __all__ = [
# "Layer",
Expand Down Expand Up @@ -289,11 +289,13 @@ def list_remove_repeat(x):

"""
y = []
[y.append(i) for i in x if not i in y]
for i in x:
if not i in y:
y.append(i)
return y


def merge_networks(layers=[]):
def merge_networks(layers=None):
"""Merge all parameters, layers and dropout probabilities to a :class:`Layer`.
The output of return network is the first network in the list.

Expand All @@ -314,6 +316,8 @@ def merge_networks(layers=[]):
>>> n1 = tl.layers.merge_networks([n1, n2])

"""
if layers is None:
raise Exception("layers should be a list of TensorLayer's Layers.")
layer = layers[0]

all_params = []
Expand Down Expand Up @@ -702,7 +706,7 @@ def __init__(
self.inputs = inputs
logging.info("EmbeddingInputlayer %s: (%d, %d)" % (self.name, vocabulary_size, embedding_size))

with tf.variable_scope(name) as vs:
with tf.variable_scope(name):
embeddings = tf.get_variable(name='embeddings', shape=(vocabulary_size, embedding_size), initializer=E_init, dtype=D_TYPE, **E_init_args)
embed = tf.nn.embedding_lookup(embeddings, self.inputs)

Expand Down
2 changes: 1 addition & 1 deletion tensorlayer/layers/extend.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def __init__(
self.inputs = layer.outputs

logging.info("TileLayer %s: multiples:%s" % (self.name, multiples))
with tf.variable_scope(name) as vs:
with tf.variable_scope(name):
self.outputs = tf.tile(self.inputs, multiples=multiples)
self.all_layers = list(layer.all_layers)
self.all_params = list(layer.all_params)
Expand Down
6 changes: 4 additions & 2 deletions tensorlayer/layers/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class LambdaLayer(Layer):
Previous layer.
fn : function
The function that applies to the outputs of previous layer.
fn_args : dictionary
fn_args : dictionary or None
The arguments for the function (option).
name : str
A unique layer name.
Expand Down Expand Up @@ -47,9 +47,11 @@ def __init__(
self,
layer,
fn,
fn_args={},
fn_args=None,
name='lambda_layer',
):
if fn_args is None:
fn_args = {}
Layer.__init__(self, name=name)
assert layer is not None
assert fn is not None
Expand Down
5 changes: 2 additions & 3 deletions tensorlayer/layers/merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ def __init__(

self.all_layers = list_remove_repeat(self.all_layers)
self.all_params = list_remove_repeat(self.all_params)
#self.all_drop = list_remove_repeat(self.all_drop) # it is a dict


class ElementwiseLayer(Layer):
Expand Down Expand Up @@ -112,8 +111,8 @@ def __init__(
self.outputs = layers[0].outputs
# logging.info(self.outputs._shape, type(self.outputs._shape))
for l in layers[1:]:
assert str(self.outputs.get_shape()) == str(
l.outputs.get_shape()), "Hint: the input shapes should be the same. %s != %s" % (self.outputs.get_shape(), str(l.outputs.get_shape()))
if str(self.outputs.get_shape()) != str(l.outputs.get_shape()):
raise Exception("Hint: the input shapes should be the same. %s != %s" % (self.outputs.get_shape(), str(l.outputs.get_shape())))
self.outputs = combine_fn(self.outputs, l.outputs, name=name)

self.all_layers = list(layers[0].all_layers)
Expand Down
Loading