Example #1
0
    def test_dnn(self):

        with tf.Graph().as_default():
            X = [3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1]
            Y = [1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3]
            input = zqtflearn.input_data(shape=[None])
            linear = zqtflearn.single_unit(input)
            regression = zqtflearn.regression(linear, optimizer='sgd', loss='mean_square',
                                              metric='R2', learning_rate=0.01)
            m = zqtflearn.DNN(regression)
            # Testing fit and predict
            m.fit(X, Y, n_epoch=1000, show_metric=True, snapshot_epoch=False)
            res = m.predict([3.2])[0]
            self.assertGreater(res, 1.3, "DNN test (linear regression) failed! with score: " + str(res) + " expected > 1.3")
            self.assertLess(res, 1.8, "DNN test (linear regression) failed! with score: " + str(res) + " expected < 1.8")

            # Testing save method
            m.save("test_dnn.zqtflearn")
            self.assertTrue(os.path.exists("test_dnn.zqtflearn.index"))

        with tf.Graph().as_default():
            input = zqtflearn.input_data(shape=[None])
            linear = zqtflearn.single_unit(input)
            regression = zqtflearn.regression(linear, optimizer='sgd', loss='mean_square',
                                              metric='R2', learning_rate=0.01)
            m = zqtflearn.DNN(regression)

            # Testing load method
            m.load("test_dnn.zqtflearn")
            res = m.predict([3.2])[0]
            self.assertGreater(res, 1.3, "DNN test (linear regression) failed after loading model! score: " + str(res) + " expected > 1.3")
            self.assertLess(res, 1.8, "DNN test (linear regression) failed after loading model! score: " + str(res) + " expected < 1.8")
Example #2
0
    def test_conv_layers(self):

        X = [[0., 0., 0., 0.], [1., 1., 1., 1.], [0., 0., 1., 0.], [1., 1., 1., 0.]]
        Y = [[1., 0.], [0., 1.], [1., 0.], [0., 1.]]

        with tf.Graph().as_default():
            g = zqtflearn.input_data(shape=[None, 4])
            g = zqtflearn.reshape(g, new_shape=[-1, 2, 2, 1])
            g = zqtflearn.conv_2d(g, 4, 2, activation='relu')
            g = zqtflearn.max_pool_2d(g, 2)
            g = zqtflearn.fully_connected(g, 2, activation='softmax')
            g = zqtflearn.regression(g, optimizer='sgd', learning_rate=1.)

            m = zqtflearn.DNN(g)
            m.fit(X, Y, n_epoch=100, snapshot_epoch=False)
            # TODO: Fix test
            #self.assertGreater(m.predict([[1., 0., 0., 0.]])[0][0], 0.5)

        # Bulk Tests
        with tf.Graph().as_default():
            g = zqtflearn.input_data(shape=[None, 4])
            g = zqtflearn.reshape(g, new_shape=[-1, 2, 2, 1])
            g = zqtflearn.conv_2d(g, 4, 2)
            g = zqtflearn.conv_2d(g, 4, 1)
            g = zqtflearn.conv_2d_transpose(g, 4, 2, [2, 2])
            g = zqtflearn.max_pool_2d(g, 2)
 def __init__(self):
     network = zqtflearn.input_data(shape=[None, 784], name="input")
     network = self.make_core_network(network)
     network = regression(network, optimizer='adam', learning_rate=0.01,
                          loss='categorical_crossentropy', name='target')
     
     model = zqtflearn.DNN(network, tensorboard_verbose=0)
     self.model = model
Example #4
0
    def test_vbs1(self):

        with tf.Graph().as_default():
            # Data loading and preprocessing
            import zqtflearn.datasets.mnist as mnist
            X, Y, testX, testY = mnist.load_data(one_hot=True)
            X = X.reshape([-1, 28, 28, 1])
            testX = testX.reshape([-1, 28, 28, 1])
            X = X[:20, :, :, :]
            Y = Y[:20, :]
            testX = testX[:10, :, :, :]
            testY = testY[:10, :]

            # Building convolutional network
            network = input_data(shape=[None, 28, 28, 1], name='input')
            network = conv_2d(network,
                              32,
                              3,
                              activation='relu',
                              regularizer="L2")
            network = max_pool_2d(network, 2)
            network = local_response_normalization(network)
            network = conv_2d(network,
                              64,
                              3,
                              activation='relu',
                              regularizer="L2")
            network = max_pool_2d(network, 2)
            network = local_response_normalization(network)
            network = fully_connected(network, 128, activation='tanh')
            network = dropout(network, 0.8)
            network = fully_connected(network, 256, activation='tanh')
            network = dropout(network, 0.8)
            network = fully_connected(network, 10, activation='softmax')
            network = regression(network,
                                 optimizer='adam',
                                 learning_rate=0.01,
                                 loss='categorical_crossentropy',
                                 name='target')

            # Training
            model = zqtflearn.DNN(network, tensorboard_verbose=3)
            model.fit({'input': X}, {'target': Y},
                      n_epoch=1,
                      batch_size=10,
                      validation_set=({
                          'input': testX
                      }, {
                          'target': testY
                      }),
                      validation_batch_size=5,
                      snapshot_step=10,
                      show_metric=True,
                      run_id='convnet_mnist_vbs')

            self.assertEqual(model.train_ops[0].validation_batch_size, 5)
            self.assertEqual(model.train_ops[0].batch_size, 10)
    def __init__(self):
        # Building deep neural network
        network = zqtflearn.input_data(shape=[None, 784], name="input")
        network = self.make_core_network(network)

        # Regression using SGD with learning rate decay and Top-3 accuracy
        sgd = zqtflearn.SGD(learning_rate=0.1, lr_decay=0.96, decay_step=1000)
        top_k = zqtflearn.metrics.Top_k(3)

        network = zqtflearn.regression(network, optimizer=sgd, metric=top_k,
                                       loss='categorical_crossentropy', name="target")
        model = zqtflearn.DNN(network, tensorboard_verbose=0)
        self.model = model
    def __init__(self):
        inputs = zqtflearn.input_data(shape=[None, 784], name="input")

        with tf.variable_scope("scope1") as scope:
            net_conv = Model1.make_core_network(inputs)	# shape (?, 10)
        with tf.variable_scope("scope2") as scope:
            net_dnn = Model2.make_core_network(inputs)	# shape (?, 10)

        network = tf.concat([net_conv, net_dnn], 1, name="concat")	# shape (?, 20)
        network = zqtflearn.fully_connected(network, 10, activation="softmax")
        network = regression(network, optimizer='adam', learning_rate=0.01,
                             loss='categorical_crossentropy', name='target')

        self.model = zqtflearn.DNN(network, tensorboard_verbose=0)
Example #7
0
    def test_recurrent_layers(self):

        X = [[1, 3, 5, 7], [2, 4, 8, 10], [1, 5, 9, 11], [2, 6, 8, 0]]
        Y = [[0., 1.], [1., 0.], [0., 1.], [1., 0.]]

        with tf.Graph().as_default():
            g = zqtflearn.input_data(shape=[None, 4])
            g = zqtflearn.embedding(g, input_dim=12, output_dim=4)
            g = zqtflearn.lstm(g, 6)
            g = zqtflearn.fully_connected(g, 2, activation='softmax')
            g = zqtflearn.regression(g, optimizer='sgd', learning_rate=1.)

            m = zqtflearn.DNN(g)
            m.fit(X, Y, n_epoch=300, snapshot_epoch=False)
            self.assertGreater(m.predict([[5, 9, 11, 1]])[0][1], 0.9)
Example #8
0
    def test_core_layers(self):

        X = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]]
        Y_nand = [[1.], [1.], [1.], [0.]]
        Y_or = [[0.], [1.], [1.], [1.]]

        # Graph definition
        with tf.Graph().as_default():
            # Building a network with 2 optimizers
            g = zqtflearn.input_data(shape=[None, 2])

            # Nand operator definition
            g_nand = zqtflearn.fully_connected(g, 32, activation='linear')
            g_nand = zqtflearn.fully_connected(g_nand, 32, activation='linear')
            g_nand = zqtflearn.fully_connected(g_nand, 1, activation='sigmoid')
            g_nand = zqtflearn.regression(g_nand, optimizer='sgd',
                                          learning_rate=2.,
                                          loss='binary_crossentropy')
            # Or operator definition
            g_or = zqtflearn.fully_connected(g, 32, activation='linear')
            g_or = zqtflearn.fully_connected(g_or, 32, activation='linear')
            g_or = zqtflearn.fully_connected(g_or, 1, activation='sigmoid')
            g_or = zqtflearn.regression(g_or, optimizer='sgd',
                                        learning_rate=2.,
                                        loss='binary_crossentropy')
            # XOR merging Nand and Or operators
            g_xor = zqtflearn.merge([g_nand, g_or], mode='elemwise_mul')

            # Training
            m = zqtflearn.DNN(g_xor)
            m.fit(X, [Y_nand, Y_or], n_epoch=400, snapshot_epoch=False)

            # Testing
            self.assertLess(m.predict([[0., 0.]])[0][0], 0.01)
            self.assertGreater(m.predict([[0., 1.]])[0][0], 0.9)
            self.assertGreater(m.predict([[1., 0.]])[0][0], 0.9)
            self.assertLess(m.predict([[1., 1.]])[0][0], 0.01)

        # Bulk Tests
        with tf.Graph().as_default():
            net = zqtflearn.input_data(shape=[None, 2])
            net = zqtflearn.flatten(net)
            net = zqtflearn.reshape(net, new_shape=[-1])
            net = zqtflearn.activation(net, 'relu')
            net = zqtflearn.dropout(net, 0.5)
            net = zqtflearn.single_unit(net)
Example #9
0
    def test_feed_dict_no_None(self):

        X = [[0., 0., 0., 0.], [1., 1., 1., 1.], [0., 0., 1., 0.], [1., 1., 1., 0.]]
        Y = [[1., 0.], [0., 1.], [1., 0.], [0., 1.]]

        with tf.Graph().as_default():
            g = zqtflearn.input_data(shape=[None, 4], name="X_in")
            g = zqtflearn.reshape(g, new_shape=[-1, 2, 2, 1])
            g = zqtflearn.conv_2d(g, 4, 2)
            g = zqtflearn.conv_2d(g, 4, 1)
            g = zqtflearn.max_pool_2d(g, 2)
            g = zqtflearn.fully_connected(g, 2, activation='softmax')
            g = zqtflearn.regression(g, optimizer='sgd', learning_rate=1.)

            m = zqtflearn.DNN(g)

            def do_fit():
                m.fit({"X_in": X, 'non_existent': X}, Y, n_epoch=30, snapshot_epoch=False)
            self.assertRaisesRegexp(Exception, "Feed dict asks for variable named 'non_existent' but no such variable is known to exist", do_fit)
 def build_simple_model(self):
     """Build a simple model for test
     Returns:
         DNN, [ (input layer name, input placeholder, input data) ], Target data
     """
     inputPlaceholder1, inputPlaceholder2 = \
         tf.placeholder(tf.float32, (1, 1), name = "input1"), tf.placeholder(tf.float32, (1, 1), name = "input2")
     input1 = zqtflearn.input_data(placeholder=inputPlaceholder1)
     input2 = zqtflearn.input_data(placeholder=inputPlaceholder2)
     network = zqtflearn.merge([input1, input2], "sum")
     network = zqtflearn.reshape(network, (1, 1))
     network = zqtflearn.fully_connected(network, 1)
     network = zqtflearn.regression(network)
     return (
         zqtflearn.DNN(network),
         [("input1:0", inputPlaceholder1, self.INPUT_DATA_1),
          ("input2:0", inputPlaceholder2, self.INPUT_DATA_2)],
         self.TARGET,
     )
Example #11
0
                                  trainable_vars=disc_vars,
                                  batch_size=64,
                                  name='target_disc',
                                  op_name='DISC')

gen_vars = zqtflearn.get_layer_variables_by_scope('Generator')
gan_model = zqtflearn.regression(stacked_gan_net,
                                 optimizer='adam',
                                 loss='categorical_crossentropy',
                                 trainable_vars=gen_vars,
                                 batch_size=64,
                                 name='target_gen',
                                 op_name='GEN')

# Define GAN model, that output the generated images.
gan = zqtflearn.DNN(gan_model)

# Training
# Prepare input data to feed to the discriminator
disc_noise = np.random.uniform(-1., 1., size=[total_samples, z_dim])
# Prepare target data to feed to the discriminator (0: fake image, 1: real image)
y_disc_fake = np.zeros(shape=[total_samples])
y_disc_real = np.ones(shape=[total_samples])
y_disc_fake = zqtflearn.data_utils.to_categorical(y_disc_fake, 2)
y_disc_real = zqtflearn.data_utils.to_categorical(y_disc_real, 2)

# Prepare input data to feed to the stacked generator/discriminator
gen_noise = np.random.uniform(-1., 1., size=[total_samples, z_dim])
# Prepare target data to feed to the discriminator
# Generator tries to fool the discriminator, thus target is 1 (e.g. real images)
y_gen = np.ones(shape=[total_samples])
Example #12
0
X_test = h5f['cifar10_X_test']
Y_test = h5f['cifar10_Y_test']

# Build network
network = input_data(shape=[None, 32, 32, 3], dtype=tf.float32)
network = conv_2d(network, 32, 3, activation='relu')
network = max_pool_2d(network, 2)
network = conv_2d(network, 64, 3, activation='relu')
network = conv_2d(network, 64, 3, activation='relu')
network = max_pool_2d(network, 2)
network = fully_connected(network, 512, activation='relu')
network = dropout(network, 0.5)
network = fully_connected(network, 10, activation='softmax')
network = regression(network,
                     optimizer='adam',
                     loss='categorical_crossentropy',
                     learning_rate=0.001)

# Training
model = zqtflearn.DNN(network, tensorboard_verbose=0)
model.fit(X,
          Y,
          n_epoch=50,
          shuffle=True,
          validation_set=(X_test, Y_test),
          show_metric=True,
          batch_size=96,
          run_id='cifar10_cnn')

h5f.close()
    def build_model(self, learning_rate=[0.001, 0.01]):
        '''
        Model - wide and deep - built using zqtflearn
        '''
        n_cc = len(self.continuous_columns)
        n_cc = 108

        input_shape = [None, n_cc]
        if self.verbose:
            print("=" * 77 + " Model %s (type=%s)" %
                  (self.name, self.model_type))
            print("  Input placeholder shape=%s" % str(input_shape))
        wide_inputs = zqtflearn.input_data(shape=input_shape, name="wide_X")
        deep_inputs = zqtflearn.input_data(shape=[None, 1], name="deep_X")
        if not isinstance(learning_rate, list):
            learning_rate = [learning_rate, learning_rate]  # wide, deep
        if self.verbose:
            print("  Learning rates (wide, deep)=%s" % learning_rate)

        with tf.name_scope(
                "Y"):  # placeholder for target variable (i.e. trainY input)
            Y_in = tf.placeholder(shape=[None, 1], dtype=tf.float32, name="Y")

        with tf.variable_op_scope([wide_inputs], None, "cb_unit",
                                  reuse=False) as scope:
            central_bias = zqtflearn.variables.variable(
                'central_bias',
                shape=[1],
                initializer=tf.constant_initializer(np.random.randn()),
                trainable=True,
                restore=True)
            tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/cb_unit',
                                 central_bias)

        if 'wide' in self.model_type:
            wide_network = self.wide_model(wide_inputs, n_cc)
            network = wide_network
            wide_network_with_bias = tf.add(wide_network,
                                            central_bias,
                                            name="wide_with_bias")

        if 'deep' in self.model_type:
            deep_network = self.deep_model(
                wide_inputs, deep_inputs, n_cc
            )  # 这里面是wide inputs,在这个函数内部wide_inputs,会和deep_model制造的输入相合并。
            deep_network_with_bias = tf.add(deep_network,
                                            central_bias,
                                            name="deep_with_bias")
            if 'wide' in self.model_type:
                network = tf.add(wide_network, deep_network)
                if self.verbose:
                    print("Wide + deep model network %s" % network)
            else:
                network = deep_network

        network = tf.add(network, central_bias, name="add_central_bias")

        # add validation monitor summaries giving confusion matrix entries
        with tf.name_scope('Monitors'):
            predictions = tf.cast(tf.greater(network, 0), tf.int64)
            print("predictions=%s" % predictions)
            Ybool = tf.cast(Y_in, tf.bool)
            print("Ybool=%s" % Ybool)
            pos = tf.boolean_mask(predictions, Ybool)
            neg = tf.boolean_mask(predictions, ~Ybool)
            psize = tf.cast(tf.shape(pos)[0], tf.int64)
            nsize = tf.cast(tf.shape(neg)[0], tf.int64)
            true_positive = tf.reduce_sum(pos, name="true_positive")
            false_negative = tf.subtract(psize,
                                         true_positive,
                                         name="false_negative")
            false_positive = tf.reduce_sum(neg, name="false_positive")
            true_negative = tf.subtract(nsize,
                                        false_positive,
                                        name="true_negative")
            overall_accuracy = tf.truediv(tf.add(true_positive, true_negative),
                                          tf.add(nsize, psize),
                                          name="overall_accuracy")
        vmset = [
            true_positive, true_negative, false_positive, false_negative,
            overall_accuracy
        ]

        trainable_vars = tf.trainable_variables()
        tv_deep = [v for v in trainable_vars if v.name.startswith('deep_')]
        tv_wide = [v for v in trainable_vars if v.name.startswith('wide_')]

        if self.verbose:
            print("DEEP trainable_vars")
            for v in tv_deep:
                print("  Variable %s: %s" % (v.name, v))
            print("WIDE trainable_vars")
            for v in tv_wide:
                print("  Variable %s: %s" % (v.name, v))

        # if 'wide' in self.model_type:
        #     if not 'deep' in self.model_type:
        #         tv_wide.append(central_bias)
        #     zqtflearn.regression(wide_network_with_bias,
        #                          placeholder=Y_in,
        #                          optimizer='sgd',
        #                          loss='roc_auc_score',
        #                          #loss='binary_crossentropy',
        #                          metric="accuracy",
        #                          learning_rate=learning_rate[0],
        #                          validation_monitors=vmset,
        #                          trainable_vars=tv_wide,
        #                          op_name="wide_regression",
        #                          name="Y")
        #
        # if 'deep' in self.model_type:
        #     if not 'wide' in self.model_type:
        #         tv_wide.append(central_bias)
        #     zqtflearn.regression(deep_network_with_bias,
        #                          placeholder=Y_in,
        #                          optimizer='adam',
        #                          loss='roc_auc_score',
        #                          #loss='binary_crossentropy',
        #                          metric="accuracy",
        #                          learning_rate=learning_rate[1],
        #                          validation_monitors=vmset if not 'wide' in self.model_type else None,
        #                          trainable_vars=tv_deep,
        #                          op_name="deep_regression",
        #                          name="Y")

        if self.model_type == 'wide+deep':  # learn central bias separately for wide+deep
            zqtflearn.regression(
                network,
                placeholder=Y_in,
                optimizer='adam',
                #loss="roc_auc_score",
                loss='binary_crossentropy',
                metric="accuracy",
                validation_monitors=vmset,
                learning_rate=learning_rate[0],  # use wide learning rate
                #trainable_vars=[central_bias], #[tv_deep,tv_wide,central_bias] # None
                op_name="central_bias_regression",
                name="Y")

        self.model = zqtflearn.DNN(
            network,
            tensorboard_verbose=self.tensorboard_verbose,
            max_checkpoints=self.max_checkpoints,
            checkpoint_path="%s/%s.tfl" % (self.checkpoints_dir, self.name),
            tensorboard_dir=self.tensorboard_dir)
        # tensorboard_dir="/tmp/tflearn_logs/" zqtflearn.DNN 我把他改为当前目录下的了,这样也比较好规范
        if 'deep' in self.model_type:
            embeddingWeights = zqtflearn.get_layer_variables_by_name(
                'deep_video_ids_embed')[0]
            # CUSTOM_WEIGHT = pickle.load("Haven't deal")
            # emb = np.array(CUSTOM_WEIGHT, dtype=np.float32)
            # emb = self.embedding
            new_emb_t = tf.convert_to_tensor(self.embedding)
            self.model.set_weights(embeddingWeights, new_emb_t)

        if self.verbose:
            print("Target variables:")
            for v in tf.get_collection(tf.GraphKeys.TARGETS):
                print("  variable %s: %s" % (v.name, v))

            print("=" * 77)

        print("model build finish")
    def build_model(self, learning_rate=[0.001, 0.01]):
        '''
        Model - wide and deep - built using zqtflearn
        '''
        n_cc = len(self.continuous_columns)
        n_categories = 1			# two categories: is_idv and is_not_idv
        input_shape = [None, n_cc]
        if self.verbose:
            print ("="*77 + " Model %s (type=%s)" % (self.name, self.model_type))
            print ("  Input placeholder shape=%s" % str(input_shape))
        wide_inputs = zqtflearn.input_data(shape=input_shape, name="wide_X")
        if not isinstance(learning_rate, list):
            learning_rate = [learning_rate, learning_rate]	# wide, deep
        if self.verbose:
            print ("  Learning rates (wide, deep)=%s" % learning_rate)

        with tf.name_scope("Y"):			# placeholder for target variable (i.e. trainY input)
            Y_in = tf.placeholder(shape=[None, 1], dtype=tf.float32, name="Y")

        with tf.variable_scope(None, "cb_unit", [wide_inputs]) as scope:
            central_bias = zqtflearn.variables.variable('central_bias', shape=[1],
                                                        initializer=tf.constant_initializer(np.random.randn()),
                                                        trainable=True, restore=True)
            tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/cb_unit', central_bias)

        if 'wide' in self.model_type:
            wide_network = self.wide_model(wide_inputs, n_cc)
            network = wide_network
            wide_network_with_bias = tf.add(wide_network, central_bias, name="wide_with_bias")

        if 'deep' in self.model_type:
            deep_network = self.deep_model(wide_inputs, n_cc)
            deep_network_with_bias = tf.add(deep_network, central_bias, name="deep_with_bias")
            if 'wide' in self.model_type:
                network = tf.add(wide_network, deep_network)
                if self.verbose:
                    print ("Wide + deep model network %s" % network)
            else:
                network = deep_network

        network = tf.add(network, central_bias, name="add_central_bias")

        # add validation monitor summaries giving confusion matrix entries
        with tf.name_scope('Monitors'):
            predictions = tf.cast(tf.greater(network, 0), tf.int64)
            print ("predictions=%s" % predictions)
            Ybool = tf.cast(Y_in, tf.bool)
            print ("Ybool=%s" % Ybool)
            pos = tf.boolean_mask(predictions, Ybool)
            neg = tf.boolean_mask(predictions, ~Ybool)
            psize = tf.cast(tf.shape(pos)[0], tf.int64)
            nsize = tf.cast(tf.shape(neg)[0], tf.int64)
            true_positive = tf.reduce_sum(pos, name="true_positive")
            false_negative = tf.subtract(psize, true_positive, name="false_negative")
            false_positive = tf.reduce_sum(neg, name="false_positive")
            true_negative = tf.subtract(nsize, false_positive, name="true_negative")
            overall_accuracy = tf.truediv(tf.add(true_positive, true_negative), tf.add(nsize, psize), name="overall_accuracy")
        vmset = [true_positive, true_negative, false_positive, false_negative, overall_accuracy]

        trainable_vars = tf.trainable_variables()
        tv_deep = [v for v in trainable_vars if v.name.startswith('deep_')]
        tv_wide = [v for v in trainable_vars if v.name.startswith('wide_')]

        if self.verbose:
            print ("DEEP trainable_vars")
            for v in tv_deep:
                print ("  Variable %s: %s" % (v.name, v))
            print ("WIDE trainable_vars")
            for v in tv_wide:
                print ("  Variable %s: %s" % (v.name, v))

        if 'wide' in self.model_type:
            if not 'deep' in self.model_type:
                tv_wide.append(central_bias)
            zqtflearn.regression(wide_network_with_bias,
                                 placeholder=Y_in,
                                 optimizer='sgd',
                                 #loss='roc_auc_score',
                                 loss='binary_crossentropy',
                                 metric="accuracy",
                                 learning_rate=learning_rate[0],
                                 validation_monitors=vmset,
                                 trainable_vars=tv_wide,
                                 op_name="wide_regression",
                                 name="Y")

        if 'deep' in self.model_type:
            if not 'wide' in self.model_type:
                tv_wide.append(central_bias)
            zqtflearn.regression(deep_network_with_bias,
                                 placeholder=Y_in,
                                 optimizer='adam',
                                 #loss='roc_auc_score',
                                 loss='binary_crossentropy',
                                 metric="accuracy",
                                 learning_rate=learning_rate[1],
                                 validation_monitors=vmset if not 'wide' in self.model_type else None,
                                 trainable_vars=tv_deep,
                                 op_name="deep_regression",
                                 name="Y")

        if self.model_type=='wide+deep':	# learn central bias separately for wide+deep
            zqtflearn.regression(network,
                                 placeholder=Y_in,
                                 optimizer='adam',
                                 loss='binary_crossentropy',
                                 metric="accuracy",
                                 learning_rate=learning_rate[0],  # use wide learning rate
                                 trainable_vars=[central_bias],
                                 op_name="central_bias_regression",
                                 name="Y")

        self.model = zqtflearn.DNN(network,
                                   tensorboard_verbose=self.tensorboard_verbose,
                                   max_checkpoints=5,
                                   checkpoint_path="%s/%s.tfl" % (self.checkpoints_dir, self.name),
                                   )

        if self.verbose:
            print ("Target variables:")
            for v in tf.get_collection(tf.GraphKeys.TARGETS):
                print ("  variable %s: %s" % (v.name, v))

            print ("="*77)
                         + (1 - x_true) * tf.log(1e-10 + 1 - x_reconstructed)
    encode_decode_loss = -tf.reduce_sum(encode_decode_loss, 1)
    # KL Divergence loss
    kl_div_loss = 1 + z_std - tf.square(z_mean) - tf.exp(z_std)
    kl_div_loss = -0.5 * tf.reduce_sum(kl_div_loss, 1)
    return tf.reduce_mean(encode_decode_loss + kl_div_loss)

net = zqtflearn.regression(decoder, optimizer='rmsprop', learning_rate=0.001,
                           loss=vae_loss, metric=None, name='target_images')

# We will need 2 models, one for training that will learn the latent
# representation, and one that can take random normal noise as input and
# use the decoder part of the network to generate an image

# Train the VAE
training_model = zqtflearn.DNN(net, tensorboard_verbose=0)
training_model.fit({'input_images': X}, {'target_images': X}, n_epoch=100,
                   validation_set=(testX, testX), batch_size=256, run_id="vae")

# Build an image generator (re-using the decoding layers)
# Input data is a normal (gaussian) random distribution (with dim = latent_dim)
input_noise = zqtflearn.input_data(shape=[None, latent_dim], name='input_noise')
decoder = zqtflearn.fully_connected(input_noise, hidden_dim, activation='relu',
                                    scope='decoder_h', reuse=True)
decoder = zqtflearn.fully_connected(decoder, original_dim, activation='sigmoid',
                                    scope='decoder_out', reuse=True)
generator_model = zqtflearn.DNN(decoder, session=training_model.session)

# Building a manifold of generated digits
n = 25 # Figure row size
figure = np.zeros((28 * n, 28 * n))
Example #16
0
                       activation='relu',
                       name='block5_conv2')
block5_conv3 = conv_2d(block5_conv2,
                       512,
                       3,
                       activation='relu',
                       name='block5_conv3')
block5_conv4 = conv_2d(block5_conv3,
                       512,
                       3,
                       activation='relu',
                       name='block5_conv4')
block4_pool = max_pool_2d(block5_conv4, 2, strides=2, name='block4_pool')
flatten_layer = zqtflearn.layers.core.flatten(block4_pool, name='Flatten')

fc1 = fully_connected(flatten_layer, 4096, activation='relu')
dp1 = dropout(fc1, 0.5)
fc2 = fully_connected(dp1, 4096, activation='relu')
dp2 = dropout(fc2, 0.5)

network = fully_connected(dp2, 1000, activation='rmsprop')

regression = zqtflearn.regression(network,
                                  optimizer='adam',
                                  loss='categorical_crossentropy',
                                  learning_rate=0.001)

model = zqtflearn.DNN(regression,
                      checkpoint_path='vgg19',
                      tensorboard_dir="./logs")
    def test_dnn_loading_scope(self):

        with tf.Graph().as_default():
            X = [
                3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779, 6.182, 7.59, 2.167,
                7.042, 10.791, 5.313, 7.997, 5.654, 9.27, 3.1
            ]
            Y = [
                1.7, 2.76, 2.09, 3.19, 1.694, 1.573, 3.366, 2.596, 2.53, 1.221,
                2.827, 3.465, 1.65, 2.904, 2.42, 2.94, 1.3
            ]
            input = zqtflearn.input_data(shape=[None])
            linear = zqtflearn.single_unit(input)
            regression = zqtflearn.regression(linear,
                                              optimizer='sgd',
                                              loss='mean_square',
                                              metric='R2',
                                              learning_rate=0.01)
            m = zqtflearn.DNN(regression)
            # Testing fit and predict
            m.fit(X, Y, n_epoch=1000, show_metric=True, snapshot_epoch=False)
            res = m.predict([3.2])[0]
            self.assertGreater(
                res, 1.3, "DNN test (linear regression) failed! with score: " +
                str(res) + " expected > 1.3")
            self.assertLess(
                res, 1.8, "DNN test (linear regression) failed! with score: " +
                str(res) + " expected < 1.8")

            # Testing save method
            m.save("test_dnn.zqtflearn")
            self.assertTrue(os.path.exists("test_dnn.zqtflearn.index"))

        # Testing loading, with change of variable scope (saved with no scope, now loading into scopeA)
        with tf.Graph().as_default():  # start with clear graph
            with tf.variable_scope("scopeA") as scope:
                input = zqtflearn.input_data(shape=[None])
                linear = zqtflearn.single_unit(input)
                regression = zqtflearn.regression(linear,
                                                  optimizer='sgd',
                                                  loss='mean_square',
                                                  metric='R2',
                                                  learning_rate=0.01)
                m = zqtflearn.DNN(regression)

                def try_load():
                    m.load("test_dnn.zqtflearn")

                self.assertRaises(
                    tf.errors.NotFoundError,
                    try_load)  # fails, since names in file don't have "scopeA"

                m.load("test_dnn.zqtflearn", variable_name_map=(
                    "scopeA/",
                    ""))  # succeeds, because variable names are rewritten
                res = m.predict([3.2])[0]
                self.assertGreater(
                    res, 1.3,
                    "DNN test (linear regression) failed after loading model! score: "
                    + str(res) + " expected > 1.3")
                self.assertLess(
                    res, 1.8,
                    "DNN test (linear regression) failed after loading model! score: "
                    + str(res) + " expected < 1.8")
Example #18
0
# Building Residual Network
net = zqtflearn.input_data(shape=[None, 28, 28, 1])
net = zqtflearn.conv_2d(net, 64, 3, activation='relu', bias=False)
# Residual blocks
net = zqtflearn.residual_bottleneck(net, 3, 16, 64)
net = zqtflearn.residual_bottleneck(net, 1, 32, 128, downsample=True)
net = zqtflearn.residual_bottleneck(net, 2, 32, 128)
net = zqtflearn.residual_bottleneck(net, 1, 64, 256, downsample=True)
net = zqtflearn.residual_bottleneck(net, 2, 64, 256)
net = zqtflearn.batch_normalization(net)
net = zqtflearn.activation(net, 'relu')
net = zqtflearn.global_avg_pool(net)
# Regression
net = zqtflearn.fully_connected(net, 10, activation='softmax')
net = zqtflearn.regression(net,
                           optimizer='momentum',
                           loss='categorical_crossentropy',
                           learning_rate=0.1)
# Training
model = zqtflearn.DNN(net,
                      checkpoint_path='model_resnet_mnist',
                      max_checkpoints=10,
                      tensorboard_verbose=0)
model.fit(X,
          Y,
          n_epoch=100,
          validation_set=(testX, testY),
          show_metric=True,
          batch_size=256,
          run_id='resnet_mnist')
#                        categorical_labels=True, normalize=True,
#                        files_extension=['.jpg', '.png'], filter_channel=True)

num_classes = 10 # num of your dataset

# VGG preprocessing
img_prep = ImagePreprocessing()
img_prep.add_featurewise_zero_center(mean=[123.68, 116.779, 103.939],
                                     per_channel=True)
# VGG Network
x = zqtflearn.input_data(shape=[None, 224, 224, 3], name='input',
                         data_preprocessing=img_prep)
softmax = vgg16(x, num_classes)
regression = zqtflearn.regression(softmax, optimizer='adam',
                                  loss='categorical_crossentropy',
                                  learning_rate=0.001, restore=False)

model = zqtflearn.DNN(regression, checkpoint_path='vgg-finetuning',
                      max_checkpoints=3, tensorboard_verbose=2,
                      tensorboard_dir="./logs")

model_file = os.path.join(model_path, "vgg16.zqtflearn")
model.load(model_file, weights_only=True)

# Start finetuning
model.fit(X, Y, n_epoch=10, validation_set=0.1, shuffle=True,
          show_metric=True, batch_size=64, snapshot_epoch=False,
          snapshot_step=200, run_id='vgg-finetuning')

model.save('your-task-model-retrained-by-vgg')
encoder = zqtflearn.fully_connected(encoder, 256)
encoder = zqtflearn.fully_connected(encoder, 64)

# Building the decoder
decoder = zqtflearn.fully_connected(encoder, 256)
decoder = zqtflearn.fully_connected(decoder, 784, activation='sigmoid')

# Regression, with mean square error
net = zqtflearn.regression(decoder,
                           optimizer='adam',
                           learning_rate=0.001,
                           loss='mean_square',
                           metric=None)

# Training the auto encoder
model = zqtflearn.DNN(net, tensorboard_verbose=0)
model.fit(X,
          X,
          n_epoch=20,
          validation_set=(testX, testX),
          run_id="auto_encoder",
          batch_size=256)

# Encoding X[0] for test
print("\nTest encoding of X[0]:")
# New model, re-using the same session, for weights sharing
encoding_model = zqtflearn.DNN(encoder, session=model.session)
print(encoding_model.predict([X[0]]))

# Testing the image reconstruction on new data (test set)
print("\nVisualizing results after being encoded and decoded:")
                activation=None,
                name='Conv2d_7b_1x1')))
net = avg_pool_2d(net,
                  net.get_shape().as_list()[1:3],
                  strides=2,
                  padding='VALID',
                  name='AvgPool_1a_8x8')
net = flatten(net)
net = dropout(net, dropout_keep_prob)
loss = fully_connected(net, num_classes, activation='softmax')

network = zqtflearn.regression(loss,
                               optimizer='RMSprop',
                               loss='categorical_crossentropy',
                               learning_rate=0.0001)
model = zqtflearn.DNN(network,
                      checkpoint_path='inception_resnet_v2',
                      max_checkpoints=1,
                      tensorboard_verbose=2,
                      tensorboard_dir="./tflearn_logs/")
model.fit(X,
          Y,
          n_epoch=1000,
          validation_set=0.1,
          shuffle=True,
          show_metric=True,
          batch_size=32,
          snapshot_step=2000,
          snapshot_epoch=False,
          run_id='inception_resnet_v2_17flowers')
Example #22
0
network = conv_2d(network, 512, 3, activation='relu')
network = conv_2d(network, 512, 3, activation='relu')
network = conv_2d(network, 512, 3, activation='relu')
network = max_pool_2d(network, 2, strides=2)

network = fully_connected(network, 4096, activation='relu')
network = dropout(network, 0.5)
network = fully_connected(network, 4096, activation='relu')
network = dropout(network, 0.5)
network = fully_connected(network, 17, activation='softmax')

network = regression(network,
                     optimizer='rmsprop',
                     loss='categorical_crossentropy',
                     learning_rate=0.0001)

# Training
model = zqtflearn.DNN(network,
                      checkpoint_path='model_vgg',
                      max_checkpoints=1,
                      tensorboard_verbose=0)
model.fit(X,
          Y,
          n_epoch=500,
          shuffle=True,
          show_metric=True,
          batch_size=32,
          snapshot_step=500,
          snapshot_epoch=False,
          run_id='vgg_oxflowers17')
Example #23
0
# MNIST Data
X, Y, testX, testY = mnist.load_data(one_hot=True)

# Model
input_layer = zqtflearn.input_data(shape=[None, 784], name='input')
dense1 = zqtflearn.fully_connected(input_layer, 128, name='dense1')
dense2 = zqtflearn.fully_connected(dense1, 256, name='dense2')
softmax = zqtflearn.fully_connected(dense2, 10, activation='softmax')
regression = zqtflearn.regression(softmax,
                                  optimizer='adam',
                                  learning_rate=0.001,
                                  loss='categorical_crossentropy')

# Define classifier, with model checkpoint (autosave)
model = zqtflearn.DNN(regression, checkpoint_path='model.tfl.ckpt')

# Train model, with model checkpoint every epoch and every 200 training steps.
model.fit(
    X,
    Y,
    n_epoch=1,
    validation_set=(testX, testY),
    show_metric=True,
    snapshot_epoch=True,  # Snapshot (save & evaluate) model every epoch.
    snapshot_step=500,  # Snapshot (save & evalaute) model every 500 steps.
    run_id='model_and_weights')

# ---------------------
# Save and load a model
# ---------------------
Example #24
0
        passengers[i][1] = 1. if passengers[i][1] == 'female' else 0.
    return np.array(passengers, dtype=np.float32)

# Ignore 'name' and 'ticket' columns (id 1 & 6 of data array)
to_ignore=[1, 6]

# Preprocess data
data = preprocess(data, to_ignore)

# Build neural network
net = zqtflearn.input_data(shape=[None, 6])
net = zqtflearn.fully_connected(net, 32)
net = zqtflearn.fully_connected(net, 32)
net = zqtflearn.fully_connected(net, 2, activation='softmax')
net = zqtflearn.regression(net)

# Define model
model = zqtflearn.DNN(net)
# Start training (apply gradient descent algorithm)
model.fit(data, labels, n_epoch=10, batch_size=16, show_metric=True)

# Let's create some data for DiCaprio and Winslet
dicaprio = [3, 'Jack Dawson', 'male', 19, 0, 0, 'N/A', 5.0000]
winslet = [1, 'Rose DeWitt Bukater', 'female', 17, 1, 2, 'N/A', 100.0000]
# Preprocess data
dicaprio, winslet = preprocess([dicaprio, winslet], to_ignore)
# Predict surviving chances (class 1 results)
pred = model.predict([dicaprio, winslet])
print("DiCaprio Surviving Rate:", pred[0][1])
print("Winslet Surviving Rate:", pred[1][1])
Example #25
0
    def build_model(self, learning_rate=[0.001, 0.01]):
        '''
        Model - wide and deep - built using tflearn
        '''
        n_cc = len(self.continuous_columns)
        n_cc = 108

        input_shape = [None, n_cc]
        if self.verbose:
            print("=" * 77 + " Model %s (type=%s)" %
                  (self.name, self.model_type))
            print("  Input placeholder shape=%s" % str(input_shape))
        wide_inputs = zqtflearn.input_data(shape=input_shape, name="wide_X")
        if not isinstance(learning_rate, list):
            learning_rate = [learning_rate, learning_rate]  # wide, deep
        if self.verbose:
            print("  Learning rates (wide, deep)=%s" % learning_rate)

        with tf.name_scope(
                "Y"):  # placeholder for target variable (i.e. trainY input)
            Y_in = tf.placeholder(shape=[None, 1], dtype=tf.float32, name="Y")

        with tf.variable_op_scope([wide_inputs], None, "cb_unit",
                                  reuse=False) as scope:
            central_bias = zqtflearn.variables.variable(
                'central_bias',
                shape=[1],
                initializer=tf.constant_initializer(np.random.randn()),
                trainable=True,
                restore=True)
            tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/cb_unit',
                                 central_bias)

        wide_network = self.wide_model(wide_inputs, n_cc)
        network = wide_network
        network = tf.add(network, central_bias, name="add_central_bias")

        # add validation monitor summaries giving confusion matrix entries
        with tf.name_scope('Monitors'):
            predictions = tf.cast(tf.greater(network, 0), tf.int64)
            print("predictions=%s" % predictions)
            Ybool = tf.cast(Y_in, tf.bool)
            print("Ybool=%s" % Ybool)
            pos = tf.boolean_mask(predictions, Ybool)
            neg = tf.boolean_mask(predictions, ~Ybool)
            psize = tf.cast(tf.shape(pos)[0], tf.int64)
            nsize = tf.cast(tf.shape(neg)[0], tf.int64)
            true_positive = tf.reduce_sum(pos, name="true_positive")
            false_negative = tf.subtract(psize,
                                         true_positive,
                                         name="false_negative")
            false_positive = tf.reduce_sum(neg, name="false_positive")
            true_negative = tf.subtract(nsize,
                                        false_positive,
                                        name="true_negative")
            overall_accuracy = tf.truediv(tf.add(true_positive, true_negative),
                                          tf.add(nsize, psize),
                                          name="overall_accuracy")
        vmset = [
            true_positive, true_negative, false_positive, false_negative,
            overall_accuracy
        ]

        zqtflearn.regression(
            network,
            placeholder=Y_in,
            optimizer='adam',
            #loss="roc_auc_score",
            loss='binary_crossentropy',
            metric="accuracy",
            learning_rate=learning_rate[0],  # use wide learning rate
            # trainable_vars=[central_bias],
            validation_monitors=vmset,
            op_name="central_bias_regression",
            name="Y")

        self.model = zqtflearn.DNN(
            network,
            tensorboard_verbose=self.tensorboard_verbose,
            max_checkpoints=self.max_checkpoints,
            checkpoint_path="%s/%s.tfl" % (self.checkpoints_dir, self.name),
            tensorboard_dir=self.tensorboard_dir)

        if self.verbose:
            print("Target variables:")
            for v in tf.get_collection(tf.GraphKeys.TARGETS):
                print("  variable %s: %s" % (v.name, v))

            print("=" * 77)
import zqtflearn

# Regression data
X = [
    3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779, 6.182, 7.59, 2.167, 7.042, 10.791,
    5.313, 7.997, 5.654, 9.27, 3.1
]
Y = [
    1.7, 2.76, 2.09, 3.19, 1.694, 1.573, 3.366, 2.596, 2.53, 1.221, 2.827,
    3.465, 1.65, 2.904, 2.42, 2.94, 1.3
]

# Linear Regression graph
input_ = zqtflearn.input_data(shape=[None])
linear = zqtflearn.single_unit(input_)
regression = zqtflearn.regression(linear,
                                  optimizer='sgd',
                                  loss='mean_square',
                                  metric='R2',
                                  learning_rate=0.01)
m = zqtflearn.DNN(regression)
m.fit(X, Y, n_epoch=1000, show_metric=True, snapshot_epoch=False)

print("\nRegression result:")
print("Y = " + str(m.get_weights(linear.W)) + "*X + " +
      str(m.get_weights(linear.b)))

print("\nTest prediction for x = 3.2, 3.3, 3.4:")
print(m.predict([3.2, 3.3, 3.4]))
# should output (close, not exact) y = [1.5315033197402954, 1.5585315227508545, 1.5855598449707031]
"""

from __future__ import absolute_import, division, print_function

import zqtflearn
import numpy as np

# Regression data- 10 training instances
#10 input features per instance.
X=np.random.rand(10,10).tolist()
#2 output features per instance
Y=np.random.rand(10,2).tolist()

# Multiple Regression graph, 10-d input layer
input_ = zqtflearn.input_data(shape=[None, 10])
#10-d fully connected layer
r1 = zqtflearn.fully_connected(input_, 10)
#2-d fully connected layer for output
r1 = zqtflearn.fully_connected(r1, 2)
r1 = zqtflearn.regression(r1, optimizer='sgd', loss='mean_square',
                          metric='R2', learning_rate=0.01)

m = zqtflearn.DNN(r1)
m.fit(X,Y, n_epoch=100, show_metric=True, snapshot_epoch=False)

#Predict for 1 instance
testinstance=np.random.rand(1,10).tolist()
print("\nInput features:  ",testinstance)
print("\n Predicted output: ")
print(m.predict(testinstance))
Example #28
0
X = [[0.], [1.]]
Y = [[1.], [0.]]

# Graph definition
with tf.Graph().as_default():
    g = zqtflearn.input_data(shape=[None, 1])
    g = zqtflearn.fully_connected(g, 128, activation='linear')
    g = zqtflearn.fully_connected(g, 128, activation='linear')
    g = zqtflearn.fully_connected(g, 1, activation='sigmoid')
    g = zqtflearn.regression(g,
                             optimizer='sgd',
                             learning_rate=2.,
                             loss='mean_square')

    # Model training
    m = zqtflearn.DNN(g)
    m.fit(X, Y, n_epoch=100, snapshot_epoch=False)

    # Test model
    print("Testing NOT operator")
    print("NOT 0:", m.predict([[0.]]))
    print("NOT 1:", m.predict([[1.]]))

# Logical OR operator
X = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]]
Y = [[0.], [1.], [1.], [1.]]

# Graph definition
with tf.Graph().as_default():
    g = zqtflearn.input_data(shape=[None, 2])
    g = zqtflearn.fully_connected(g, 128, activation='linear')
Example #29
0
    def test_vm1(self):

        with tf.Graph().as_default():
            # Data loading and preprocessing
            import zqtflearn.datasets.mnist as mnist
            X, Y, testX, testY = mnist.load_data(one_hot=True)
            X = X.reshape([-1, 28, 28, 1])
            testX = testX.reshape([-1, 28, 28, 1])
            X = X[:10, :, :, :]
            Y = Y[:10, :]

            # Building convolutional network
            network = input_data(shape=[None, 28, 28, 1], name='input')
            network = conv_2d(network,
                              32,
                              3,
                              activation='relu',
                              regularizer="L2")
            network = max_pool_2d(network, 2)
            network = local_response_normalization(network)
            network = conv_2d(network,
                              64,
                              3,
                              activation='relu',
                              regularizer="L2")
            network = max_pool_2d(network, 2)
            network = local_response_normalization(network)
            network = fully_connected(network, 128, activation='tanh')
            network = dropout(network, 0.8)
            network = fully_connected(network, 256, activation='tanh')
            network = dropout(network, 0.8)

            # construct two varaibles to add as additional "valiation monitors"
            # these varaibles are evaluated each time validation happens (eg at a snapshot)
            # and the results are summarized and output to the tensorboard events file,
            # together with the accuracy and loss plots.
            #
            # Here, we generate a dummy variable given by the sum over the current
            # network tensor, and a constant variable.  In practice, the validation
            # monitor may present useful information, like confusion matrix
            # entries, or an AUC metric.
            with tf.name_scope('CustomMonitor'):
                test_var = tf.reduce_sum(tf.cast(network, tf.float32),
                                         name="test_var")
                test_const = tf.constant(32.0, name="custom_constant")

            print("network=%s, test_var=%s" % (network, test_var))
            network = fully_connected(network, 10, activation='softmax')
            network = regression(network,
                                 optimizer='adam',
                                 learning_rate=0.01,
                                 loss='categorical_crossentropy',
                                 name='target',
                                 validation_monitors=[test_var, test_const])

            # Training
            model = zqtflearn.DNN(network, tensorboard_verbose=3)
            model.fit({'input': X}, {'target': Y},
                      n_epoch=1,
                      validation_set=({
                          'input': testX
                      }, {
                          'target': testY
                      }),
                      snapshot_step=10,
                      show_metric=True,
                      run_id='convnet_mnist')

            # check for validation monitor variables
            ats = tf.get_collection("Adam_testing_summaries")
            print("ats=%s" % ats)
            self.assertTrue(
                len(ats) == 4
            )  # should be four variables being summarized: [loss, test_var, test_const, accuracy]

            session = model.session
            print("session=%s" % session)
            trainer = model.trainer
            print("train_ops = %s" % trainer.train_ops)
            top = trainer.train_ops[0]
            vmtset = top.validation_monitors_T
            print("validation_monitors_T = %s" % vmtset)
            with model.session.as_default():
                ats_var_val = zqtflearn.variables.get_value(vmtset[0])
                ats_const_val = zqtflearn.variables.get_value(vmtset[1])
            print("summary values: var=%s, const=%s" %
                  (ats_var_val, ats_const_val))
            self.assertTrue(
                ats_const_val ==
                32)  # test to make sure the constant made it through
from zqtflearn.layers.embedding_ops import embedding
from zqtflearn.layers.recurrent import bidirectional_rnn, BasicLSTMCell
from zqtflearn.layers.estimator import regression

# IMDB Dataset loading
train, test, _ = imdb.load_data(path='imdb.pkl',
                                n_words=10000,
                                valid_portion=0.1)
trainX, trainY = train
testX, testY = test

# Data preprocessing
# Sequence padding
trainX = pad_sequences(trainX, maxlen=200, value=0.)
testX = pad_sequences(testX, maxlen=200, value=0.)
# Converting labels to binary vectors
trainY = to_categorical(trainY)
testY = to_categorical(testY)

# Network building
net = input_data(shape=[None, 200])
net = embedding(net, input_dim=20000, output_dim=128)
net = bidirectional_rnn(net, BasicLSTMCell(128), BasicLSTMCell(128))
net = dropout(net, 0.5)
net = fully_connected(net, 2, activation='softmax')
net = regression(net, optimizer='adam', loss='categorical_crossentropy')

# Training
model = zqtflearn.DNN(net, clip_gradients=0., tensorboard_verbose=2)
model.fit(trainX, trainY, validation_set=0.1, show_metric=True, batch_size=64)