code: def test_uncertainty():
      """Test estimating uncertainty a KerasModel."""
      n_samples = 30
      n_features = 1
      noise = 0.1
      X = np.random.rand(n_samples, n_features)
      y = 10 * X + np.random.normal(
          scale=noise, size=(n_samples, n_features)
      )
      dataset = dc.data.NumpyDataset(X, y)
  
      # Build a model that predicts uncertainty.
  
      inputs = tf.keras.Input(shape=(n_features,))
      switch = tf.keras.Input(shape=tuple())
      hidden = tf.keras.layers.Dense(200, activation="relu")(inputs)
      dropout = dc.models.layers.SwitchedDropout(rate=0.1)(
          [hidden, switch]
      )
      output = tf.keras.layers.Dense(n_features)(dropout)
      log_var = tf.keras.layers.Dense(n_features)(dropout)
      var = tf.keras.layers.Activation(tf.exp)(log_var)
      keras_model = tf.keras.Model(
          inputs=[inputs, switch],
          outputs=[output, var, output, log_var],
      )
  
      def loss(outputs, labels, weights):
          diff = labels[0] - outputs[0]
          log_var = outputs[1]
          var = tf.exp(log_var)
          return tf.reduce_mean(diff * diff / var + log_var)
  
      class UncertaintyModel(dc.models.KerasModel):
          def default_generator(
              self,
              dataset,
              epochs=1,
              mode="fit",
              deterministic=True,
              pad_batches=True,
          ):
              for epoch in range(epochs):
                  for X_b, y_b, w_b, ids_b in dataset.iterbatches(
                      batch_size=self.batch_size,
                      deterministic=deterministic,
                      pad_batches=pad_batches,
                  ):
                      if mode == "predict":
                          dropout = np.array(0.0)
                      else:
                          dropout = np.array(1.0)
                      yield ([X_b, dropout], [y_b], [w_b])
  
      model = UncertaintyModel(
          keras_model,
          loss,
          output_types=["prediction", "variance", "loss", "loss"],
          learning_rate=0.003,
      )
  
      # Fit the model and see if its predictions are correct.
  
      model.fit(dataset, nb_epoch=2500)
      pred, std = model.predict_uncertainty(dataset)
      assert np.mean(np.abs(y - pred)) < 1.0
      assert noise < np.mean(std) < 1.0
  
file_path: deepchem/deepchem/models/tests/test_kerasmodel.py
imports: import os
  import math
  import deepchem
  import numpy
  import unittest
  import pytest
label_desc: Use image node_id 7 for calling a global function with example usage: test_uncertainty() and returns: tf