I have three functions that I need to calculate the derivatives of. I'm now using a python library for that, but I want to implement the hessian and gradient calculations by my own: def func1(x):
return sum(100 * (x[i+1] - x[i]**2)**2 + (1 - x[i])**2 for i in range(len(x) - 1))
def func2(x):
return sum(x_i4 - 16 * x_i2 + 5 * x_i for x_i in x)
def calcular_gradiente_hessiana_simbolico(func_symbolic, num_vars):
# Definir as variáveis simbólicas
vars = sp.symbols(f'x0:{num_vars}')
code
# Calcular o gradiente
gradiente = [sp.diff(func_symbolic(vars), var) for var in vars]
# Calcular a matriz Hessiana
hessiana = [[sp.diff(grad, var) for var in vars] for grad in gradiente]
return gradiente, hessiana, vars
It looks like you're attempting to calculate the symbolic gradients and Hessians of your functions (func1, func2, and func3) using SymPy in Python, and then lambdify them for numerical evaluations.
Your approach is generally correct, but there are a few issues that might prevent your code from working as intended. I'll guide you through the necessary steps to properly compute and utilize the gradients and Hessians for your functions.
1. Understanding the Functions
Let's first understand the functions you're dealing with:
func1: A variant of the Rosenbrock function, a common test function for optimization algorithms.
python
def func1(x):
return sum(100 * (x[i+1] - x[i]**2)**2 + (1 - x[i])**2 for i in range(len(x) - 1))
func2: A quartic function defined over all elements in x.
python
def func2(x):
return sum(x_i**4 - 16 * x_i**2 + 5 * x_i for x_i in x)
func3: Himmelblau's function, a multi-modal function used to test optimization algorithms.
The primary issue with your code is that the functions func1, func2, and func3 are designed for numerical computations—they expect x to be a list or NumPy array of numbers. However, for symbolic computations with SymPy, x needs to be a list of symbolic variables.
When you pass vars (a tuple of symbolic variables) to func_symbolic(vars), the functions must handle symbolic arithmetic.
3. Adjusting the Functions for Symbolic Computation
To fix this, ensure that your functions can handle symbolic inputs. You might need to adjust them slightly:
Ensure that indexing and operations are compatible with symbolic variables.
Convert x to a SymPy Matrix or list if necessary.
4. Revised Code
Here's the adjusted code with explanations:
python
import sympy as sp
import numpy as np
from sympy.utilities.lambdify import lambdify
# Adjusted functions to work with symbolic variables
def func1(x):
# x should be a list or tuple of symbolic variables
return sum(100 * (x[i+1] - x[i]**2)**2 + (1 - x[i])**2 for i in range(len(x) - 1))
def func2(x):
# x can be a list of symbolic variables
return sum(x_i**4 - 16 * x_i**2 + 5 * x_i for x_i in x)
def func3(x):
x1, x2 = x[0], x[1]
return (x1**2 + x2 - 11)**2 + (x1 + x2**2 - 7)**2
def calcular_gradiente_hessiana_simbolico(func_symbolic, num_vars):
# Define the symbolic variables as a list
vars = sp.symbols(f'x0:{num_vars}')
vars_list = list(vars)
# Compute the symbolic function expression
func_expr = func_symbolic(vars_list)
# Compute the gradient vector
gradiente = [sp.diff(func_expr, var) for var in vars_list]
# Compute the Hessian matrix
hessiana = [[sp.diff(grad, var2) for var2 in vars_list] for grad in gradiente]
return gradiente, hessiana, vars_list
# Compute and store symbolic gradients and Hessians
gradientes_simbolicos = {}
hessianas_simbolicas = {}
vars_simbolicas = {}
# For func1
gradientes_simbolicos['func1'], hessianas_simbolicas['func1'], vars_simbolicas['func1'] = \
calcular_gradiente_hessiana_simbolico(func1, 7)
# For func2
gradientes_simbolicos['func2'], hessianas_simbolicas['func2'], vars_simbolicas['func2'] = \
calcular_gradiente_hessiana_simbolico(func2, 100)
# For func3
gradientes_simbolicos['func3'], hessianas_simbolicas['func3'], vars_simbolicas['func3'] = \
calcular_gradiente_hessiana_simbolico(func3, 2)
# Lambdify the gradients and Hessians
gradiente_f1_lambdified = lambdify(vars_simbolicas['func1'], gradientes_simbolicos['func1'], modules='numpy')
gradiente_f2_lambdified = lambdify(vars_simbolicas['func2'], gradientes_simbolicos['func2'], modules='numpy')
gradiente_f3_lambdified = lambdify(vars_simbolicas['func3'], gradientes_simbolicos['func3'], modules='numpy')
hessiana_f1_lambdified = lambdify(vars_simbolicas['func1'], hessianas_simbolicas['func1'], modules='numpy')
hessiana_f2_lambdified = lambdify(vars_simbolicas['func2'], hessianas_simbolicas['func2'], modules='numpy')
hessiana_f3_lambdified = lambdify(vars_simbolicas['func3'], hessianas_simbolicas['func3'], modules='numpy')
5. Testing the Lambdified Functions
Now, you can test the lambdified functions with numerical inputs:
python
# Example input for func1
x_test_func1 = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
# Evaluate gradient and Hessian at the test point
gradient_f1 = gradiente_f1_lambdified(*x_test_func1)
hessian_f1 = hessiana_f1_lambdified(*x_test_func1)
print("Gradient of func1 at x_test_func1:")
print(gradient_f1)
print("\nHessian of func1 at x_test_func1:")
print(hessian_f1)
Important Notes:
Unpacking Arguments: When calling the lambdified functions, use *x_test_func1 to unpack the array since the functions expect individual arguments for each variable.
Output Formats: The outputs gradient_f1 and hessian_f1 will be lists of NumPy arrays. You may need to convert them into arrays or matrices for further computations.
6. Handling Large Numbers of Variables
For func2, which uses 100 variables, symbolic computation can be resource-intensive. If you encounter performance issues:
Consider Numerical Approximations: Use numerical methods for gradient and Hessian approximation, such as finite differences.
Use Automatic Differentiation Libraries: Libraries like Autograd, TensorFlow, or PyTorch support automatic differentiation and can handle larger-scale problems more efficiently.
7. Checking the Results
Ensure that the computed gradients and Hessians are correct:
Compare with Numerical Gradients: Use numerical methods to compute the gradient and Hessian at a test point and compare them with your symbolic results.
Verify Dimensions: The gradient should be a vector of length num_vars, and the Hessian should be a num_vars x num_vars matrix.
8. Full Example for func3
Here's a complete example for func3:
python
# Example input for func3
x_test_func3 = np.array([3.0, 2.0])
# Evaluate gradient and Hessian at the test point
gradient_f3 = gradiente_f3_lambdified(*x_test_func3)
hessian_f3 = hessiana_f3_lambdified(*x_test_func3)
print("Gradient of func3 at x_test_func3:")
print(gradient_f3)
print("\nHessian of func3 at x_test_func3:")
print(np.array(hessian_f3))
9. Final Remarks
By adjusting your functions to handle symbolic variables and ensuring that the lambdified functions are called with the correct arguments, you should be able to compute and use the gradients and Hessians as intended.
If you have any further questions or encounter any issues, feel free to ask for additional assistance!