# Домашнее задание "Производная функции нескольких аргументов".


```python
import numpy as np
from sympy import *
from scipy.optimize import approx_fprime
```

### Уровень 0:

Посчитайте частные производные функций:


1) $f(x,y)=2x^2y^3 + 1/x + y^2x + 7$, а для этой функции также градиент в точке $(1,2)$

2) $f(x,y)=x^2y - sin(xy) + cos(x^2) + 6y$


```python
x = symbols('x')
y = symbols('y')
```


```python
# first function
f = 2 * x**2 * y**3 + 1/x + y**2 * x + 7
```


```python
f1x = diff(f, x)
print(format(f1x))
```

    4*x*y**3 + y**2 - 1/x**2



```python
f1y = diff(f, y)
print(format(f1y))
```

    6*x**2*y**2 + 2*x*y



```python
# second function
f = x**2 * y - sin(x * y) + cos(x**2) + 6 * y
```


```python
f1x = diff(f, x)
print(format(f1x))
```

    2*x*y - 2*x*sin(x**2) - y*cos(x*y)



```python
f1y = diff(f, y)
print(format(f1y))
```

    x**2 - x*cos(x*y) + 6



```python
# gradient of the first function
def func(t):
    return 2 * t[0] ** 2 * t[1] ** 3 + 1 / t[0] + t[1] ** 2 * t[0] + 7


eps = np.sqrt(np.finfo(float).eps)
grad = approx_fprime([1, 2], func, [eps, eps])
print(grad)
```

    [35.00000024 28.00000024]


### Уровень 1:

Градиентный спуск своими руками:


```python
def f(t):
    return (t[0] ** 2) + (t[1] ** 2)
```


```python
x0 = np.array([100, 200])
learning_rate = 0.1
```


```python
eps = np.sqrt(np.finfo(float).eps)
x = x0
for i in range(100):
    # Calculate gradient
    grad = approx_fprime(x, f, [eps, eps])

    # Update x with gradient
    x = np.array([
        x[0] - learning_rate * grad[0],
        x[1] - learning_rate * grad[1]
    ])

print("Minimum is in: ", x)
print("Minimum value is: ", f(x))
```

    Minimum is in:  [1.29197811e-08 3.32901401e-08]
    Minimum value is:  1.2751541739575636e-15



Проверка с помощью встроенной функции numpy:


```python
from scipy.optimize import minimize

res = minimize(f, x0, method='nelder-mead', options={'xtol': 1e-8, 'disp': True})
print(res)
```

    Optimization terminated successfully.
             Current function value: 0.000000
             Iterations: 85
             Function evaluations: 164
     final_simplex: (array([[ 3.31391559e-09, -1.82888492e-09],
           [-3.91522747e-09, -3.79451217e-09],
           [-4.97134432e-09,  7.91645290e-09]]), array([1.43268566e-17, 2.97273287e-17, 8.73844908e-17]))
               fun: 1.4326856592347756e-17
           message: 'Optimization terminated successfully.'
              nfev: 164
               nit: 85
            status: 0
           success: True
                 x: array([ 3.31391559e-09, -1.82888492e-09])



```python

```

0f4be98d6d7222a4ac384092f6ebd21931e177ce
ipynb
Jupyter Notebook
HW_5.ipynb
seoSergio/mds-16
b6fe646fd7f63653261130aa37e38320c471b831
MIT
HW_5.ipynb
seoSergio/mds-16
b6fe646fd7f63653261130aa37e38320c471b831
MIT
HW_5.ipynb
seoSergio/mds-16
b6fe646fd7f63653261130aa37e38320c471b831
MIT
Qwen/Qwen-72B
1. YES
2. YES