예제 #1
0
    def test_summary(self):
        class ToString(object):
            def __init__(self):
                self.contents = ''

            def __call__(self, msg):
                self.contents += msg + '\n'

        # Single-io
        model = testing_utils.SmallSubclassMLP(num_hidden=32,
                                               num_classes=4,
                                               use_bn=True,
                                               use_dp=True)
        model(np.ones((3, 4)))  # need to build model first
        print_fn = ToString()
        model.summary(print_fn=print_fn)
        self.assertTrue('Trainable params: 356' in print_fn.contents)

        # Multi-io
        model = model_util.get_multi_io_subclass_model(num_classes=(5, 6),
                                                       use_bn=True,
                                                       use_dp=True)
        model([np.ones((3, 4)), np.ones((3, 4))])  # need to build model first
        print_fn = ToString()
        model.summary(print_fn=print_fn)
        self.assertTrue('Trainable params: 587' in print_fn.contents)
 def __init__(self, num_classes=2):
     super(NestedTestModel1, self).__init__(name='nested_model_1')
     self.num_classes = num_classes
     self.dense1 = keras.layers.Dense(32, activation='relu')
     self.dense2 = keras.layers.Dense(num_classes, activation='relu')
     self.bn = keras.layers.BatchNormalization()
     self.test_net = testing_utils.SmallSubclassMLP(num_hidden=32,
                                                    num_classes=4,
                                                    use_bn=True,
                                                    use_dp=True)
예제 #3
0
  def test_trainable_custom_model_false(self):
    """Tests that overall False trainable status of Model is preserved."""
    # Set all layers to *not* be trainable.
    model = testing_utils.SmallSubclassMLP(1, 4, trainable=False)
    model.compile(loss='mse', optimizer='rmsprop')
    self._train_model(model, use_dataset=False)
    loaded = self._save_and_load(model)

    self._test_evaluation(model, loaded)
    self.assertEmpty(model.trainable_variables)
    self.assertEmpty(loaded.trainable_variables)
예제 #4
0
  def test_invalid_input_shape_build(self):
    num_classes = 2
    input_dim = 50

    model = testing_utils.SmallSubclassMLP(
        num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True)

    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    with self.assertRaisesRegexp(
        ValueError, 'input shape is not one of the valid types'):
      model.build(input_shape=tensor_shape.Dimension(input_dim))
예제 #5
0
  def test_single_io_workflow_with_tensors(self):
    num_classes = 2
    num_samples = 10
    input_dim = 50

    with ops.Graph().as_default(), self.cached_session():
      model = testing_utils.SmallSubclassMLP(
          num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True)
      model.compile(loss='mse', optimizer='rmsprop')

      x = array_ops.ones((num_samples, input_dim))
      y = array_ops.zeros((num_samples, num_classes))

      model.fit(x, y, epochs=2, steps_per_epoch=10, verbose=0)
      _ = model.evaluate(steps=10, verbose=0)
예제 #6
0
  def test_single_io_dimension_subclass_build(self):
    num_classes = 2
    input_dim = tensor_shape.Dimension(50)
    batch_size = tensor_shape.Dimension(None)

    model = testing_utils.SmallSubclassMLP(
        num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True)

    self.assertFalse(model.built, 'Model should not have been built')
    self.assertFalse(model.weights, ('Model should have no weights since it '
                                     'has not been built.'))
    model.build(input_shape=(batch_size, input_dim))
    self.assertTrue(model.weights, ('Model should have weights now that it '
                                    'has been properly built.'))
    self.assertTrue(model.built, 'Model should be built after calling `build`.')
    model(array_ops.ones((32, input_dim)))
  def test_single_io_workflow_with_np_arrays(self):
    num_classes = 2
    num_samples = 100
    input_dim = 50

    model = testing_utils.SmallSubclassMLP(
        num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True)
    model.compile(
        loss='mse',
        optimizer='rmsprop',
        metrics=['acc', keras.metrics.CategoricalAccuracy()],
        run_eagerly=testing_utils.should_run_eagerly(),
        experimental_run_tf_function=testing_utils.should_run_tf_function())

    x = np.ones((num_samples, input_dim))
    y = np.zeros((num_samples, num_classes))

    model.fit(x, y, epochs=2, batch_size=32, verbose=0)
    _ = model.evaluate(x, y, verbose=0)
예제 #8
0
    def test_single_io_workflow_with_datasets(self):
        num_classes = 2
        num_samples = 10
        input_dim = 50

        with self.cached_session():
            model = testing_utils.SmallSubclassMLP(num_hidden=32,
                                                   num_classes=num_classes,
                                                   use_dp=True,
                                                   use_bn=True)
            model.compile(loss='mse',
                          optimizer='rmsprop',
                          run_eagerly=testing_utils.should_run_eagerly())

            x = np.ones((num_samples, input_dim), dtype=np.float32)
            y = np.zeros((num_samples, num_classes), dtype=np.float32)
            dataset = dataset_ops.Dataset.from_tensor_slices((x, y))
            dataset = dataset.repeat(100)
            dataset = dataset.batch(10)

            model.fit(dataset, epochs=2, steps_per_epoch=10, verbose=0)
            _ = model.evaluate(dataset, steps=10, verbose=0)