In [174]:
import sympy as symb
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
symb.init_printing()

In [175]:
x_1, x_2 = symb.symbols('x_1 x_2')

In [176]:
def grad(f):
    
    return symb.Matrix([f.diff(x_1),f.diff(x_2)]).T

In [177]:
f = (x_2 - 2 * x_1 + symb.exp(-x_1))** 2 + (x_1 - 2 * x_2 + symb.exp(-x_2))** 2
f


Out[177]:
$$\left(- 2 x_{1} + x_{2} + e^{- x_{1}}\right)^{2} + \left(x_{1} - 2 x_{2} + e^{- x_{2}}\right)^{2}$$

In [178]:
g = grad(f)
g


Out[178]:
$$\left[\begin{matrix}2 x_{1} - 4 x_{2} + \left(-4 - 2 e^{- x_{1}}\right) \left(- 2 x_{1} + x_{2} + e^{- x_{1}}\right) + 2 e^{- x_{2}} & - 4 x_{1} + 2 x_{2} + \left(-4 - 2 e^{- x_{2}}\right) \left(x_{1} - 2 x_{2} + e^{- x_{2}}\right) + 2 e^{- x_{1}}\end{matrix}\right]$$

In [179]:
f_numeric = symb.lambdify((x_1,x_2),f,'numpy')

In [180]:
f_numeric(1,1)


Out[180]:
$$0.799152801787$$

In [181]:
g_numeric = symb.lambdify((x_1,x_2),g,'numpy')
g


Out[181]:
$$\left[\begin{matrix}2 x_{1} - 4 x_{2} + \left(-4 - 2 e^{- x_{1}}\right) \left(- 2 x_{1} + x_{2} + e^{- x_{1}}\right) + 2 e^{- x_{2}} & - 4 x_{1} + 2 x_{2} + \left(-4 - 2 e^{- x_{2}}\right) \left(x_{1} - 2 x_{2} + e^{- x_{2}}\right) + 2 e^{- x_{1}}\end{matrix}\right]$$

In [182]:
g_numeric(1,1)


Out[182]:
matrix([[ 1.72932943,  1.72932943]])

In [183]:
X = np.arange(-2, 2, 0.1)
Y = np.arange(-2, 2, 0.1)
X, Y = np.meshgrid(X, Y)

X[0][0]


Out[183]:
$$-2.0$$

In [184]:
Z = f_numeric(X,Y)

In [184]:


In [185]:
def grad_numeric(x_1, x_2):
    
    comp_1 = 2 * x_1 - 4 * x_2 + 2 * np.exp(-x_2) + (-4 - 2 * np.exp(-x_1)) * (-2 * x_1 + x_2 + np.exp(-x_1)) 
    
    comp_2 = -4 * x_1 + 2 * x_2 + (-4 - 2 * np.exp(-x_2)) * (x_1 - 2 * x_2 + np.exp(-x_2)) + 2 * np.exp(-x_1)
    
    return np.array([comp_1,comp_2])

In [186]:
X_1 = grad_numeric(x,y)
x_sol = np.zeros((2,20))
alpha = .01

In [189]:
for i in xrange(10):
    
    x_sol[i] = x_sol[i+1] - alpha * X_1


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-189-ba3dbddccbf0> in <module>()
      1 for i in xrange(10):
      2 
----> 3     x_sol[i] = x_sol[i+1] - alpha * X_1

ValueError: could not broadcast input array from shape (2,20) into shape (20)

In [188]:
plt.scatter(x_sol[1,:],x_sol[0,:])


Out[188]:
<matplotlib.collections.PathCollection at 0x5eb8150>

In [192]:
f.diff(x_1,2)


Out[192]:
$$2 \left(\left(2 + e^{- x_{1}}\right)^{2} + \left(- 2 x_{1} + x_{2} + e^{- x_{1}}\right) e^{- x_{1}} + 1\right)$$

In [ ]: