Data Science Machine Learning Data Analysis
37.9K subscribers
2.79K photos
30 videos
39 files
1.26K links
This channel is for Programmers, Coders, Software Engineers.

1- Data Science
2- Machine Learning
3- Data Visualization
4- Artificial Intelligence
5- Data Analysis
6- Statistics
7- Deep Learning

Cross promotion and ads: @hussein_sheikho
Download Telegram
Topic: Python SciPy – From Easy to Top: Part 3 of 6: Optimization Basics

---

1. What is Optimization?

• Optimization is the process of finding the minimum or maximum of a function.

• SciPy provides tools to solve these problems efficiently.

---

2. Using `scipy.optimize.minimize`

This function minimizes a scalar function of one or more variables.

Example: Minimize the function f(x) = (x - 3)^2

from scipy import optimize

def f(x):
return (x - 3)**2

result = optimize.minimize(f, x0=0)
print("Minimum value:", result.fun)
print("At x =", result.x)


---

**3. Minimizing Multivariable Functions**

Example: Minimize f(x, y) = (x - 2)^2 + (y + 3)^2

def f(vars):
x, y = vars
return (x - 2)**2 + (y + 3)**2

result = optimize.minimize(f, x0=[0, 0])
print("Minimum value:", result.fun)
print("At x, y =", result.x)


---

**4. Using Bounds and Constraints**

You can restrict the variables within bounds or constraints.

Example: Minimize f(x) = (x - 3)^2 with x between 0 and 5

result = optimize.minimize(f, x0=0, bounds=[(0, 5)])
print("Minimum with bounds:", result.fun)
print("At x =", result.x)


---

5. Root Finding with `optimize.root_scalar`

Find a root of a scalar function.

Example: Find root of f(x) = x^3 - 1 between 0 and 2

def f(x):
return x**3 - 1

root = optimize.root_scalar(f, bracket=[0, 2])
print("Root:", root.root)


---

6. Summary

• SciPy’s optimization tools help find minima, maxima, and roots.

• Supports single and multivariable problems with constraints.

---

Exercise

• Minimize the function f(x) = x^4 - 3x^3 + 2 over the range \[-2, 3].

• Find the root of f(x) = cos(x) - x near x=1.

---

#Python #SciPy #Optimization #RootFinding #ScientificComputing

https://t.iss.one/DataScienceM
3