<jupyter_start><jupyter_text>log-sum-exp trick<jupyter_code>%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
np.exp(0)
np.exp(-1000)
xs = np.arange(-100, 0, 0.01)
ls = np.exp(xs)
plt.plot(xs, ls)
def log_sum_exp(xs):
    xs = np.array(xs)
    return np.log(np.sum(np.exp(xs)))

def log_sum_exp_trick(xs, f=np.max):
    xs = np.array(xs)
    a = f(xs)
    return a + np.log(np.sum(np.exp(xs - a)))
log_sum_exp([-10] * 10)
log_sum_exp_trick([-10] * 10)
log_sum_exp([-1e10] * 10)
log_sum_exp_trick([-1e10] * 10, f=np.max)
log_sum_exp_trick([-1e10] * 10, f=np.min)
10 ** -10 == 1e-10
x = [-1e10] * 10 + [0.999]
x = [-1e5] * 2
log_sum_exp_trick(x)
log_sum_exp_trick(x)
log_sum_exp(x)
log_sum_exp_trick([-1e10] * 10 + [-0.999], f=np.min)
log_sum_exp_trick([-1e10] * 10 + [-0.999], f=np.max)
xs = [-1e10, -1e8]
log_sum_exp(xs)
log_sum_exp_trick(xs)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1984304932735426, 'fraction_numerical': 0.08632286995515695, 'mean_word_length': 4.445121951219512, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '633624', 'license': 'MIT', 'n_tokens_mistral': 506, 'n_tokens_neox': 458, 'n_words': 76, 'path': 'algorithms/log-sum-exp-trick.ipynb', 'repo_name': 'ashishpatel26/learning', 'size': '892'}