Fit a statistical model using MLE with NumPy and SciPy
19. Maximum Likelihood Estimation with SciPy Optimize
Write a NumPy program to generate a set of data and fit a statistical model using SciPy's optimize module for maximum likelihood estimation (MLE).
Sample Solution:
Python Code:
Output:
Explanation:
- Import libraries:
- Import the necessary modules from NumPy, SciPy, and Matplotlib.
- Generate synthetic data:
- Create a sample dataset from a normal distribution using NumPy.
- Define the negative log-likelihood function:
- Define the function for the negative log-likelihood of a normal distribution.
- Initial guess:
- Provide an initial guess for the parameters (mean and standard deviation).
- Perform MLE:
- Use SciPy's minimize function with the L-BFGS-B method to find the parameters that minimize the negative log-likelihood.
- Extract parameters:
- Retrieve the estimated parameters (mean and standard deviation) from the result.
- Print results:
- Output the estimated parameters.
- Use Matplotlib to visualize the histogram of the data and the fitted normal distribution.
For more Practice: Solve these Related Problems:
- Write a Numpy program to generate a dataset from a known distribution and use SciPy's optimize.minimize to perform maximum likelihood estimation of its parameters.
- Write a Numpy program to fit a statistical model to data using SciPy's optimize module and compare the MLE results with method-of-moments estimates.
- Write a Numpy program to implement a custom log-likelihood function and optimize it with SciPy's optimize.minimize for parameter estimation.
- Write a Numpy program to perform maximum likelihood estimation on a dataset with outliers and compare the robustness of different loss functions using SciPy.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.Previous: Create a 2D grid and solve a PDE with NumPy and SciPy.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics