<jupyter_start><jupyter_text>Copyright 2018 The TensorFlow Authors.Licensed under the Apache License, Version 2.0 (the "License");<jupyter_code>#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.<jupyter_output><empty_output><jupyter_text>Credit Card Interest      Run in Google Colab        View source on GitHub   Let’s imagine that you would like to estimate the interest rate on your credit card one year from now. Suppose the current prime rate is 2% and your credit card company charges you 10% plus prime. Given the strength of the current economy, you believe that the Federal Reserve is more likely to raise interest rates than not. The Fed will meet eight times in the next twelve months and will either raise the federal funds rate by 0.25% or leave it at the previous level. We use the binomial distribution to model your credit card’s interest rate at the end of the twelve-month period. Specifically, we’ll use the TensorFlow Probability Binomial distribution class  with the following parameters: total_count = 8 (number of trials or meetings), probs = {.6, .7, .8, .9}, for our range of estimates about the probability of the Fed raising the federal funds rate by 0.25% at each meeting.  Dependencies & Prerequisites<jupyter_code>#@title TensorFlow Probability Installation settings { display-mode: "form" }
TFP_Installation = "Stable TFP" #@param ["Most Recent TFP", "Stable TFP", "Stable TFP-GPU", "Most Recent TFP-GPU", "TFP Already Installed"]

if TFP_Installation == "Most Recent TFP":
    !pip install -q tfp-nightly
    print("Most recent TFP version installed")
elif TFP_Installation == "Stable TFP":
    !pip install -q --upgrade tensorflow-probability
    print("Up-to-date, stable  TFP version installed")
elif TFP_Installation == "Stable TFP-GPU":
    !pip install -q --upgrade tensorflow-probability-gpu
    print("Up-to-date, stable TFP-GPU version installed")
    print("(make sure GPU is properly configured)")
elif TFP_Installation == "Most Recent TFP-GPU":
    !pip install -q tfp-nightly-gpu
    print("Most recent TFP-GPU version installed")
    print("(make sure GPU is properly configured)")
elif TFP_Installation == "TFP Already Installed":
    print("TFP already installed in this environment")
    pass
else:
    print("Installation Error: Please select a viable TFP installation option.")


#@title Imports and Global Variables (make sure to run this cell)  { display-mode: "form" }
from __future__ import absolute_import, division, print_function

warning_status = "ignore" #@param ["ignore", "always", "module", "once", "default", "error"]
import warnings
warnings.filterwarnings(warning_status)
with warnings.catch_warnings():
    warnings.filterwarnings(warning_status, category=DeprecationWarning)
    warnings.filterwarnings(warning_status, category=UserWarning)

import numpy as np
import os
matplotlib_style = 'fivethirtyeight' #@param ['fivethirtyeight', 'bmh', 'ggplot', 'seaborn', 'default', 'Solarize_Light2', 'classic', 'dark_background', 'seaborn-colorblind', 'seaborn-notebook']
import matplotlib.pyplot as plt; plt.style.use(matplotlib_style)
import matplotlib.axes as axes;
from matplotlib.patches import Ellipse
%matplotlib inline
import seaborn as sns; sns.set_context('notebook')
notebook_screen_res = 'png' #@param ['retina', 'png', 'jpeg', 'svg', 'pdf']
%config InlineBackend.figure_format = notebook_screen_res

import tensorflow as tf

# Eager Execution
use_tf_eager = True #@param {type:"boolean"}


# Use try/except so we can easily re-execute the whole notebook.
if use_tf_eager:
  try:
    tf.compat.v1.enable_eager_execution()
  except:
    reset_session()


import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
 

def default_session_options(enable_gpu_ram_resizing=True,
                            enable_xla=False):
  """Creates default options for Graph-mode session."""
  config = tf.ConfigProto()
  config.log_device_placement = True
  if enable_gpu_ram_resizing:
    # `allow_growth=True` makes it possible to connect multiple
    # colabs to your GPU. Otherwise the colab malloc's all GPU ram.
    config.gpu_options.allow_growth = True
  if enable_xla:
    # Enable on XLA. https://www.tensorflow.org/performance/xla/.
    config.graph_options.optimizer_options.global_jit_level = (
        tf.OptimizerOptions.ON_1)
  return config


def reset_session(options=None):
  """Creates a new global, interactive session in Graph-mode."""
  if tf.executing_eagerly():
    return
  global sess
  try:
    tf.reset_default_graph()
    sess.close()
  except:
    pass
  if options is None:
    options = default_session_options()
  sess = tf.InteractiveSession(config=options)
 

def evaluate(tensors):
  """Evaluates Tensor or EagerTensor to Numpy `ndarray`s.
  Args:
  tensors: Object of `Tensor` or EagerTensor`s; can be `list`, `tuple`,
    `namedtuple` or combinations thereof.
 
  Returns:
    ndarrays: Object with same structure as `tensors` except with `Tensor` or
      `EagerTensor`s replaced by Numpy `ndarray`s.
  """
  if tf.executing_eagerly():
    return tf.contrib.framework.nest.pack_sequence_as(
        tensors,
        [t.numpy() if tf.contrib.framework.is_tensor(t) else t
         for t in tf.contrib.framework.nest.flatten(tensors)])
  return sess.run(tensors)


class _TFColor(object):
  """Enum of colors used in TF docs."""
  red = '#F15854'
  blue = '#5DA5DA'
  orange = '#FAA43A'
  green = '#60BD68'
  pink = '#F17CB0'
  brown = '#B2912F'
  purple = '#B276B2'
  yellow = '#DECF3F'
  gray = '#4D4D4D'
  def __getitem__(self, i):
    return [
        self.red,
        self.orange,
        self.green,
        self.blue,
        self.pink,
        self.brown,
        self.purple,
        self.yellow,
        self.gray,
    ][i % 9]
TFColor = _TFColor()<jupyter_output><empty_output><jupyter_text>Compute Probabilities Compute the probabilities of possible credit card interest rates in 12 months.<jupyter_code># First we encode our assumptions.
num_times_fed_meets_per_year = 8.
possible_fed_increases = tf.range(
    start=0.,
    limit=num_times_fed_meets_per_year + 1)
possible_cc_interest_rates = 2. + 10. + 0.25 * possible_fed_increases 
prob_fed_raises_rates = tf.constant([0.6, 0.7, 0.8, 0.9])  # Wild guesses.

# Now we use TFP to compute probabilities in a vectorized manner.
# Pad a dim so we broadcast fed probs against CC interest rates.
prob_fed_raises_rates = prob_fed_raises_rates[..., tf.newaxis]
prob_cc_interest_rate = tfd.Binomial(
    total_count=num_times_fed_meets_per_year,
    probs=prob_fed_raises_rates).prob(possible_fed_increases)<jupyter_output><empty_output><jupyter_text>Execute TF Code<jupyter_code># Convert from TF to numpy.
[
    possible_cc_interest_rates_,
    prob_cc_interest_rate_,
    prob_fed_raises_rates_,
] = evaluate([
    possible_cc_interest_rates,
    prob_cc_interest_rate,
    prob_fed_raises_rates,
])<jupyter_output><empty_output><jupyter_text>Visualize Results<jupyter_code>plt.figure(figsize=(14, 9))
for i, pf in enumerate(prob_fed_raises_rates_):
  plt.subplot(2, 2, i+1)
  plt.bar(possible_cc_interest_rates_,
          prob_cc_interest_rate_[i],
          color=TFColor[i],
          width=0.23,
          label="$p = {:.1f}$".format(pf[0]),
          alpha=0.6,
          edgecolor=TFColor[i],
          lw="3")
  plt.xticks(possible_cc_interest_rates_ + 0.125, possible_cc_interest_rates_)
  plt.xlim(12, 14.25)
  plt.ylim(0, 0.5)
  plt.ylabel("Probability of cc interest rate")
  plt.xlabel("Credit card interest rate (%)")
  plt.title("Credit card interest rates: "
            "prob_fed_raises_rates = {:.1f}".format(pf[0]));
  plt.suptitle("Estimates of credit card interest rates in 12 months.",
               fontsize="x-large",
               y=1.02)
  plt.tight_layout()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10013222743118164, 'fraction_numerical': 0.013102536362543575, 'mean_word_length': 4.190268247036806, 'pattern_counts': {'":': 5, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '41546', 'license': 'Apache-2.0', 'n_tokens_mistral': 2749, 'n_tokens_neox': 2615, 'n_words': 799, 'path': 'tensorflow_probability/examples/jupyter_notebooks/Credit_Card_Interest.ipynb', 'repo_name': 'eozd/probability', 'size': '8319'}