Python: Gridsearch Without Machine Learning with example code?

In the context of machine learning, grid search is commonly used to find the best hyperparameters for a model. However, you can also use grid search to find optimal parameters or combinations for other types of algorithms or processes that require tuning. Here’s a simple example of using grid search without machine learning:

Let’s say you want to find the best combination of two numbers that gives the maximum result when multiplied. You’ll search over a grid of possible values for these two numbers to find the combination that produces the highest result.

import itertools

# Define the possible values for the two numbers
possible_values = [1, 2, 3, 4, 5]

# Initialize variables to store the best combination and result
best_combination = None
best_result = float('-inf') # Negative infinity

# Iterate over all possible combinations of the two numbers
for combo in itertools.product(possible_values, repeat=2):
num1, num2 = combo
result = num1 * num2

# Update the best combination and result if the current result is higher
if result > best_result:
best_combination = combo
best_result = result

print("Best Combination:", best_combination)
print("Best Result:", best_result)

In this example, itertools.product generates all possible combinations of the numbers from possible_values. For each combination, the product is calculated, and if it’s greater than the current best result, the best result and combination are updated.

This example demonstrates how grid search can be used to explore and find optimal parameters in a simple non-machine learning context. In practice, grid search is often used with machine learning models to find the best hyperparameters, leading to improved model performance.