Skip to content
Advertisement

How to obtain the values of provided data in which a minimum value occurs in a list?

So I’ve been trying to select 2 parameters as a result in which the minimum value occurs in another calculation (the error below). Consider the following dummy code for better understanding:

def min_error(par1, par2):
    
    output = {"parameters": {"par1": [], "par2": []}, 
                             "error": []
             }

    for i in par1:
        for j in par2:            
            reg = somefunction(par1 = i, par2 = j)         
            error = abs(ymax-ymin) #This returns a list of calculated errors
            output["parameters"]["par1"].append(i)
            output["parameters"]["par2"].append(j)
            output["error"].append(error)

    return output

When calling the function defined min_error(par1, par2); par1 and par2 are lists so my nested for loop is going to append multiple values in the output dictionary.

At this point the code returns a dictionary with 3 lists but what I’m looking for is that out of all the errors calculated, choose the minimum error and the two parameters par1, par2 from the list provided by the user that cause that minimum error and assign it to the output dictionary so that it returns only something like…

{'parameters': {'par1': 10,
                'par2': 0.11,
                'error': 9.83}

…instead of obtaining the full list. Just the minimum error and the parameters that cause the minimum error should be the actual result from it.

Is tried using an if statement similar to:

 if output["error"] == min(error):
     output["parameters"]["par1"][i]
     output["parameters"]["par2"][j]
     output["error"]

…but I don’t know how to link that minimum value to the values in par1 and par2 that made that possible. Any help is very appreciated! Thanks

Advertisement

Answer

If I understand you correctly, you want to transform the output dictionary to one with "hyperparameters" key and minimal error (you can use min() built-in function for that).

For example, if you have

output = {
    "parameters": {"par1": [1, 2, 3], "par2": [4, 5, 6]},
    "error": [10, 0, 20],
}

Then:

out = dict(
    hyperparameters=dict(
        zip(
            ("par1", "par2", "error"),
            min(
                zip(
                    output["parameters"]["par1"],
                    output["parameters"]["par2"],
                    output["error"],
                ),
                key=lambda i: i[2],
            ),
        )
    )
)

print(out)

Prints:

{
    "hyperparameters": {
        "par1": 2, 
        "par2": 5, 
        "error": 0
    }
}

Or:

p1, p2, e = min(
    zip(
        output["parameters"]["par1"],
        output["parameters"]["par2"],
        output["error"],
    ),
    key=lambda i: i[2],
)

d = {"par1": p1, "par2": p2, "error": e}
print(d)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement