├── models ├── __init__.py ├── mlp_tf.py └── cd.py ├── run_training.sh ├── preprocessing.py ├── run_tests.sh ├── .gitignore ├── data_gen.py ├── requirements.txt ├── README.md ├── test_network.py ├── train_network.py └── LICENSE /models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /run_training.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | SCRIPT=train_network.py 4 | TIME=$(date +%s) 5 | LOGFILE=${TIME}.log 6 | 7 | for MODEL_TYPE in cd bnn de 8 | do 9 | for T_MAX in 0.05 0.1 0.2 10 | do 11 | if [ ${MODEL_TYPE} == de ] 12 | then 13 | N_EPOCHS=40 14 | else 15 | N_EPOCHS=200 16 | fi 17 | ARGS="--model-type ${MODEL_TYPE} --t-spread-max ${T_MAX} --n-epochs ${N_EPOCHS}" 18 | time python ${SCRIPT} ${ARGS} >> ${LOGFILE} 19 | done 20 | done 21 | -------------------------------------------------------------------------------- /preprocessing.py: -------------------------------------------------------------------------------- 1 | from sklearn.preprocessing import MinMaxScaler 2 | 3 | 4 | def scale(train_set, val_set, test_set=None, min_val=0, max_val=1, gap=0): 5 | scaler = MinMaxScaler((min_val+gap, max_val-gap)) 6 | 7 | if train_set.ndim == 1: 8 | train_set = train_set.reshape(-1, 1) 9 | val_set = val_set.reshape(-1, 1) 10 | if test_set is not None: 11 | test_set = test_set.reshape(-1, 1) 12 | 13 | scaler.fit(train_set) 14 | train_set = scaler.transform(train_set) 15 | val_set = scaler.transform(val_set) 16 | if test_set is not None: 17 | test_set = scaler.transform(test_set) 18 | return scaler, train_set, val_set, test_set 19 | return scaler, train_set, val_set 20 | -------------------------------------------------------------------------------- /run_tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | SCRIPT=test_network.py 4 | 5 | for MODEL_TYPE in cd bnn de 6 | do 7 | if [ ${MODEL_TYPE} == de ] 8 | then 9 | N_EPOCHS=40 10 | else 11 | N_EPOCHS=200 12 | fi 13 | for ell in {2..15} 14 | do 15 | let ell_max=$ell+1 16 | ARGS="--model-type ${MODEL_TYPE} --ell-range-min ${ell} --ell-range-max ${ell_max} --n-epochs ${N_EPOCHS} --t-spread-max 0.2" 17 | time python ${SCRIPT} ${ARGS} 18 | done 19 | ARGS="--model-type ${MODEL_TYPE} --ell-range-min 8 --ell-range-max 12 --n-epochs ${N_EPOCHS} --t-spread-max 0.2" 20 | time python ${SCRIPT} ${ARGS} 21 | ARGS="--model-type ${MODEL_TYPE} --ell-range-min 12 --ell-range-max 16 --n-epochs ${N_EPOCHS} --t-spread-max 0.2" 22 | time python ${SCRIPT} ${ARGS} 23 | ARGS="--model-type ${MODEL_TYPE} --g-range-min 15 --g-range-max 20 --n-epochs ${N_EPOCHS} --t-spread-max 0.2" 24 | time python ${SCRIPT} ${ARGS} 25 | for g in {10..24} 26 | do 27 | let g_max=$g+1 28 | ARGS="--model-type ${MODEL_TYPE} --g-range-min ${g} --g-range-max ${g_max} --n-epochs ${N_EPOCHS} --t-spread-max 0.2" 29 | time python ${SCRIPT} ${ARGS} 30 | done 31 | done 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | # pictures and data 107 | *.png 108 | *.npy 109 | *.pdf 110 | 111 | # saved models 112 | *.h5 113 | 114 | # pycharm 115 | .idea/ 116 | -------------------------------------------------------------------------------- /data_gen.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.special import gamma 3 | 4 | 5 | def pendulum(n=10000, n_t=10, g_range=None, theta_range=None, ell_range=None, m_range=None, t_spread=None, 6 | ell_spread=None, seed=42): 7 | if g_range is None: 8 | g_range = [5, 15] 9 | if theta_range is None: 10 | theta_range = [5, 15] 11 | if ell_range is None: 12 | ell_range = [0.2, 0.8] 13 | if m_range is None: 14 | m_range = [0.02, 0.1] 15 | if t_spread is None: 16 | t_spread = [0.03, 0.03] 17 | if ell_spread is None: 18 | ell_spread = [0., 0.] 19 | 20 | np.random.seed(seed) 21 | 22 | g = (g_range[1] - g_range[0]) * np.random.rand(n) + g_range[0] 23 | theta = ((theta_range[1] - theta_range[0]) * np.random.rand(n) + theta_range[0]).reshape((n, 1)) 24 | ell = ((ell_range[1] - ell_range[0]) * np.random.rand(n) + ell_range[0]).reshape((n, 1)) 25 | m = ((m_range[1] - m_range[0]) * np.random.rand(n) + m_range[0]).reshape((n, 1)) 26 | t = (2 * np.pi * np.sqrt(ell / g.reshape((n, 1)))) 27 | 28 | t_scales = np.random.uniform(t_spread[0], t_spread[1], n) 29 | t_scales = np.repeat(t_scales, n_t).reshape((n, n_t)) 30 | t_spreads = np.random.normal(scale=t_scales, size=(n, n_t)) 31 | t_sigma = t_spreads * t 32 | t = t + t_sigma 33 | 34 | ell_scales = np.random.uniform(ell_spread[0], ell_spread[1], n).reshape((n, 1)) 35 | ell_spreads = np.random.normal(scale=ell_scales, size=(n, 1)) 36 | ell_sigma = ell_spreads * ell 37 | ell = ell + ell_sigma 38 | 39 | feat = np.concatenate([theta, ell, m, t], axis=1) 40 | y = g 41 | 42 | # statistical uncertainty 43 | delta_t = np.std(t_sigma, axis=1) / np.sqrt(2) * gamma((n_t-1)/2) / gamma(n_t/2) 44 | mean_t = np.mean(t, axis=1) 45 | ell = ell.reshape(n, ) 46 | delta_ell = ell * ell_scales.reshape(n, ) 47 | calc_y = 4 * np.pi ** 2 * ell / mean_t ** 2 48 | delta_y = 4 * np.pi ** 2 / mean_t ** 2 * np.sqrt((2 * ell * delta_t / mean_t) ** 2 + delta_ell ** 2) 49 | 50 | return feat, y, calc_y, delta_y 51 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | absl-py==0.9.0 2 | asn1crypto==0.24.0 3 | astor==0.8.1 4 | attrs==19.3.0 5 | backcall==0.1.0 6 | bleach==3.1.4 7 | cachetools==4.0.0 8 | certifi==2019.11.28 9 | chardet==3.0.4 10 | cloudpickle==1.3.0 11 | cryptography==2.3 12 | cycler==0.10.0 13 | decorator==4.4.1 14 | defusedxml==0.6.0 15 | entrypoints==0.3 16 | enum34==1.1.6 17 | gast==0.2.2 18 | google-auth==1.10.0 19 | google-auth-oauthlib==0.4.1 20 | google-pasta==0.1.8 21 | grpcio==1.26.0 22 | h5py==2.10.0 23 | idna==2.6 24 | importlib-metadata==1.4.0 25 | ipykernel==5.1.3 26 | ipython==7.11.1 27 | ipython-genutils==0.2.0 28 | ipywidgets==7.5.1 29 | jedi==0.15.2 30 | Jinja2==2.10.3 31 | joblib==0.14.1 32 | jsonschema==3.2.0 33 | jupyter==1.0.0 34 | jupyter-client==5.3.4 35 | jupyter-console==6.0.0 36 | jupyter-core==4.6.1 37 | jupyter-http-over-ws==0.0.7 38 | Keras-Applications==1.0.8 39 | Keras-Preprocessing==1.1.0 40 | keyring==10.6.0 41 | keyrings.alt==3.0 42 | kiwisolver==1.1.0 43 | Markdown==3.1.1 44 | MarkupSafe==1.1.1 45 | matplotlib==3.2.0 46 | mistune==0.8.4 47 | more-itertools==8.0.2 48 | nbconvert==5.6.1 49 | nbformat==5.0.3 50 | notebook==6.0.2 51 | numpy==1.18.1 52 | oauthlib==3.1.0 53 | opt-einsum==3.1.0 54 | pandocfilters==1.4.2 55 | parso==0.5.2 56 | pexpect==4.7.0 57 | pickleshare==0.7.5 58 | prometheus-client==0.7.1 59 | prompt-toolkit==2.0.10 60 | protobuf==3.11.2 61 | ptyprocess==0.6.0 62 | pyasn1==0.4.8 63 | pyasn1-modules==0.2.8 64 | pycrypto==2.6.1 65 | Pygments==2.5.2 66 | pygobject==3.26.1 67 | pyparsing==2.4.6 68 | pyrsistent==0.15.7 69 | python-apt==1.6.4 70 | python-dateutil==2.8.1 71 | pyxdg==0.26 72 | pyzmq==18.1.1 73 | qtconsole==4.6.0 74 | requests==2.22.0 75 | requests-oauthlib==1.3.0 76 | rsa==4.0 77 | scikit-learn==0.22.2.post1 78 | scipy==1.4.1 79 | SecretStorage==2.3.1 80 | Send2Trash==1.5.0 81 | six==1.13.0 82 | tensorboard==2.1.0 83 | tensorflow-estimator==2.1.0 84 | tensorflow-gpu==2.1.0 85 | tensorflow-probability==0.9.0 86 | termcolor==1.1.0 87 | terminado==0.8.3 88 | testpath==0.4.4 89 | tornado==6.0.3 90 | traitlets==4.3.3 91 | urllib3==1.25.7 92 | wcwidth==0.1.8 93 | webencodings==0.5.1 94 | Werkzeug==0.16.0 95 | widgetsnbextension==3.5.1 96 | wrapt==1.11.2 97 | zipp==0.6.0 98 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Deeply Uncertain 2 | 3 | Code repository for the paper "Deeply Uncertain: Comparing Methods of Uncertainty Quantification in Deep Learning Algorithms", by @joaocaldeira and @bnord. The paper can be found at arXiv:2004.10710. 4 | 5 | ## Paper Abstract 6 | 7 | We present a comparison of methods for uncertainty quantification (UQ) in deep learning algorithms in the context of a simple physical system. Three of the most common uncertainty quantification methods - Bayesian Neural Networks (BNN), Concrete Dropout (CD), and Deep Ensembles (DE) - are compared to the standard analytic error propagation. We discuss this comparison in terms endemic to both machine learning ("epistemic" and "aleatoric") and the physical sciences ("statistical" and "systematic"). The comparisons are presented in terms of simulated experimental measurements of a single pendulum - a prototypical physical system for studying measurement and analysis techniques. Our results highlight some pitfalls that may occur when using these UQ methods. For example, when the variation of noise in the training set is small, all methods predicted the same relative uncertainty independently of the inputs. This issue is particularly hard to avoid in BNN. On the other hand, when the test set contains samples far from the training distribution, we found that no methods sufficiently increased the uncertainties associated to their predictions. This problem was particularly clear for CD. In light of these results, we make some recommendations for usage and interpretation of UQ methods. 8 | 9 | ## Reproducing the results 10 | 11 | To reproduce the results in the paper, run the script `run_training.sh` followed by `run_tests.sh` and all the cells in the notebook `make_plots.ipynb`. To recreate the environment, you can install packages from the `requirements.txt` file, or use the docker image `tensorflow/tensorflow:latest-gpu-py3-jupyter` and install `scikit-learn`, `tensorflow-probability`, and `matplotlib==3.2`. 12 | 13 | ## Basic explanation of code 14 | 15 | 1. data_gen.py: generates simulations of pendulum swing data 16 | 2. preprocssin.py: rescales data 17 | 3. train_network.py: generates data and trains one kind of UQ neural network 18 | 4. test_network.py: evaluates one kind of trained neural network 19 | 5. run_train.sh: run all model training to replicate the paper results 20 | 6. run_test.sh: test all trained models to replicate the paper results 21 | 7. make_plots.ipynb: notebook to generate plots tested and trained models 22 | 8. models/cd.py: concrete dropout 23 | 9. models/mlp_tf: flipout for BNN model 24 | 25 | -------------------------------------------------------------------------------- /models/mlp_tf.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import tensorflow_probability as tfp 3 | from tensorflow_probability.python.internal import tensorshape_util 4 | 5 | tfk = tf.keras 6 | tfkl = tf.keras.layers 7 | tfpl = tfp.layers 8 | tfd = tfp.distributions 9 | 10 | n_train = 90000 11 | 12 | 13 | class MeanMetricWrapper(tfk.metrics.Mean): 14 | # code by @mcourteaux from https://github.com/tensorflow/probability/issues/742#issuecomment-580433644 15 | def __init__(self, fn, name=None, dtype=None, **kwargs): 16 | super(MeanMetricWrapper, self).__init__(name=name, dtype=dtype) 17 | self._fn = fn 18 | self._fn_kwargs = kwargs 19 | 20 | def update_state(self, y_true, y_pred, sample_weight=None): 21 | matches = self._fn(y_true, y_pred, **self._fn_kwargs) 22 | return super(MeanMetricWrapper, self).update_state( 23 | matches, sample_weight=sample_weight) 24 | 25 | def get_config(self): 26 | config = {} 27 | for k, v in six.iteritems(self._fn_kwargs): 28 | config[k] = K.eval(v) if is_tensor_or_variable(v) else v 29 | base_config = super(MeanMetricWrapper, self).get_config() 30 | return dict(list(base_config.items()) + list(config.items())) 31 | 32 | 33 | def scaled_kl_fn(a, b, _): 34 | """ 35 | idea from 36 | https://github.com/google-research/google-research/blob/9645220c865ab5603b377e6a98265631ece61d44/uq_benchmark_2019/uq_utils.py 37 | https://arxiv.org/pdf/1906.02530.pdf 38 | :param a: distribution 39 | :param b: distribution 40 | :return: scaled kl divergence 41 | """ 42 | return tfd.kl_divergence(a, b) / n_train 43 | 44 | 45 | def mmd_from_dists(a, b, _): 46 | p = a.distribution 47 | q = b.distribution 48 | 49 | num_reduce_dims = (tensorshape_util.rank(a.event_shape) - 50 | tensorshape_util.rank(p.event_shape)) 51 | gamma_sq = 0.5 52 | reduce_dims = [-i - 1 for i in range(0, num_reduce_dims)] 53 | for i in reduce_dims: 54 | gamma_sq *= a.event_shape[i] 55 | 56 | sigma_p = tf.convert_to_tensor(tf.square(p.scale)) 57 | sigma_q = tf.convert_to_tensor(tf.square(q.scale)) 58 | scale_pp = gamma_sq + 2 * sigma_p 59 | scale_qq = gamma_sq + 2 * sigma_q 60 | scale_cr = gamma_sq + sigma_p + sigma_q 61 | 62 | return tf.reduce_sum( 63 | tf.math.sqrt(gamma_sq / scale_pp) + tf.math.sqrt(gamma_sq / scale_qq) 64 | - 2 * tf.math.sqrt(gamma_sq / scale_cr) * tf.math.exp( 65 | -0.5 * tf.math.squared_difference(p.loc, q.loc) / scale_cr), 66 | axis=reduce_dims) 67 | 68 | 69 | def negloglik(y_data, rv_y): 70 | return -rv_y.log_prob(y_data) 71 | 72 | 73 | def negloglik_met(y_true, y_pred): 74 | return tf.reduce_mean(-y_pred.log_prob(tf.cast(y_true, tf.float32))) 75 | 76 | 77 | def mlp(hidden_dim=100, n_layers=3, n_inputs=13, dropout_rate=0, loss='mse'): 78 | input_data = tfkl.Input((n_inputs,)) 79 | x = input_data 80 | for _ in range(n_layers): 81 | x = tfkl.Dense(hidden_dim, activation='relu')(x) 82 | if dropout_rate > 0: 83 | x = tfkl.Dropout(dropout_rate)(x) 84 | 85 | if loss == 'mse': 86 | x = tfkl.Dense(1)(x) 87 | model = tfk.Model(input_data, x) 88 | model.compile(loss='mean_squared_error', optimizer=tf.optimizers.Adam()) 89 | elif loss == 'nll': 90 | x = tfkl.Dense(2)(x) 91 | x = tfpl.DistributionLambda(lambda t: tfd.Normal(loc=t[..., :1], 92 | scale=1e-3 + tf.math.softplus(t[..., 1:])))(x) 93 | model = tfk.Model(input_data, x) 94 | model.compile(optimizer=tf.optimizers.Adam(), loss=negloglik, metrics=['mse']) 95 | else: 96 | raise ValueError(f'Loss {loss} not implemented.') 97 | 98 | return model 99 | 100 | 101 | def mlp_flipout(hidden_dim=100, n_layers=3, n_inputs=13, dropout_rate=0, kernel='kl'): 102 | input_img = tfkl.Input(n_inputs) 103 | x = input_img 104 | if kernel == 'kl': 105 | kernel_fn = scaled_kl_fn 106 | elif kernel == 'mmd': 107 | kernel_fn = mmd_from_dists 108 | else: 109 | raise ValueError(f'Kernel {kernel} not defined!') 110 | 111 | for _ in range(n_layers): 112 | x = tfpl.DenseFlipout(hidden_dim, activation='relu', kernel_divergence_fn=kernel_fn)(x) 113 | if dropout_rate > 0: 114 | x = tfkl.Dropout(dropout_rate)(x) 115 | x = tfpl.DenseFlipout(2, kernel_divergence_fn=kernel_fn)(x) 116 | x = tfpl.DistributionLambda(lambda t: tfd.Normal(loc=t[..., :1], 117 | scale=1e-3 + tf.math.softplus(t[..., 1:])))(x) 118 | model = tfk.Model(input_img, x) 119 | 120 | model.compile(optimizer=tf.optimizers.Adam(learning_rate=1e-4), loss=negloglik, 121 | metrics=['mse', MeanMetricWrapper(negloglik_met, name='nll')]) 122 | 123 | return model 124 | -------------------------------------------------------------------------------- /test_network.py: -------------------------------------------------------------------------------- 1 | from data_gen import pendulum 2 | import pickle 3 | from models.mlp_tf import mlp, mlp_flipout 4 | from models.cd import make_model 5 | import argparse 6 | import numpy as np 7 | 8 | parser = argparse.ArgumentParser() 9 | parser.add_argument('--model-type', default='de', type=str, help='model type') 10 | parser.add_argument('--model-number', default='1', type=int, help='model number') 11 | parser.add_argument('--t-spread-min', default=0.01, type=float, help='minimum T spread (rel noise on measurements)') 12 | parser.add_argument('--t-spread-max', default=0.1, type=float, help='maximum T spread (rel noise on measurements)') 13 | parser.add_argument('--ell-spread-min', default=0.02, type=float, help='minimum L spread (rel noise on measurements)') 14 | parser.add_argument('--ell-spread-max', default=0.02, type=float, help='maximum L spread (rel noise on measurements)') 15 | parser.add_argument('--ell-range-min', default=2, type=int, help='minimum 10*L') 16 | parser.add_argument('--ell-range-max', default=8, type=int, help='maximum 10*L') 17 | parser.add_argument('--g-range-min', default=5, type=int, help='minimum g') 18 | parser.add_argument('--g-range-max', default=15, type=int, help='maximum g') 19 | parser.add_argument('--n-test', default=10000, type=int, help='number of test examples') 20 | parser.add_argument('--n-epochs', default=100, type=int, help='number of training epochs') 21 | parser.add_argument('--data-dir', default='data/', type=str, help='data directory') 22 | 23 | n_models = 10 24 | n_neurons = 100 25 | 26 | 27 | def main(model_type, model_number, t_spread_min, t_spread_max, ell_spread_min, ell_spread_max, ell_range_min, 28 | ell_range_max, g_range_min, g_range_max, n_test, n_epochs, data_dir): 29 | t_range_str = f'trange{int(100 * t_spread_min)}to{int(100 * t_spread_max)}' 30 | model_name = f'{model_type}_{t_range_str}_{n_epochs}ep' 31 | 32 | test_name = '' 33 | if ell_range_min != 2 or ell_range_max != 8: 34 | test_name += f'_ell{int(ell_range_min)}to{int(ell_range_max)}' 35 | if g_range_min != 5. or g_range_max != 15.: 36 | test_name += f'_g{int(g_range_min)}to{int(g_range_max)}' 37 | 38 | ell_range_min /= 10. 39 | ell_range_max /= 10. 40 | 41 | # Generate data 42 | feat_test, _, _, _ = pendulum(n=n_test, t_spread=[t_spread_min, t_spread_max], 43 | ell_range=[ell_range_min, ell_range_max], g_range=[g_range_min, g_range_max], 44 | ell_spread=[ell_spread_min, ell_spread_max], seed=666) 45 | 46 | with open(f'{data_dir}x_scaler_{t_range_str}.pkl', 'rb') as file_pi: 47 | x_scaler = pickle.load(file_pi) 48 | with open(f'{data_dir}y_scaler_{t_range_str}.pkl', 'rb') as file_pi: 49 | y_scaler = pickle.load(file_pi) 50 | 51 | feat_test = x_scaler.transform(feat_test) 52 | 53 | if model_type == 'de': 54 | models = [mlp(loss='nll') for _ in range(n_models)] 55 | elif model_type == 'cd': 56 | n_features = feat_test.shape[1] 57 | n_outputs = 1 58 | models = [make_model(n_features, n_outputs, n_neurons)] 59 | elif model_type == 'bnn': 60 | models = [mlp_flipout()] 61 | else: 62 | raise ValueError(f'Model type {model_type} not recognized!') 63 | 64 | for j, mod in enumerate(models): 65 | mod.load_weights(f'{data_dir}model_{model_name}_{str(model_number+j).zfill(3)}.h5') 66 | 67 | # make predictions 68 | if model_type == 'de': 69 | y_pred = [] 70 | for model in models: 71 | y_pred.append(model(feat_test.astype('float32'))) 72 | elif model_type == 'cd': 73 | y_pred = np.array([models[0].predict(feat_test) for _ in range(n_models)]) 74 | elif model_type == 'bnn': 75 | y_pred = [models[0](feat_test.astype('float32')) for _ in range(n_models)] 76 | 77 | if model_type == 'de' or model_type == 'bnn': 78 | y_pred_val = [pred.loc.numpy() for pred in y_pred] 79 | y_pred_unc = [pred.scale.numpy() for pred in y_pred] 80 | elif model_type == 'cd': 81 | y_pred_val = y_pred[:, :, :1] 82 | y_pred_unc = np.sqrt(np.exp(y_pred[:, :, 1:])) 83 | 84 | y_pred_val_resc = [y_scaler.inverse_transform(y) for y in y_pred_val] 85 | y_pred_unc_resc = [y / y_scaler.scale_[0] for y in y_pred_unc] 86 | 87 | y_pred_val_resc = np.array(y_pred_val_resc).reshape((n_models, n_test)) 88 | y_pred_unc_resc = np.array(y_pred_unc_resc).reshape((n_models, n_test)) 89 | 90 | y_pred_mean = np.mean(y_pred_val_resc, axis=0) 91 | y_pred_ep_unc = np.std(y_pred_val_resc, axis=0) 92 | y_pred_al_unc = np.sqrt(np.mean(y_pred_unc_resc * y_pred_unc_resc, axis=0)) 93 | y_pred_unc = np.sqrt(y_pred_al_unc ** 2 + y_pred_ep_unc ** 2) 94 | 95 | np.save(f'{data_dir}y_pred_test_{model_name}_{str(model_number).zfill(3)}{test_name}.npy', y_pred_mean) 96 | np.save(f'{data_dir}y_pred_test_alunc_{model_name}_{str(model_number).zfill(3)}{test_name}.npy', y_pred_al_unc) 97 | np.save(f'{data_dir}y_pred_test_epunc_{model_name}_{str(model_number).zfill(3)}{test_name}.npy', y_pred_ep_unc) 98 | np.save(f'{data_dir}y_pred_test_prunc_{model_name}_{str(model_number).zfill(3)}{test_name}.npy', y_pred_unc) 99 | 100 | 101 | if __name__ == '__main__': 102 | args = parser.parse_args() 103 | main(**vars(args)) 104 | -------------------------------------------------------------------------------- /train_network.py: -------------------------------------------------------------------------------- 1 | from data_gen import pendulum 2 | from sklearn.model_selection import train_test_split 3 | from preprocessing import scale 4 | import pickle 5 | from models.mlp_tf import mlp, mlp_flipout 6 | from models.cd import make_model 7 | import argparse 8 | import os 9 | import numpy as np 10 | 11 | parser = argparse.ArgumentParser() 12 | parser.add_argument('--model-type', default='de', type=str, help='model type') 13 | parser.add_argument('--t-spread-min', default=0.01, type=float, help='minimum T spread (rel noise on measurements)') 14 | parser.add_argument('--t-spread-max', default=0.1, type=float, help='maximum T spread (rel noise on measurements)') 15 | parser.add_argument('--ell-spread-min', default=0.02, type=float, help='minimum L spread (rel noise on measurements)') 16 | parser.add_argument('--ell-spread-max', default=0.02, type=float, help='maximum L spread (rel noise on measurements)') 17 | parser.add_argument('--n', default=100000, type=int, help='number of training and validation examples') 18 | parser.add_argument('--n-test', default=10000, type=int, help='number of test examples') 19 | parser.add_argument('--n-epochs', default=100, type=int, help='number of training epochs') 20 | parser.add_argument('--data-dir', default='data/', type=str, help='data directory') 21 | 22 | val_proportion = 0.1 23 | n_models = 10 24 | n_neurons = 100 25 | 26 | 27 | def main(model_type, t_spread_min, t_spread_max, ell_spread_min, ell_spread_max, n, n_test, n_epochs, data_dir): 28 | # Generate data 29 | feat, y, _, _ = pendulum(n=n, t_spread=[t_spread_min, t_spread_max], ell_spread=[ell_spread_min, ell_spread_max]) 30 | 31 | # Set up data 32 | x_train, x_val, y_train, y_val = train_test_split(feat, y, test_size=val_proportion, random_state=42) 33 | x_scaler, x_train, x_val = scale(x_train, x_val) 34 | y_scaler, y_train, y_val = scale(y_train, y_val) 35 | 36 | t_range_str = f'trange{int(100*t_spread_min)}to{int(100*t_spread_max)}' 37 | model_name = f'{model_type}_{t_range_str}_{n_epochs}ep' 38 | 39 | os.makedirs(data_dir, exist_ok=True) 40 | 41 | if not os.path.isfile(f'{data_dir}x_scaler_{t_range_str}.pkl'): 42 | with open(f'{data_dir}x_scaler_{t_range_str}.pkl', 'wb') as file_pi: 43 | pickle.dump(x_scaler, file_pi) 44 | with open(f'{data_dir}y_scaler_{t_range_str}.pkl', 'wb') as file_pi: 45 | pickle.dump(y_scaler, file_pi) 46 | 47 | # train and save models 48 | model_number = 1 49 | while os.path.isfile(f'{data_dir}model_{model_name}_{str(model_number).zfill(3)}.h5'): 50 | model_number += 1 51 | 52 | if model_type == 'de': 53 | models = [mlp(loss='nll') for _ in range(n_models)] 54 | elif model_type == 'cd': 55 | n_features = x_train.shape[1] 56 | n_outputs = y_train.shape[1] 57 | dropout_reg = 2. / n 58 | models = [make_model(n_features, n_outputs, n_neurons, dropout_reg)] 59 | elif model_type == 'bnn': 60 | models = [mlp_flipout()] 61 | else: 62 | raise ValueError(f'Model type {model_type} not recognized!') 63 | 64 | for j, mod in enumerate(models): 65 | print(f'Model {j+1}') 66 | history = mod.fit(x_train, y_train, epochs=n_epochs, validation_data=(x_val, y_val)) 67 | mod.save_weights(f'{data_dir}model_{model_name}_{str(model_number+j).zfill(3)}.h5') 68 | with open(f'{data_dir}history_{model_name}_{str(model_number+j).zfill(3)}.pkl', 'wb') as file_pi: 69 | pickle.dump(history.history, file_pi) 70 | 71 | # Generate test set 72 | feat_test, _, _, _ = pendulum(n=n_test, t_spread=[t_spread_min, t_spread_max], 73 | ell_spread=[ell_spread_min, ell_spread_max], seed=666) 74 | feat_test = x_scaler.transform(feat_test) 75 | 76 | # make predictions 77 | if model_type == 'de': 78 | y_pred = [] 79 | for model in models: 80 | y_pred.append(model(feat_test.astype('float32'))) 81 | elif model_type == 'cd': 82 | y_pred = np.array([models[0].predict(feat_test) for _ in range(n_models)]) 83 | elif model_type == 'bnn': 84 | y_pred = [models[0](feat_test.astype('float32')) for _ in range(n_models)] 85 | 86 | if model_type == 'de' or model_type == 'bnn': 87 | y_pred_val = [pred.loc.numpy() for pred in y_pred] 88 | y_pred_unc = [pred.scale.numpy() for pred in y_pred] 89 | elif model_type == 'cd': 90 | y_pred_val = y_pred[:, :, :1] 91 | y_pred_unc = np.sqrt(np.exp(y_pred[:, :, 1:])) 92 | 93 | y_pred_val_resc = [y_scaler.inverse_transform(y) for y in y_pred_val] 94 | y_pred_unc_resc = [y / y_scaler.scale_[0] for y in y_pred_unc] 95 | 96 | y_pred_val_resc = np.array(y_pred_val_resc).reshape((n_models, n_test)) 97 | y_pred_unc_resc = np.array(y_pred_unc_resc).reshape((n_models, n_test)) 98 | 99 | y_pred_mean = np.mean(y_pred_val_resc, axis=0) 100 | y_pred_ep_unc = np.std(y_pred_val_resc, axis=0) 101 | y_pred_al_unc = np.sqrt(np.mean(y_pred_unc_resc * y_pred_unc_resc, axis=0)) 102 | y_pred_unc = np.sqrt(y_pred_al_unc ** 2 + y_pred_ep_unc ** 2) 103 | 104 | np.save(f'{data_dir}y_pred_test_{model_name}_{str(model_number).zfill(3)}.npy', y_pred_mean) 105 | np.save(f'{data_dir}y_pred_test_alunc_{model_name}_{str(model_number).zfill(3)}.npy', y_pred_al_unc) 106 | np.save(f'{data_dir}y_pred_test_epunc_{model_name}_{str(model_number).zfill(3)}.npy', y_pred_ep_unc) 107 | np.save(f'{data_dir}y_pred_test_prunc_{model_name}_{str(model_number).zfill(3)}.npy', y_pred_unc) 108 | 109 | 110 | if __name__ == '__main__': 111 | args = parser.parse_args() 112 | main(**vars(args)) 113 | -------------------------------------------------------------------------------- /models/cd.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | from tensorflow.keras import optimizers 3 | from tensorflow.keras.layers import InputSpec, Dense, Wrapper, Input, concatenate 4 | from tensorflow.keras.models import Model 5 | import numpy as np 6 | 7 | 8 | class ConcreteDropout(Wrapper): 9 | """This wrapper allows to learn the dropout probability for any given input Dense layer. 10 | ```python 11 | # as the first layer in a model 12 | model = Sequential() 13 | model.add(ConcreteDropout(Dense(8), input_shape=(16))) 14 | # now model.output_shape == (None, 8) 15 | # subsequent layers: no need for input_shape 16 | model.add(ConcreteDropout(Dense(32))) 17 | # now model.output_shape == (None, 32) 18 | ``` 19 | `ConcreteDropout` can be used with arbitrary layers which have 2D 20 | kernels, not just `Dense`. However, Conv2D layers require different 21 | weighing of the regulariser (use SpatialConcreteDropout instead). 22 | # Arguments 23 | layer: a layer instance. 24 | weight_regularizer: 25 | A positive number which satisfies 26 | $weight_regularizer = l**2 / (\tau * N)$ 27 | with prior lengthscale l, model precision $\tau$ (inverse observation noise), 28 | and N the number of instances in the dataset. 29 | Note that kernel_regularizer is not needed. 30 | dropout_regularizer: 31 | A positive number which satisfies 32 | $dropout_regularizer = 2 / (\tau * N)$ 33 | with model precision $\tau$ (inverse observation noise) and N the number of 34 | instances in the dataset. 35 | Note the relation between dropout_regularizer and weight_regularizer: 36 | $weight_regularizer / dropout_regularizer = l**2 / 2$ 37 | with prior lengthscale l. Note also that the factor of two should be 38 | ignored for cross-entropy loss, and used only for the eculedian loss. 39 | """ 40 | 41 | def __init__(self, layer, weight_regularizer=0, dropout_regularizer=1e-5, 42 | init_min=0.1, init_max=0.1, is_mc_dropout=True, **kwargs): 43 | assert 'kernel_regularizer' not in kwargs 44 | super(ConcreteDropout, self).__init__(layer, **kwargs) 45 | self.weight_regularizer = weight_regularizer 46 | self.dropout_regularizer = dropout_regularizer 47 | self.is_mc_dropout = is_mc_dropout 48 | self.supports_masking = True 49 | self.p_logit = None 50 | self.init_min = np.log(init_min) - np.log(1. - init_min) 51 | self.init_max = np.log(init_max) - np.log(1. - init_max) 52 | 53 | def build(self, input_shape=None): 54 | self.input_spec = InputSpec(shape=input_shape) 55 | if not self.layer.built: 56 | self.layer.build(input_shape) 57 | self.layer.built = True 58 | super(ConcreteDropout, self).build() 59 | 60 | # initialise p 61 | self.p_logit = self.add_weight(name='p_logit', 62 | shape=(1,), 63 | initializer=tf.random_uniform_initializer(self.init_min, self.init_max), 64 | dtype=tf.dtypes.float32, 65 | trainable=True) 66 | 67 | def compute_output_shape(self, input_shape): 68 | return self.layer.compute_output_shape(input_shape) 69 | 70 | def concrete_dropout(self, x, p): 71 | """ 72 | Concrete dropout - used at training time (gradients can be propagated) 73 | :param x: input 74 | :return: approx. dropped out input 75 | """ 76 | eps = 1e-07 77 | temp = 0.1 78 | 79 | unif_noise = tf.random.uniform(shape=tf.shape(x)) 80 | drop_prob = ( 81 | tf.math.log(p + eps) 82 | - tf.math.log(1. - p + eps) 83 | + tf.math.log(unif_noise + eps) 84 | - tf.math.log(1. - unif_noise + eps) 85 | ) 86 | drop_prob = tf.math.sigmoid(drop_prob / temp) 87 | random_tensor = 1. - drop_prob 88 | 89 | retain_prob = 1. - p 90 | x *= random_tensor 91 | x /= retain_prob 92 | return x 93 | 94 | def call(self, inputs, training=None): 95 | p = tf.math.sigmoid(self.p_logit) 96 | 97 | # initialise regulariser / prior KL term 98 | input_dim = inputs.shape[-1] # last dim 99 | weight = self.layer.kernel 100 | kernel_regularizer = self.weight_regularizer * tf.reduce_sum(tf.square(weight)) / (1. - p) 101 | dropout_regularizer = p * tf.math.log(p) + (1. - p) * tf.math.log(1. - p) 102 | dropout_regularizer *= self.dropout_regularizer * input_dim 103 | regularizer = tf.reduce_sum(kernel_regularizer + dropout_regularizer) 104 | if self.is_mc_dropout: 105 | return self.layer.call(self.concrete_dropout(inputs, p)), regularizer 106 | else: 107 | def relaxed_dropped_inputs(): 108 | return self.layer.call(self.concrete_dropout(inputs, p)), regularizer 109 | 110 | return tf.keras.backend.in_train_phase(relaxed_dropped_inputs, 111 | self.layer.call(inputs), 112 | training=training), regularizer 113 | 114 | 115 | def mse_loss(true, pred): 116 | n_outputs = pred.shape[1] // 2 117 | mean = pred[:, :n_outputs] 118 | return tf.reduce_mean((true - mean) ** 2, -1) 119 | 120 | 121 | def heteroscedastic_loss(true, pred): 122 | n_outputs = pred.shape[1] // 2 123 | mean = pred[:, :n_outputs] 124 | log_var = pred[:, n_outputs:] 125 | precision = tf.math.exp(-log_var) 126 | return tf.reduce_sum(precision * (true - mean) ** 2. + log_var, -1) 127 | 128 | 129 | def make_model(n_features, n_outputs, n_nodes=100, dropout_reg=1e-5, wd=0): 130 | losses = [] 131 | inp = Input(shape=(n_features,)) 132 | x = inp 133 | x, loss = ConcreteDropout(Dense(n_nodes, activation='relu'), 134 | weight_regularizer=wd, dropout_regularizer=dropout_reg)(x) 135 | losses.append(loss) 136 | x, loss = ConcreteDropout(Dense(n_nodes, activation='relu'), 137 | weight_regularizer=wd, dropout_regularizer=dropout_reg)(x) 138 | losses.append(loss) 139 | x, loss = ConcreteDropout(Dense(n_nodes, activation='relu'), 140 | weight_regularizer=wd, dropout_regularizer=dropout_reg)(x) 141 | losses.append(loss) 142 | mean, loss = ConcreteDropout(Dense(n_outputs), weight_regularizer=wd, dropout_regularizer=dropout_reg)(x) 143 | losses.append(loss) 144 | log_var, loss = ConcreteDropout(Dense(n_outputs), weight_regularizer=wd, dropout_regularizer=dropout_reg)(x) 145 | losses.append(loss) 146 | out = concatenate([mean, log_var]) 147 | model = Model(inp, out) 148 | for loss in losses: 149 | model.add_loss(loss) 150 | 151 | model.compile(optimizer=optimizers.Adam(), loss=heteroscedastic_loss, metrics=[mse_loss]) 152 | assert len(model.layers[1].trainable_weights) == 3 # kernel, bias, and dropout prob 153 | assert len(model.losses) == 5, f'{len(model.losses)} is not 5' # a loss for each Concrete Dropout layer 154 | 155 | return model 156 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------