Machine Learning
38.9K subscribers
3.72K photos
31 videos
40 files
1.29K links
Machine learning insights, practical tutorials, and clear explanations for beginners and aspiring data scientists. Follow the channel for models, algorithms, coding guides, and real-world ML applications.

Admin: @HusseinSheikho
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