![]() |
VOOZH | about |
SciPy is a Python library that is available for free and open source and is used for technical and scientific computing. It is a set of useful functions and mathematical methods created using Python's NumPy module.
Packages | Description |
File input/output | |
Special Function(airy, elliptic, bessel, gamma, beta, etc) | |
Linear Algebra Operation | |
Interpolation | |
Optimization and fit | |
Statistics and random numbers | |
Numerical Integration | |
Fast Fourier transforms | |
Signal Processing | |
Image manipulation |
In this article, we will learn the scipy.optimize sub-package.
This package includes functions for minimizing and maximizing objective functions subject to given constraints. Let's understand this package with the help of examples.
func : callable
The function whose root is required. It must be a function of a single variable of the form f(x, a, b, c, . . . ), where a, b, c, . . . are extra arguments that can be passed in the args parameter.
x0 : float, sequence, or ndarray
Initial point from where you want to find the root of the function. It will somewhere near the actual root. Our initial guess is 0.
Find the smallest positive root of the function f(x) = x3 - 2x + 0.5 .
Import the optimize.newton package using the below command. Newton package contains a function that will calculate the root using the Newton Raphson method. Define a function for the given objective function. Use the newton function. This function will return the result object which contains the smallest positive root for the given function f1.
Output:
0.25865202250415226
Maximize: Z = 5x + 4y
Constraints:
- 2y ≤ 50
- x + 2y ≤ 25
- x + y ≤ 15
- x ≥ 0 and y ≥ 0
Import the optimize.linprog module using the following command. Create an array of the objective function's coefficients. Before that convert the objective function in minimization form by multiplying it with a negative sign in the equation. Now create the two arrays for the constraints equations. One array will be for left-hand equations and the second array for right-hand side values.
Use the linprog inbuilt function and pass the arrays that we have created an addition mention the method.
Output:
con: array([], dtype=float64) crossover_nit: 0 eqlin: marginals: array([], dtype=float64) residual: array([], dtype=float64) fun: -75.0 ineqlin: marginals: array([-0., -0., -5.]) residual: array([50., 10., 0.]) lower: marginals: <MemoryView of 'ndarray' at 0x7f41289de040> residual: array([15., 0.]) message: 'Optimization terminated successfully.' nit: 1 slack: array([50., 10., 0.]) status: 0 success: True upper: marginals: <MemoryView of 'ndarray' at 0x7f4128a56d40> residual: array([inf, inf]) x: array([15., 0.])
This function will return an object that contains the optimal answer for the given problem.
A city corporation has decided to carry out road repairs on main four arteries of the city. The government has agreed to make a special grant of Rs. 50 lakh towards the cost with a condition that repairs are done at the lowest cost and quickest time. If the conditions warrant, a supplementary token grant will also be considered favourably. The corporation has floated tenders and five contractors have sent in their bids. In order to expedite work, one road will be awarded to only one contractor.
Cost of Repairs ( Rs in lakh) Contractors R1 R2 R3 R4 R5 C1 9 14 19 15 13 C2 7 17 20 19 18 C3 8 18 21 18 17 C4 10 12 18 19 18 C5 10 15 21 16 15 Find the best way of assigning the repair work to the contractors and the costs. If it is necessary to seek supplementary grants,what should be the amount sought?
In this code, we required the NumPy array so first install the NumPy module and then import the required modules. Create a multidimensional NumPy array of given data. Use the optimize.linear_sum_assignment() function. This function returns two NumPy arrays (Optimal solution) - one is the row ( Contactors) and the second is the column ( Corresponding Repair Cost).
Use the sum() function and calculate the total minimum optimal cost.
Output:
[0 1 2 3 4] [4 0 2 1 3] 69
How the assignment will be done can be concluded below from the obtained data.
Hence Final Minimal cost will be,
13 + 7 + 21 + 12 + 16 = Rs. 69 lakh.
This algorithm deals with the Minimization of a scalar function of one or more variables. The BFGS algorithm is one of the most widely used second-order algorithms for numerical optimization, and it is frequently used to fit machine learning algorithms such as the logistic regression algorithm.
Objective Function:
- z = sin( X ) + cos( Y )
Output:
fun: -0.999999999999904 hess_inv: array([[ 1.01409071, -0.00302069], [-0.00302069, 1.00066793]]) jac: array([-4.24683094e-07, 9.68575478e-08]) message: 'Optimization terminated successfully.' nfev: 24 nit: 6 njev: 8 status: 0 success: True x: array([ 1.5707959 , -3.14159257])
Curve fitting requires that you define the function that maps examples of inputs to outputs like Machine Learning supervised learning. The mapping function can have a straight line (Linear Regression), a Curve line (Polynomial Regression), and much more. A detailed GeeksForGeeks article on Scipy Curve_fit is available here SciPy | Curve Fitting.
Output:
[16.45191102 0.14955689] [[1.74663622e+00 1.19187398e-02] [1.19187398e-02 2.52349161e-04]]
Non-linear optimization with no constraint and there is only one decision variable in this optimization that we are trying to find a value for.
Output:
fun: -9.481481481481376 message: 'Solution found.' nfev: 12 status: 0 success: True x: 0.6666668296237073
Noisy Optimization Problem - A noisy objective function is a function that gives different answers each time the same input is evaluated.
Output:
final_simplex: (array([[0.52539082], [0.52539063]]), array([6.79569941e-07, 9.02524100e-05])) fun: 6.795699413959474e-07 message: 'Optimization terminated successfully.' nfev: 47 nit: 18 status: 0 success: True x: array([0.52539082])