Create a NumPy function named log_sum_exp which computes the natural logarithm (base e) of the sum of the exponentials of the input elements. This is a common operation in many statistical computations.
Example:
Input array: [1, 2, 3]
Output: 3.40760596444438
Solution
Try the exercise on your own first, then compare with the worked solution below.
# Solutiondef log_sum_exp(arr):""" Computes the logarithm of the sum of exponentiations of the input elements: Natural logarithm of the sum of exponentials (base e) """ exp_sum = np.sum(np.exp(arr)) log_sum_exp_base_e = np.log(exp_sum)return log_sum_exp_base_e# Example arrayarray = np.array([1, 2, 3])# Compute the log-sum-exp for the example arraylog_sum_exp_result = log_sum_exp(array)print(log_sum_exp_result)
NameError: name 'np' is not defined
Source Code
---title: "Review: Log-Sum-Exp Function"subtitle: "Module 4: IDEs & Tools"format: html---## Log-Sum-Exp FunctionCreate a NumPy function named `log_sum_exp` which computes the natural logarithm (base e) of the sum of the exponentials of the input elements. This is a common operation in many statistical computations.Example:- Input array: [1, 2, 3]- Output: 3.40760596444438::: {.callout-tip collapse="true"}## SolutionTry the exercise on your own first, then compare with the worked solution below.```{python}# Solutiondef log_sum_exp(arr):""" Computes the logarithm of the sum of exponentiations of the input elements: Natural logarithm of the sum of exponentials (base e) """ exp_sum = np.sum(np.exp(arr)) log_sum_exp_base_e = np.log(exp_sum)return log_sum_exp_base_e# Example arrayarray = np.array([1, 2, 3])# Compute the log-sum-exp for the example arraylog_sum_exp_result = log_sum_exp(array)print(log_sum_exp_result)```:::