To analyze the progression of the objective function for each initial point across different optimization methods (Gradient Descent, Newton's Method, and BFGS) for your defined functions (func1, func2, and func3), you can enhance your existing code by incorporating visualization and detailed tracking of the function's values throughout the optimization process. Here's a comprehensive guide to achieve this:
1. Ensure Correct Storage of Function Progression Data
Your current implementation already stores the list of function values (f_list) for each iteration in the df_results DataFrame under the column "Lista de f". However, to facilitate easier analysis and visualization, it's beneficial to structure this data appropriately.
Recommendations:
- Use JSON Format for Storing Lists: Instead of saving lists as string representations in CSV files, consider storing them in JSON format to preserve their structure.
import json
# When saving to CSV
df_results['Lista de f'] = df_results['Lista de f'].apply(lambda x: json.dumps(x))
df_results.to_csv("Last.csv", index=False)
# When loading from CSV
df = pd.read_csv('Last.csv')
df['Lista de f'] = df['Lista de f'].apply(lambda x: json.loads(x))
2. Visualize Function Value Progression
Visualizing how the objective function's value changes over iterations provides intuitive insights into the convergence behavior of each optimization method.
a. Plotting Function Values Over Iterations for Each Run
You can create line plots showing the function value versus iteration number for each run of a method.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import json
# Load the results
df = pd.read_csv('Last.csv')
df['Lista de f'] = df['Lista de f'].apply(lambda x: json.loads(x)) # Convert string to list
def plot_progression(df, function_name, method_name):
subset = df[(df['Função utilizada'] == function_name) & (df['Método'] == method_name)]
plt.figure(figsize=(12, 8))
for idx, row in subset.iterrows():
f_values = row['Lista de f']
plt.plot(range(1, len(f_values) + 1), f_values, label=f'Run {idx + 1}')
plt.title(f'Function Value Progression for {function_name} using {method_name}')
plt.xlabel('Iteration')
plt.ylabel('Function Value')
plt.yscale('log') # Log scale for better visibility if values span several orders
plt.legend()
plt.grid(True)
plt.show()
# Example Usage:
plot_progression(df, 'func1', 'Gradiente')
plot_progression(df, 'func1', 'Newton')
plot_progression(df, 'func1', 'BFGS')
# Repeat for func2 and func3 as needed
b. Plotting Average Progression Across Runs
To compare methods more effectively, plot the average function value progression across multiple runs, along with confidence intervals.
import numpy as np
def plot_average_progression(df, function_name, method_name):
subset = df[(df['Função utilizada'] == function_name) & (df['Método'] == method_name)]
all_f_lists = [row['Lista de f'] for idx, row in subset.iterrows()]
# Determine the maximum number of iterations
max_iters = max(len(f) for f in all_f_lists)
# Pad shorter lists with the last value to align iterations
padded_f_lists = [f + [f[-1]]*(max_iters - len(f)) for f in all_f_lists]
f_matrix = np.array(padded_f_lists)
# Compute mean and standard deviation
mean_f = np.mean(f_matrix, axis=0)
std_f = np.std(f_matrix, axis=0)
iterations = range(1, max_iters + 1)
plt.figure(figsize=(12, 8))
plt.plot(iterations, mean_f, label=f'Mean {method_name}')
plt.fill_between(iterations, mean_f - std_f, mean_f + std_f, alpha=0.3)
plt.title(f'Average Function Value Progression for {function_name} using {method_name}')
plt.xlabel('Iteration')
plt.ylabel('Function Value')
plt.yscale('log')
plt.legend()
plt.grid(True)
plt.show()
# Example Usage:
plot_average_progression(df, 'func1', 'Gradiente')
plot_average_progression(df, 'func1', 'Newton')
plot_average_progression(df, 'func1', 'BFGS')
# Repeat for func2 and func3 as needed
3. Compare Methods Across Functions
Create comparative plots to analyze how different methods perform on the same function.
def compare_methods(df, function_name):
methods = df['Método'].unique()
plt.figure(figsize=(12, 8))
for method in methods:
subset = df[(df['Função utilizada'] == function_name) & (df['Método'] == method)]
all_f_lists = [row['Lista de f'] for idx, row in subset.iterrows()]
max_iters = max(len(f) for f in all_f_lists)
padded_f_lists = [f + [f[-1]]*(max_iters - len(f)) for f in all_f_lists]
f_matrix = np.array(padded_f_lists)
mean_f = np.mean(f_matrix, axis=0)
std_f = np.std(f_matrix, axis=0)
iterations = range(1, max_iters + 1)
plt.plot(iterations, mean_f, label=f'{method} Mean')
plt.fill_between(iterations, mean_f - std_f, mean_f + std_f, alpha=0.2)
plt.title(f'Comparison of Optimization Methods for {function_name}')
plt.xlabel('Iteration')
plt.ylabel('Function Value')
plt.yscale('log')
plt.legend()
plt.grid(True)
plt.show()
# Example Usage:
compare_methods(df, 'func1')
compare_methods(df, 'func2')
compare_methods(df, 'func3')
4. Analyze Convergence Metrics
Beyond visualizing the function value progression, analyzing specific convergence metrics can provide deeper insights.
a. Number of Iterations to Converge
Create a bar plot to compare the average number of iterations each method takes to converge.
def plot_iterations(df, function_name):
subset = df[df['Função utilizada'] == function_name]
plt.figure(figsize=(10, 6))
sns.boxplot(x='Método', y='# de iterações', data=subset)
plt.title(f'Number of Iterations to Converge for {function_name}')
plt.xlabel('Method')
plt.ylabel('Number of Iterations')
plt.yscale('log')
plt.grid(True)
plt.show()
# Example Usage:
plot_iterations(df, 'func1')
plot_iterations(df, 'func2')
plot_iterations(df, 'func3')
b. Distribution of Final Function Values
Use box plots or histograms to visualize the distribution of final function values obtained by each method.
def plot_final_values(df, function_name):
subset = df[df['Função utilizada'] == function_name]
plt.figure(figsize=(10, 6))
sns.boxplot(x='Método', y='Valor da função no ponto ótimo encontrado', data=subset)
plt.title(f'Distribution of Final Function Values for {function_name}')
plt.xlabel('Method')
plt.ylabel('Final Function Value')
plt.yscale('log')
plt.grid(True)
plt.show()
# Example Usage:
plot_final_values(df, 'func1')
plot_final_values(df, 'func2')
plot_final_values(df, 'func3')
5. Corrections and Improvements in Your Existing Code
There are a few areas in your current code that require corrections to ensure accurate data labeling and storage:
a. Correcting the "Método" Field for Newton and BFGS Armijo Entries
In your existing loop, Newton and BFGS methods incorrectly label the "Método" as "Gradiente" in the Armijo DataFrame. Here's how to fix it:
# Correct labels for Newton and BFGS Armijo entries
newton_armijo = {
"Método": "Newton",
"Total Armijo": newtonArmijoIterations,
"Média Armijo por Iteração": newtonArmijoIterations / newtonIterations,
}
bfgs_armijo = {
"Método": "BFGS",
"Total Armijo": bfgsArmijoIterations,
"Média Armijo por Iteração": bfgsArmijoIterations / bfgsIterations,
}
b. Streamlining DataFrame Concatenation
Instead of concatenating DataFrames in each iteration, consider collecting all records first and then creating the DataFrame in one go. This approach is more efficient.
# Initialize lists to collect records
results_records = []
armijo_records = []
for i in range(5):
# Example for func1
gradientX, gradientIterations, gradientArmijoIterations, gradientF, gradientFList, gradientErrors, GradientExecTime = GradientSearch(
func1, avaliar_gradiente_f1, initial_points_f1[i], 1e-5, 10000, 1, "time"
)
newtonX, newtonIterations, newtonArmijoIterations, newtonF, newtonFList, newtonErrors, newtonExecTime = NewtonSearch(
func1, avaliar_gradiente_f1, avaliar_hessiana_f1, initial_points_f1[i], 1e-5, 10000, 1, "time"
)
bfgsX, bfgsIterations, bfgsArmijoIterations, bfgsF, bfgsFList, bfgsErrors, bfgsExecTime = BFGS(
func1, avaliar_gradiente_f1, initial_points_f1[i], 1e-5, 10000, 1, "time"
)
# Collect Armijo data
armijo_records.extend([
{
"Método": "Gradiente",
"Total Armijo": gradientArmijoIterations,
"Média Armijo por Iteração": gradientArmijoIterations / gradientIterations,
},
{
"Método": "Newton",
"Total Armijo": newtonArmijoIterations,
"Média Armijo por Iteração": newtonArmijoIterations / newtonIterations,
},
{
"Método": "BFGS",
"Total Armijo": bfgsArmijoIterations,
"Média Armijo por Iteração": bfgsArmijoIterations / bfgsIterations,
},
])
# Collect result data
results_records.extend([
{
"Função utilizada": "func1",
"Ponto inicial": initial_points_f1[i],
"Método": "Gradiente",
"# de iterações": gradientIterations,
"# total de iterações da busca de Armijo": gradientArmijoIterations,
"Ponto ótimo encontrado": gradientX.tolist(),
"Valor da função no ponto ótimo encontrado": gradientF,
"Erro de aproximação": np.linalg.norm(avaliar_gradiente_f1(gradientX)),
"Lista de f": gradientFList,
"Razão de erros": gradientErrors,
"Tempo de execução": GradientExecTime
},
{
"Função utilizada": "func1",
"Ponto inicial": initial_points_f1[i],
"Método": "Newton",
"# de iterações": newtonIterations,
"# total de iterações da busca de Armijo": newtonArmijoIterations,
"Ponto ótimo encontrado": newtonX.tolist(),
"Valor da função no ponto ótimo encontrado": newtonF,
"Erro de aproximação": np.linalg.norm(avaliar_gradiente_f1(newtonX)),
"Lista de f": newtonFList,
"Razão de erros": newtonErrors,
"Tempo de execução": newtonExecTime
},
{
"Função utilizada": "func1",
"Ponto inicial": initial_points_f1[i],
"Método": "BFGS",
"# de iterações": bfgsIterations,
"# total de iterações da busca de Armijo": bfgsArmijoIterations,
"Ponto ótimo encontrado": bfgsX.tolist(),
"Valor da função no ponto ótimo encontrado": bfgsF,
"Erro de aproximação": np.linalg.norm(avaliar_gradiente_f1(bfgsX)),
"Lista de f": bfgsFList,
"Razão de erros": bfgsErrors,
"Tempo de execução": bfgsExecTime
}
])
# After loops, create DataFrames
df_results = pd.DataFrame(results_records)
df_armijo = pd.DataFrame(armijo_records)
# Save to files
df_results.to_csv("Last.csv", index=False)
df_armijo.to_csv("Armijo.csv", index=False)
c. Handling Data Types Appropriately
Ensure that when storing lists (like "Ponto ótimo encontrado"), they are converted to a serializable format (e.g., lists or JSON strings) to prevent issues during saving and loading.
# Convert NumPy arrays to lists before storing
"Ponto ótimo encontrado": gradientX.tolist()
6. Advanced Analysis: Convergence Rate and Efficiency
To gain deeper insights into the efficiency and convergence rates of each method, consider the following analyses:
a. Convergence Rate
Calculate how quickly each method reduces the function value relative to the number of iterations.
def plot_convergence_rate(df, function_name):
subset = df[df['Função utilizada'] == function_name]
plt.figure(figsize=(12, 8))
for method in subset['Método'].unique():
method_data = subset[subset['Método'] == method]
total_iters = method_data['# de iterações']
final_f = method_data['Valor da função no ponto ótimo encontrado']
plt.scatter(total_iters, final_f, label=method, alpha=0.7)
plt.title(f'Convergence Rate for {function_name}')
plt.xlabel('Number of Iterations')
plt.ylabel('Final Function Value')
plt.yscale('log')
plt.xscale('linear')
plt.legend()
plt.grid(True)
plt.show()
# Example Usage:
plot_convergence_rate(df, 'func1')
plot_convergence_rate(df, 'func2')
plot_convergence_rate(df, 'func3')
b. Efficiency Analysis Based on Execution Time
Compare how much computational time each method takes relative to the achieved function value.
def plot_efficiency(df, function_name):
subset = df[df['Função utilizada'] == function_name]
plt.figure(figsize=(12, 8))
sns.scatterplot(x='Tempo de execução', y='Valor da função no ponto ótimo encontrado', hue='Método', data=subset, s=100)
plt.title(f'Efficiency Analysis for {function_name}')
plt.xlabel('Execution Time (seconds)')
plt.ylabel('Final Function Value')
plt.yscale('log')
plt.xscale('log')
plt.legend()
plt.grid(True)
plt.show()
# Example Usage:
plot_efficiency(df, 'func1')
plot_efficiency(df, 'func2')
plot_efficiency(df, 'func3')
7. Final Remarks and Best Practices
-
Consistent Data Handling: Ensure that all numerical data is consistently formatted and correctly typed, especially when dealing with lists and arrays.
-
Avoid Using eval When Possible: While eval can convert strings back to lists, it's safer to use structured formats like JSON to handle such data.
-
Optimize Data Storage: For large-scale experiments, consider using more efficient data storage solutions (like HDF5) instead of CSV for better performance and scalability.
-
Enhance Visualization: Depending on the number of runs and data points, you might need to adjust plot aesthetics (like transparency and color palettes) to maintain clarity.
-
Document and Comment Code: Clearly comment your code to indicate the purpose of each section, which aids in maintenance and future upgrades.
By incorporating these visualization and analysis techniques, you'll be able to comprehensively understand and compare the performance and convergence behavior of different optimization methods across various functions and initial points.